Amar-Aly commited on
Commit
51c6456
·
verified ·
1 Parent(s): ee78fba

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/__init__.py +39 -0
  2. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection.py +222 -0
  3. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection_pool.py +420 -0
  4. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http11.py +379 -0
  5. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http2.py +592 -0
  6. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http_proxy.py +367 -0
  7. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/interfaces.py +137 -0
  8. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/socks_proxy.py +341 -0
  9. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/__init__.py +0 -0
  10. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/anyio.py +146 -0
  11. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/auto.py +52 -0
  12. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/base.py +101 -0
  13. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/mock.py +143 -0
  14. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/sync.py +241 -0
  15. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/trio.py +159 -0
  16. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/__init__.py +39 -0
  17. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection.py +222 -0
  18. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection_pool.py +420 -0
  19. .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/http11.py +379 -0
  20. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/METADATA +107 -0
  21. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/RECORD +24 -0
  22. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/WHEEL +4 -0
  23. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE +3 -0
  24. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.APACHE +177 -0
  25. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.BSD +23 -0
  26. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/__init__.py +15 -0
  27. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_elffile.py +108 -0
  28. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_manylinux.py +262 -0
  29. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_musllinux.py +85 -0
  30. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_parser.py +365 -0
  31. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_structures.py +69 -0
  32. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_tokenizer.py +193 -0
  33. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/__init__.py +147 -0
  34. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/_spdx.py +799 -0
  35. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/markers.py +388 -0
  36. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/metadata.py +978 -0
  37. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/py.typed +0 -0
  38. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/pylock.py +635 -0
  39. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/requirements.py +86 -0
  40. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/specifiers.py +1068 -0
  41. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/tags.py +651 -0
  42. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/utils.py +158 -0
  43. .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/version.py +792 -0
  44. .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/METADATA +412 -0
  45. .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/RECORD +22 -0
  46. .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/WHEEL +4 -0
  47. .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/entry_points.txt +5 -0
  48. .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/licenses/LICENSE +21 -0
  49. .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__init__.py +39 -0
  50. .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__main__.py +3 -0
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .connection import AsyncHTTPConnection
2
+ from .connection_pool import AsyncConnectionPool
3
+ from .http11 import AsyncHTTP11Connection
4
+ from .http_proxy import AsyncHTTPProxy
5
+ from .interfaces import AsyncConnectionInterface
6
+
7
+ try:
8
+ from .http2 import AsyncHTTP2Connection
9
+ except ImportError: # pragma: nocover
10
+
11
+ class AsyncHTTP2Connection: # type: ignore
12
+ def __init__(self, *args, **kwargs) -> None: # type: ignore
13
+ raise RuntimeError(
14
+ "Attempted to use http2 support, but the `h2` package is not "
15
+ "installed. Use 'pip install httpcore[http2]'."
16
+ )
17
+
18
+
19
+ try:
20
+ from .socks_proxy import AsyncSOCKSProxy
21
+ except ImportError: # pragma: nocover
22
+
23
+ class AsyncSOCKSProxy: # type: ignore
24
+ def __init__(self, *args, **kwargs) -> None: # type: ignore
25
+ raise RuntimeError(
26
+ "Attempted to use SOCKS support, but the `socksio` package is not "
27
+ "installed. Use 'pip install httpcore[socks]'."
28
+ )
29
+
30
+
31
+ __all__ = [
32
+ "AsyncHTTPConnection",
33
+ "AsyncConnectionPool",
34
+ "AsyncHTTPProxy",
35
+ "AsyncHTTP11Connection",
36
+ "AsyncHTTP2Connection",
37
+ "AsyncConnectionInterface",
38
+ "AsyncSOCKSProxy",
39
+ ]
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import logging
5
+ import ssl
6
+ import types
7
+ import typing
8
+
9
+ from .._backends.auto import AutoBackend
10
+ from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
11
+ from .._exceptions import ConnectError, ConnectTimeout
12
+ from .._models import Origin, Request, Response
13
+ from .._ssl import default_ssl_context
14
+ from .._synchronization import AsyncLock
15
+ from .._trace import Trace
16
+ from .http11 import AsyncHTTP11Connection
17
+ from .interfaces import AsyncConnectionInterface
18
+
19
+ RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc.
20
+
21
+
22
+ logger = logging.getLogger("httpcore.connection")
23
+
24
+
25
+ def exponential_backoff(factor: float) -> typing.Iterator[float]:
26
+ """
27
+ Generate a geometric sequence that has a ratio of 2 and starts with 0.
28
+
29
+ For example:
30
+ - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...`
31
+ - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...`
32
+ """
33
+ yield 0
34
+ for n in itertools.count():
35
+ yield factor * 2**n
36
+
37
+
38
+ class AsyncHTTPConnection(AsyncConnectionInterface):
39
+ def __init__(
40
+ self,
41
+ origin: Origin,
42
+ ssl_context: ssl.SSLContext | None = None,
43
+ keepalive_expiry: float | None = None,
44
+ http1: bool = True,
45
+ http2: bool = False,
46
+ retries: int = 0,
47
+ local_address: str | None = None,
48
+ uds: str | None = None,
49
+ network_backend: AsyncNetworkBackend | None = None,
50
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
51
+ ) -> None:
52
+ self._origin = origin
53
+ self._ssl_context = ssl_context
54
+ self._keepalive_expiry = keepalive_expiry
55
+ self._http1 = http1
56
+ self._http2 = http2
57
+ self._retries = retries
58
+ self._local_address = local_address
59
+ self._uds = uds
60
+
61
+ self._network_backend: AsyncNetworkBackend = (
62
+ AutoBackend() if network_backend is None else network_backend
63
+ )
64
+ self._connection: AsyncConnectionInterface | None = None
65
+ self._connect_failed: bool = False
66
+ self._request_lock = AsyncLock()
67
+ self._socket_options = socket_options
68
+
69
+ async def handle_async_request(self, request: Request) -> Response:
70
+ if not self.can_handle_request(request.url.origin):
71
+ raise RuntimeError(
72
+ f"Attempted to send request to {request.url.origin} on connection to {self._origin}"
73
+ )
74
+
75
+ try:
76
+ async with self._request_lock:
77
+ if self._connection is None:
78
+ stream = await self._connect(request)
79
+
80
+ ssl_object = stream.get_extra_info("ssl_object")
81
+ http2_negotiated = (
82
+ ssl_object is not None
83
+ and ssl_object.selected_alpn_protocol() == "h2"
84
+ )
85
+ if http2_negotiated or (self._http2 and not self._http1):
86
+ from .http2 import AsyncHTTP2Connection
87
+
88
+ self._connection = AsyncHTTP2Connection(
89
+ origin=self._origin,
90
+ stream=stream,
91
+ keepalive_expiry=self._keepalive_expiry,
92
+ )
93
+ else:
94
+ self._connection = AsyncHTTP11Connection(
95
+ origin=self._origin,
96
+ stream=stream,
97
+ keepalive_expiry=self._keepalive_expiry,
98
+ )
99
+ except BaseException as exc:
100
+ self._connect_failed = True
101
+ raise exc
102
+
103
+ return await self._connection.handle_async_request(request)
104
+
105
+ async def _connect(self, request: Request) -> AsyncNetworkStream:
106
+ timeouts = request.extensions.get("timeout", {})
107
+ sni_hostname = request.extensions.get("sni_hostname", None)
108
+ timeout = timeouts.get("connect", None)
109
+
110
+ retries_left = self._retries
111
+ delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
112
+
113
+ while True:
114
+ try:
115
+ if self._uds is None:
116
+ kwargs = {
117
+ "host": self._origin.host.decode("ascii"),
118
+ "port": self._origin.port,
119
+ "local_address": self._local_address,
120
+ "timeout": timeout,
121
+ "socket_options": self._socket_options,
122
+ }
123
+ async with Trace("connect_tcp", logger, request, kwargs) as trace:
124
+ stream = await self._network_backend.connect_tcp(**kwargs)
125
+ trace.return_value = stream
126
+ else:
127
+ kwargs = {
128
+ "path": self._uds,
129
+ "timeout": timeout,
130
+ "socket_options": self._socket_options,
131
+ }
132
+ async with Trace(
133
+ "connect_unix_socket", logger, request, kwargs
134
+ ) as trace:
135
+ stream = await self._network_backend.connect_unix_socket(
136
+ **kwargs
137
+ )
138
+ trace.return_value = stream
139
+
140
+ if self._origin.scheme in (b"https", b"wss"):
141
+ ssl_context = (
142
+ default_ssl_context()
143
+ if self._ssl_context is None
144
+ else self._ssl_context
145
+ )
146
+ alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"]
147
+ ssl_context.set_alpn_protocols(alpn_protocols)
148
+
149
+ kwargs = {
150
+ "ssl_context": ssl_context,
151
+ "server_hostname": sni_hostname
152
+ or self._origin.host.decode("ascii"),
153
+ "timeout": timeout,
154
+ }
155
+ async with Trace("start_tls", logger, request, kwargs) as trace:
156
+ stream = await stream.start_tls(**kwargs)
157
+ trace.return_value = stream
158
+ return stream
159
+ except (ConnectError, ConnectTimeout):
160
+ if retries_left <= 0:
161
+ raise
162
+ retries_left -= 1
163
+ delay = next(delays)
164
+ async with Trace("retry", logger, request, kwargs) as trace:
165
+ await self._network_backend.sleep(delay)
166
+
167
+ def can_handle_request(self, origin: Origin) -> bool:
168
+ return origin == self._origin
169
+
170
+ async def aclose(self) -> None:
171
+ if self._connection is not None:
172
+ async with Trace("close", logger, None, {}):
173
+ await self._connection.aclose()
174
+
175
+ def is_available(self) -> bool:
176
+ if self._connection is None:
177
+ # If HTTP/2 support is enabled, and the resulting connection could
178
+ # end up as HTTP/2 then we should indicate the connection as being
179
+ # available to service multiple requests.
180
+ return (
181
+ self._http2
182
+ and (self._origin.scheme == b"https" or not self._http1)
183
+ and not self._connect_failed
184
+ )
185
+ return self._connection.is_available()
186
+
187
+ def has_expired(self) -> bool:
188
+ if self._connection is None:
189
+ return self._connect_failed
190
+ return self._connection.has_expired()
191
+
192
+ def is_idle(self) -> bool:
193
+ if self._connection is None:
194
+ return self._connect_failed
195
+ return self._connection.is_idle()
196
+
197
+ def is_closed(self) -> bool:
198
+ if self._connection is None:
199
+ return self._connect_failed
200
+ return self._connection.is_closed()
201
+
202
+ def info(self) -> str:
203
+ if self._connection is None:
204
+ return "CONNECTION FAILED" if self._connect_failed else "CONNECTING"
205
+ return self._connection.info()
206
+
207
+ def __repr__(self) -> str:
208
+ return f"<{self.__class__.__name__} [{self.info()}]>"
209
+
210
+ # These context managers are not used in the standard flow, but are
211
+ # useful for testing or working with connection instances directly.
212
+
213
+ async def __aenter__(self) -> AsyncHTTPConnection:
214
+ return self
215
+
216
+ async def __aexit__(
217
+ self,
218
+ exc_type: type[BaseException] | None = None,
219
+ exc_value: BaseException | None = None,
220
+ traceback: types.TracebackType | None = None,
221
+ ) -> None:
222
+ await self.aclose()
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection_pool.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ssl
4
+ import sys
5
+ import types
6
+ import typing
7
+
8
+ from .._backends.auto import AutoBackend
9
+ from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend
10
+ from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol
11
+ from .._models import Origin, Proxy, Request, Response
12
+ from .._synchronization import AsyncEvent, AsyncShieldCancellation, AsyncThreadLock
13
+ from .connection import AsyncHTTPConnection
14
+ from .interfaces import AsyncConnectionInterface, AsyncRequestInterface
15
+
16
+
17
+ class AsyncPoolRequest:
18
+ def __init__(self, request: Request) -> None:
19
+ self.request = request
20
+ self.connection: AsyncConnectionInterface | None = None
21
+ self._connection_acquired = AsyncEvent()
22
+
23
+ def assign_to_connection(self, connection: AsyncConnectionInterface | None) -> None:
24
+ self.connection = connection
25
+ self._connection_acquired.set()
26
+
27
+ def clear_connection(self) -> None:
28
+ self.connection = None
29
+ self._connection_acquired = AsyncEvent()
30
+
31
+ async def wait_for_connection(
32
+ self, timeout: float | None = None
33
+ ) -> AsyncConnectionInterface:
34
+ if self.connection is None:
35
+ await self._connection_acquired.wait(timeout=timeout)
36
+ assert self.connection is not None
37
+ return self.connection
38
+
39
+ def is_queued(self) -> bool:
40
+ return self.connection is None
41
+
42
+
43
+ class AsyncConnectionPool(AsyncRequestInterface):
44
+ """
45
+ A connection pool for making HTTP requests.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ ssl_context: ssl.SSLContext | None = None,
51
+ proxy: Proxy | None = None,
52
+ max_connections: int | None = 10,
53
+ max_keepalive_connections: int | None = None,
54
+ keepalive_expiry: float | None = None,
55
+ http1: bool = True,
56
+ http2: bool = False,
57
+ retries: int = 0,
58
+ local_address: str | None = None,
59
+ uds: str | None = None,
60
+ network_backend: AsyncNetworkBackend | None = None,
61
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
62
+ ) -> None:
63
+ """
64
+ A connection pool for making HTTP requests.
65
+
66
+ Parameters:
67
+ ssl_context: An SSL context to use for verifying connections.
68
+ If not specified, the default `httpcore.default_ssl_context()`
69
+ will be used.
70
+ max_connections: The maximum number of concurrent HTTP connections that
71
+ the pool should allow. Any attempt to send a request on a pool that
72
+ would exceed this amount will block until a connection is available.
73
+ max_keepalive_connections: The maximum number of idle HTTP connections
74
+ that will be maintained in the pool.
75
+ keepalive_expiry: The duration in seconds that an idle HTTP connection
76
+ may be maintained for before being expired from the pool.
77
+ http1: A boolean indicating if HTTP/1.1 requests should be supported
78
+ by the connection pool. Defaults to True.
79
+ http2: A boolean indicating if HTTP/2 requests should be supported by
80
+ the connection pool. Defaults to False.
81
+ retries: The maximum number of retries when trying to establish a
82
+ connection.
83
+ local_address: Local address to connect from. Can also be used to connect
84
+ using a particular address family. Using `local_address="0.0.0.0"`
85
+ will connect using an `AF_INET` address (IPv4), while using
86
+ `local_address="::"` will connect using an `AF_INET6` address (IPv6).
87
+ uds: Path to a Unix Domain Socket to use instead of TCP sockets.
88
+ network_backend: A backend instance to use for handling network I/O.
89
+ socket_options: Socket options that have to be included
90
+ in the TCP socket when the connection was established.
91
+ """
92
+ self._ssl_context = ssl_context
93
+ self._proxy = proxy
94
+ self._max_connections = (
95
+ sys.maxsize if max_connections is None else max_connections
96
+ )
97
+ self._max_keepalive_connections = (
98
+ sys.maxsize
99
+ if max_keepalive_connections is None
100
+ else max_keepalive_connections
101
+ )
102
+ self._max_keepalive_connections = min(
103
+ self._max_connections, self._max_keepalive_connections
104
+ )
105
+
106
+ self._keepalive_expiry = keepalive_expiry
107
+ self._http1 = http1
108
+ self._http2 = http2
109
+ self._retries = retries
110
+ self._local_address = local_address
111
+ self._uds = uds
112
+
113
+ self._network_backend = (
114
+ AutoBackend() if network_backend is None else network_backend
115
+ )
116
+ self._socket_options = socket_options
117
+
118
+ # The mutable state on a connection pool is the queue of incoming requests,
119
+ # and the set of connections that are servicing those requests.
120
+ self._connections: list[AsyncConnectionInterface] = []
121
+ self._requests: list[AsyncPoolRequest] = []
122
+
123
+ # We only mutate the state of the connection pool within an 'optional_thread_lock'
124
+ # context. This holds a threading lock unless we're running in async mode,
125
+ # in which case it is a no-op.
126
+ self._optional_thread_lock = AsyncThreadLock()
127
+
128
+ def create_connection(self, origin: Origin) -> AsyncConnectionInterface:
129
+ if self._proxy is not None:
130
+ if self._proxy.url.scheme in (b"socks5", b"socks5h"):
131
+ from .socks_proxy import AsyncSocks5Connection
132
+
133
+ return AsyncSocks5Connection(
134
+ proxy_origin=self._proxy.url.origin,
135
+ proxy_auth=self._proxy.auth,
136
+ remote_origin=origin,
137
+ ssl_context=self._ssl_context,
138
+ keepalive_expiry=self._keepalive_expiry,
139
+ http1=self._http1,
140
+ http2=self._http2,
141
+ network_backend=self._network_backend,
142
+ )
143
+ elif origin.scheme == b"http":
144
+ from .http_proxy import AsyncForwardHTTPConnection
145
+
146
+ return AsyncForwardHTTPConnection(
147
+ proxy_origin=self._proxy.url.origin,
148
+ proxy_headers=self._proxy.headers,
149
+ proxy_ssl_context=self._proxy.ssl_context,
150
+ remote_origin=origin,
151
+ keepalive_expiry=self._keepalive_expiry,
152
+ network_backend=self._network_backend,
153
+ )
154
+ from .http_proxy import AsyncTunnelHTTPConnection
155
+
156
+ return AsyncTunnelHTTPConnection(
157
+ proxy_origin=self._proxy.url.origin,
158
+ proxy_headers=self._proxy.headers,
159
+ proxy_ssl_context=self._proxy.ssl_context,
160
+ remote_origin=origin,
161
+ ssl_context=self._ssl_context,
162
+ keepalive_expiry=self._keepalive_expiry,
163
+ http1=self._http1,
164
+ http2=self._http2,
165
+ network_backend=self._network_backend,
166
+ )
167
+
168
+ return AsyncHTTPConnection(
169
+ origin=origin,
170
+ ssl_context=self._ssl_context,
171
+ keepalive_expiry=self._keepalive_expiry,
172
+ http1=self._http1,
173
+ http2=self._http2,
174
+ retries=self._retries,
175
+ local_address=self._local_address,
176
+ uds=self._uds,
177
+ network_backend=self._network_backend,
178
+ socket_options=self._socket_options,
179
+ )
180
+
181
+ @property
182
+ def connections(self) -> list[AsyncConnectionInterface]:
183
+ """
184
+ Return a list of the connections currently in the pool.
185
+
186
+ For example:
187
+
188
+ ```python
189
+ >>> pool.connections
190
+ [
191
+ <AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 6]>,
192
+ <AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 9]> ,
193
+ <AsyncHTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>,
194
+ ]
195
+ ```
196
+ """
197
+ return list(self._connections)
198
+
199
+ async def handle_async_request(self, request: Request) -> Response:
200
+ """
201
+ Send an HTTP request, and return an HTTP response.
202
+
203
+ This is the core implementation that is called into by `.request()` or `.stream()`.
204
+ """
205
+ scheme = request.url.scheme.decode()
206
+ if scheme == "":
207
+ raise UnsupportedProtocol(
208
+ "Request URL is missing an 'http://' or 'https://' protocol."
209
+ )
210
+ if scheme not in ("http", "https", "ws", "wss"):
211
+ raise UnsupportedProtocol(
212
+ f"Request URL has an unsupported protocol '{scheme}://'."
213
+ )
214
+
215
+ timeouts = request.extensions.get("timeout", {})
216
+ timeout = timeouts.get("pool", None)
217
+
218
+ with self._optional_thread_lock:
219
+ # Add the incoming request to our request queue.
220
+ pool_request = AsyncPoolRequest(request)
221
+ self._requests.append(pool_request)
222
+
223
+ try:
224
+ while True:
225
+ with self._optional_thread_lock:
226
+ # Assign incoming requests to available connections,
227
+ # closing or creating new connections as required.
228
+ closing = self._assign_requests_to_connections()
229
+ await self._close_connections(closing)
230
+
231
+ # Wait until this request has an assigned connection.
232
+ connection = await pool_request.wait_for_connection(timeout=timeout)
233
+
234
+ try:
235
+ # Send the request on the assigned connection.
236
+ response = await connection.handle_async_request(
237
+ pool_request.request
238
+ )
239
+ except ConnectionNotAvailable:
240
+ # In some cases a connection may initially be available to
241
+ # handle a request, but then become unavailable.
242
+ #
243
+ # In this case we clear the connection and try again.
244
+ pool_request.clear_connection()
245
+ else:
246
+ break # pragma: nocover
247
+
248
+ except BaseException as exc:
249
+ with self._optional_thread_lock:
250
+ # For any exception or cancellation we remove the request from
251
+ # the queue, and then re-assign requests to connections.
252
+ self._requests.remove(pool_request)
253
+ closing = self._assign_requests_to_connections()
254
+
255
+ await self._close_connections(closing)
256
+ raise exc from None
257
+
258
+ # Return the response. Note that in this case we still have to manage
259
+ # the point at which the response is closed.
260
+ assert isinstance(response.stream, typing.AsyncIterable)
261
+ return Response(
262
+ status=response.status,
263
+ headers=response.headers,
264
+ content=PoolByteStream(
265
+ stream=response.stream, pool_request=pool_request, pool=self
266
+ ),
267
+ extensions=response.extensions,
268
+ )
269
+
270
+ def _assign_requests_to_connections(self) -> list[AsyncConnectionInterface]:
271
+ """
272
+ Manage the state of the connection pool, assigning incoming
273
+ requests to connections as available.
274
+
275
+ Called whenever a new request is added or removed from the pool.
276
+
277
+ Any closing connections are returned, allowing the I/O for closing
278
+ those connections to be handled seperately.
279
+ """
280
+ closing_connections = []
281
+
282
+ # First we handle cleaning up any connections that are closed,
283
+ # have expired their keep-alive, or surplus idle connections.
284
+ for connection in list(self._connections):
285
+ if connection.is_closed():
286
+ # log: "removing closed connection"
287
+ self._connections.remove(connection)
288
+ elif connection.has_expired():
289
+ # log: "closing expired connection"
290
+ self._connections.remove(connection)
291
+ closing_connections.append(connection)
292
+ elif (
293
+ connection.is_idle()
294
+ and len([connection.is_idle() for connection in self._connections])
295
+ > self._max_keepalive_connections
296
+ ):
297
+ # log: "closing idle connection"
298
+ self._connections.remove(connection)
299
+ closing_connections.append(connection)
300
+
301
+ # Assign queued requests to connections.
302
+ queued_requests = [request for request in self._requests if request.is_queued()]
303
+ for pool_request in queued_requests:
304
+ origin = pool_request.request.url.origin
305
+ available_connections = [
306
+ connection
307
+ for connection in self._connections
308
+ if connection.can_handle_request(origin) and connection.is_available()
309
+ ]
310
+ idle_connections = [
311
+ connection for connection in self._connections if connection.is_idle()
312
+ ]
313
+
314
+ # There are three cases for how we may be able to handle the request:
315
+ #
316
+ # 1. There is an existing connection that can handle the request.
317
+ # 2. We can create a new connection to handle the request.
318
+ # 3. We can close an idle connection and then create a new connection
319
+ # to handle the request.
320
+ if available_connections:
321
+ # log: "reusing existing connection"
322
+ connection = available_connections[0]
323
+ pool_request.assign_to_connection(connection)
324
+ elif len(self._connections) < self._max_connections:
325
+ # log: "creating new connection"
326
+ connection = self.create_connection(origin)
327
+ self._connections.append(connection)
328
+ pool_request.assign_to_connection(connection)
329
+ elif idle_connections:
330
+ # log: "closing idle connection"
331
+ connection = idle_connections[0]
332
+ self._connections.remove(connection)
333
+ closing_connections.append(connection)
334
+ # log: "creating new connection"
335
+ connection = self.create_connection(origin)
336
+ self._connections.append(connection)
337
+ pool_request.assign_to_connection(connection)
338
+
339
+ return closing_connections
340
+
341
+ async def _close_connections(self, closing: list[AsyncConnectionInterface]) -> None:
342
+ # Close connections which have been removed from the pool.
343
+ with AsyncShieldCancellation():
344
+ for connection in closing:
345
+ await connection.aclose()
346
+
347
+ async def aclose(self) -> None:
348
+ # Explicitly close the connection pool.
349
+ # Clears all existing requests and connections.
350
+ with self._optional_thread_lock:
351
+ closing_connections = list(self._connections)
352
+ self._connections = []
353
+ await self._close_connections(closing_connections)
354
+
355
+ async def __aenter__(self) -> AsyncConnectionPool:
356
+ return self
357
+
358
+ async def __aexit__(
359
+ self,
360
+ exc_type: type[BaseException] | None = None,
361
+ exc_value: BaseException | None = None,
362
+ traceback: types.TracebackType | None = None,
363
+ ) -> None:
364
+ await self.aclose()
365
+
366
+ def __repr__(self) -> str:
367
+ class_name = self.__class__.__name__
368
+ with self._optional_thread_lock:
369
+ request_is_queued = [request.is_queued() for request in self._requests]
370
+ connection_is_idle = [
371
+ connection.is_idle() for connection in self._connections
372
+ ]
373
+
374
+ num_active_requests = request_is_queued.count(False)
375
+ num_queued_requests = request_is_queued.count(True)
376
+ num_active_connections = connection_is_idle.count(False)
377
+ num_idle_connections = connection_is_idle.count(True)
378
+
379
+ requests_info = (
380
+ f"Requests: {num_active_requests} active, {num_queued_requests} queued"
381
+ )
382
+ connection_info = (
383
+ f"Connections: {num_active_connections} active, {num_idle_connections} idle"
384
+ )
385
+
386
+ return f"<{class_name} [{requests_info} | {connection_info}]>"
387
+
388
+
389
+ class PoolByteStream:
390
+ def __init__(
391
+ self,
392
+ stream: typing.AsyncIterable[bytes],
393
+ pool_request: AsyncPoolRequest,
394
+ pool: AsyncConnectionPool,
395
+ ) -> None:
396
+ self._stream = stream
397
+ self._pool_request = pool_request
398
+ self._pool = pool
399
+ self._closed = False
400
+
401
+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
402
+ try:
403
+ async for part in self._stream:
404
+ yield part
405
+ except BaseException as exc:
406
+ await self.aclose()
407
+ raise exc from None
408
+
409
+ async def aclose(self) -> None:
410
+ if not self._closed:
411
+ self._closed = True
412
+ with AsyncShieldCancellation():
413
+ if hasattr(self._stream, "aclose"):
414
+ await self._stream.aclose()
415
+
416
+ with self._pool._optional_thread_lock:
417
+ self._pool._requests.remove(self._pool_request)
418
+ closing = self._pool._assign_requests_to_connections()
419
+
420
+ await self._pool._close_connections(closing)
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http11.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import logging
5
+ import ssl
6
+ import time
7
+ import types
8
+ import typing
9
+
10
+ import h11
11
+
12
+ from .._backends.base import AsyncNetworkStream
13
+ from .._exceptions import (
14
+ ConnectionNotAvailable,
15
+ LocalProtocolError,
16
+ RemoteProtocolError,
17
+ WriteError,
18
+ map_exceptions,
19
+ )
20
+ from .._models import Origin, Request, Response
21
+ from .._synchronization import AsyncLock, AsyncShieldCancellation
22
+ from .._trace import Trace
23
+ from .interfaces import AsyncConnectionInterface
24
+
25
+ logger = logging.getLogger("httpcore.http11")
26
+
27
+
28
+ # A subset of `h11.Event` types supported by `_send_event`
29
+ H11SendEvent = typing.Union[
30
+ h11.Request,
31
+ h11.Data,
32
+ h11.EndOfMessage,
33
+ ]
34
+
35
+
36
+ class HTTPConnectionState(enum.IntEnum):
37
+ NEW = 0
38
+ ACTIVE = 1
39
+ IDLE = 2
40
+ CLOSED = 3
41
+
42
+
43
+ class AsyncHTTP11Connection(AsyncConnectionInterface):
44
+ READ_NUM_BYTES = 64 * 1024
45
+ MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024
46
+
47
+ def __init__(
48
+ self,
49
+ origin: Origin,
50
+ stream: AsyncNetworkStream,
51
+ keepalive_expiry: float | None = None,
52
+ ) -> None:
53
+ self._origin = origin
54
+ self._network_stream = stream
55
+ self._keepalive_expiry: float | None = keepalive_expiry
56
+ self._expire_at: float | None = None
57
+ self._state = HTTPConnectionState.NEW
58
+ self._state_lock = AsyncLock()
59
+ self._request_count = 0
60
+ self._h11_state = h11.Connection(
61
+ our_role=h11.CLIENT,
62
+ max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE,
63
+ )
64
+
65
+ async def handle_async_request(self, request: Request) -> Response:
66
+ if not self.can_handle_request(request.url.origin):
67
+ raise RuntimeError(
68
+ f"Attempted to send request to {request.url.origin} on connection "
69
+ f"to {self._origin}"
70
+ )
71
+
72
+ async with self._state_lock:
73
+ if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE):
74
+ self._request_count += 1
75
+ self._state = HTTPConnectionState.ACTIVE
76
+ self._expire_at = None
77
+ else:
78
+ raise ConnectionNotAvailable()
79
+
80
+ try:
81
+ kwargs = {"request": request}
82
+ try:
83
+ async with Trace(
84
+ "send_request_headers", logger, request, kwargs
85
+ ) as trace:
86
+ await self._send_request_headers(**kwargs)
87
+ async with Trace("send_request_body", logger, request, kwargs) as trace:
88
+ await self._send_request_body(**kwargs)
89
+ except WriteError:
90
+ # If we get a write error while we're writing the request,
91
+ # then we supress this error and move on to attempting to
92
+ # read the response. Servers can sometimes close the request
93
+ # pre-emptively and then respond with a well formed HTTP
94
+ # error response.
95
+ pass
96
+
97
+ async with Trace(
98
+ "receive_response_headers", logger, request, kwargs
99
+ ) as trace:
100
+ (
101
+ http_version,
102
+ status,
103
+ reason_phrase,
104
+ headers,
105
+ trailing_data,
106
+ ) = await self._receive_response_headers(**kwargs)
107
+ trace.return_value = (
108
+ http_version,
109
+ status,
110
+ reason_phrase,
111
+ headers,
112
+ )
113
+
114
+ network_stream = self._network_stream
115
+
116
+ # CONNECT or Upgrade request
117
+ if (status == 101) or (
118
+ (request.method == b"CONNECT") and (200 <= status < 300)
119
+ ):
120
+ network_stream = AsyncHTTP11UpgradeStream(network_stream, trailing_data)
121
+
122
+ return Response(
123
+ status=status,
124
+ headers=headers,
125
+ content=HTTP11ConnectionByteStream(self, request),
126
+ extensions={
127
+ "http_version": http_version,
128
+ "reason_phrase": reason_phrase,
129
+ "network_stream": network_stream,
130
+ },
131
+ )
132
+ except BaseException as exc:
133
+ with AsyncShieldCancellation():
134
+ async with Trace("response_closed", logger, request) as trace:
135
+ await self._response_closed()
136
+ raise exc
137
+
138
+ # Sending the request...
139
+
140
+ async def _send_request_headers(self, request: Request) -> None:
141
+ timeouts = request.extensions.get("timeout", {})
142
+ timeout = timeouts.get("write", None)
143
+
144
+ with map_exceptions({h11.LocalProtocolError: LocalProtocolError}):
145
+ event = h11.Request(
146
+ method=request.method,
147
+ target=request.url.target,
148
+ headers=request.headers,
149
+ )
150
+ await self._send_event(event, timeout=timeout)
151
+
152
+ async def _send_request_body(self, request: Request) -> None:
153
+ timeouts = request.extensions.get("timeout", {})
154
+ timeout = timeouts.get("write", None)
155
+
156
+ assert isinstance(request.stream, typing.AsyncIterable)
157
+ async for chunk in request.stream:
158
+ event = h11.Data(data=chunk)
159
+ await self._send_event(event, timeout=timeout)
160
+
161
+ await self._send_event(h11.EndOfMessage(), timeout=timeout)
162
+
163
+ async def _send_event(self, event: h11.Event, timeout: float | None = None) -> None:
164
+ bytes_to_send = self._h11_state.send(event)
165
+ if bytes_to_send is not None:
166
+ await self._network_stream.write(bytes_to_send, timeout=timeout)
167
+
168
+ # Receiving the response...
169
+
170
+ async def _receive_response_headers(
171
+ self, request: Request
172
+ ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]:
173
+ timeouts = request.extensions.get("timeout", {})
174
+ timeout = timeouts.get("read", None)
175
+
176
+ while True:
177
+ event = await self._receive_event(timeout=timeout)
178
+ if isinstance(event, h11.Response):
179
+ break
180
+ if (
181
+ isinstance(event, h11.InformationalResponse)
182
+ and event.status_code == 101
183
+ ):
184
+ break
185
+
186
+ http_version = b"HTTP/" + event.http_version
187
+
188
+ # h11 version 0.11+ supports a `raw_items` interface to get the
189
+ # raw header casing, rather than the enforced lowercase headers.
190
+ headers = event.headers.raw_items()
191
+
192
+ trailing_data, _ = self._h11_state.trailing_data
193
+
194
+ return http_version, event.status_code, event.reason, headers, trailing_data
195
+
196
+ async def _receive_response_body(
197
+ self, request: Request
198
+ ) -> typing.AsyncIterator[bytes]:
199
+ timeouts = request.extensions.get("timeout", {})
200
+ timeout = timeouts.get("read", None)
201
+
202
+ while True:
203
+ event = await self._receive_event(timeout=timeout)
204
+ if isinstance(event, h11.Data):
205
+ yield bytes(event.data)
206
+ elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)):
207
+ break
208
+
209
+ async def _receive_event(
210
+ self, timeout: float | None = None
211
+ ) -> h11.Event | type[h11.PAUSED]:
212
+ while True:
213
+ with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}):
214
+ event = self._h11_state.next_event()
215
+
216
+ if event is h11.NEED_DATA:
217
+ data = await self._network_stream.read(
218
+ self.READ_NUM_BYTES, timeout=timeout
219
+ )
220
+
221
+ # If we feed this case through h11 we'll raise an exception like:
222
+ #
223
+ # httpcore.RemoteProtocolError: can't handle event type
224
+ # ConnectionClosed when role=SERVER and state=SEND_RESPONSE
225
+ #
226
+ # Which is accurate, but not very informative from an end-user
227
+ # perspective. Instead we handle this case distinctly and treat
228
+ # it as a ConnectError.
229
+ if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE:
230
+ msg = "Server disconnected without sending a response."
231
+ raise RemoteProtocolError(msg)
232
+
233
+ self._h11_state.receive_data(data)
234
+ else:
235
+ # mypy fails to narrow the type in the above if statement above
236
+ return event # type: ignore[return-value]
237
+
238
+ async def _response_closed(self) -> None:
239
+ async with self._state_lock:
240
+ if (
241
+ self._h11_state.our_state is h11.DONE
242
+ and self._h11_state.their_state is h11.DONE
243
+ ):
244
+ self._state = HTTPConnectionState.IDLE
245
+ self._h11_state.start_next_cycle()
246
+ if self._keepalive_expiry is not None:
247
+ now = time.monotonic()
248
+ self._expire_at = now + self._keepalive_expiry
249
+ else:
250
+ await self.aclose()
251
+
252
+ # Once the connection is no longer required...
253
+
254
+ async def aclose(self) -> None:
255
+ # Note that this method unilaterally closes the connection, and does
256
+ # not have any kind of locking in place around it.
257
+ self._state = HTTPConnectionState.CLOSED
258
+ await self._network_stream.aclose()
259
+
260
+ # The AsyncConnectionInterface methods provide information about the state of
261
+ # the connection, allowing for a connection pooling implementation to
262
+ # determine when to reuse and when to close the connection...
263
+
264
+ def can_handle_request(self, origin: Origin) -> bool:
265
+ return origin == self._origin
266
+
267
+ def is_available(self) -> bool:
268
+ # Note that HTTP/1.1 connections in the "NEW" state are not treated as
269
+ # being "available". The control flow which created the connection will
270
+ # be able to send an outgoing request, but the connection will not be
271
+ # acquired from the connection pool for any other request.
272
+ return self._state == HTTPConnectionState.IDLE
273
+
274
+ def has_expired(self) -> bool:
275
+ now = time.monotonic()
276
+ keepalive_expired = self._expire_at is not None and now > self._expire_at
277
+
278
+ # If the HTTP connection is idle but the socket is readable, then the
279
+ # only valid state is that the socket is about to return b"", indicating
280
+ # a server-initiated disconnect.
281
+ server_disconnected = (
282
+ self._state == HTTPConnectionState.IDLE
283
+ and self._network_stream.get_extra_info("is_readable")
284
+ )
285
+
286
+ return keepalive_expired or server_disconnected
287
+
288
+ def is_idle(self) -> bool:
289
+ return self._state == HTTPConnectionState.IDLE
290
+
291
+ def is_closed(self) -> bool:
292
+ return self._state == HTTPConnectionState.CLOSED
293
+
294
+ def info(self) -> str:
295
+ origin = str(self._origin)
296
+ return (
297
+ f"{origin!r}, HTTP/1.1, {self._state.name}, "
298
+ f"Request Count: {self._request_count}"
299
+ )
300
+
301
+ def __repr__(self) -> str:
302
+ class_name = self.__class__.__name__
303
+ origin = str(self._origin)
304
+ return (
305
+ f"<{class_name} [{origin!r}, {self._state.name}, "
306
+ f"Request Count: {self._request_count}]>"
307
+ )
308
+
309
+ # These context managers are not used in the standard flow, but are
310
+ # useful for testing or working with connection instances directly.
311
+
312
+ async def __aenter__(self) -> AsyncHTTP11Connection:
313
+ return self
314
+
315
+ async def __aexit__(
316
+ self,
317
+ exc_type: type[BaseException] | None = None,
318
+ exc_value: BaseException | None = None,
319
+ traceback: types.TracebackType | None = None,
320
+ ) -> None:
321
+ await self.aclose()
322
+
323
+
324
+ class HTTP11ConnectionByteStream:
325
+ def __init__(self, connection: AsyncHTTP11Connection, request: Request) -> None:
326
+ self._connection = connection
327
+ self._request = request
328
+ self._closed = False
329
+
330
+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
331
+ kwargs = {"request": self._request}
332
+ try:
333
+ async with Trace("receive_response_body", logger, self._request, kwargs):
334
+ async for chunk in self._connection._receive_response_body(**kwargs):
335
+ yield chunk
336
+ except BaseException as exc:
337
+ # If we get an exception while streaming the response,
338
+ # we want to close the response (and possibly the connection)
339
+ # before raising that exception.
340
+ with AsyncShieldCancellation():
341
+ await self.aclose()
342
+ raise exc
343
+
344
+ async def aclose(self) -> None:
345
+ if not self._closed:
346
+ self._closed = True
347
+ async with Trace("response_closed", logger, self._request):
348
+ await self._connection._response_closed()
349
+
350
+
351
+ class AsyncHTTP11UpgradeStream(AsyncNetworkStream):
352
+ def __init__(self, stream: AsyncNetworkStream, leading_data: bytes) -> None:
353
+ self._stream = stream
354
+ self._leading_data = leading_data
355
+
356
+ async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
357
+ if self._leading_data:
358
+ buffer = self._leading_data[:max_bytes]
359
+ self._leading_data = self._leading_data[max_bytes:]
360
+ return buffer
361
+ else:
362
+ return await self._stream.read(max_bytes, timeout)
363
+
364
+ async def write(self, buffer: bytes, timeout: float | None = None) -> None:
365
+ await self._stream.write(buffer, timeout)
366
+
367
+ async def aclose(self) -> None:
368
+ await self._stream.aclose()
369
+
370
+ async def start_tls(
371
+ self,
372
+ ssl_context: ssl.SSLContext,
373
+ server_hostname: str | None = None,
374
+ timeout: float | None = None,
375
+ ) -> AsyncNetworkStream:
376
+ return await self._stream.start_tls(ssl_context, server_hostname, timeout)
377
+
378
+ def get_extra_info(self, info: str) -> typing.Any:
379
+ return self._stream.get_extra_info(info)
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http2.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import logging
5
+ import time
6
+ import types
7
+ import typing
8
+
9
+ import h2.config
10
+ import h2.connection
11
+ import h2.events
12
+ import h2.exceptions
13
+ import h2.settings
14
+
15
+ from .._backends.base import AsyncNetworkStream
16
+ from .._exceptions import (
17
+ ConnectionNotAvailable,
18
+ LocalProtocolError,
19
+ RemoteProtocolError,
20
+ )
21
+ from .._models import Origin, Request, Response
22
+ from .._synchronization import AsyncLock, AsyncSemaphore, AsyncShieldCancellation
23
+ from .._trace import Trace
24
+ from .interfaces import AsyncConnectionInterface
25
+
26
+ logger = logging.getLogger("httpcore.http2")
27
+
28
+
29
+ def has_body_headers(request: Request) -> bool:
30
+ return any(
31
+ k.lower() == b"content-length" or k.lower() == b"transfer-encoding"
32
+ for k, v in request.headers
33
+ )
34
+
35
+
36
+ class HTTPConnectionState(enum.IntEnum):
37
+ ACTIVE = 1
38
+ IDLE = 2
39
+ CLOSED = 3
40
+
41
+
42
+ class AsyncHTTP2Connection(AsyncConnectionInterface):
43
+ READ_NUM_BYTES = 64 * 1024
44
+ CONFIG = h2.config.H2Configuration(validate_inbound_headers=False)
45
+
46
+ def __init__(
47
+ self,
48
+ origin: Origin,
49
+ stream: AsyncNetworkStream,
50
+ keepalive_expiry: float | None = None,
51
+ ):
52
+ self._origin = origin
53
+ self._network_stream = stream
54
+ self._keepalive_expiry: float | None = keepalive_expiry
55
+ self._h2_state = h2.connection.H2Connection(config=self.CONFIG)
56
+ self._state = HTTPConnectionState.IDLE
57
+ self._expire_at: float | None = None
58
+ self._request_count = 0
59
+ self._init_lock = AsyncLock()
60
+ self._state_lock = AsyncLock()
61
+ self._read_lock = AsyncLock()
62
+ self._write_lock = AsyncLock()
63
+ self._sent_connection_init = False
64
+ self._used_all_stream_ids = False
65
+ self._connection_error = False
66
+
67
+ # Mapping from stream ID to response stream events.
68
+ self._events: dict[
69
+ int,
70
+ list[
71
+ h2.events.ResponseReceived
72
+ | h2.events.DataReceived
73
+ | h2.events.StreamEnded
74
+ | h2.events.StreamReset,
75
+ ],
76
+ ] = {}
77
+
78
+ # Connection terminated events are stored as state since
79
+ # we need to handle them for all streams.
80
+ self._connection_terminated: h2.events.ConnectionTerminated | None = None
81
+
82
+ self._read_exception: Exception | None = None
83
+ self._write_exception: Exception | None = None
84
+
85
+ async def handle_async_request(self, request: Request) -> Response:
86
+ if not self.can_handle_request(request.url.origin):
87
+ # This cannot occur in normal operation, since the connection pool
88
+ # will only send requests on connections that handle them.
89
+ # It's in place simply for resilience as a guard against incorrect
90
+ # usage, for anyone working directly with httpcore connections.
91
+ raise RuntimeError(
92
+ f"Attempted to send request to {request.url.origin} on connection "
93
+ f"to {self._origin}"
94
+ )
95
+
96
+ async with self._state_lock:
97
+ if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE):
98
+ self._request_count += 1
99
+ self._expire_at = None
100
+ self._state = HTTPConnectionState.ACTIVE
101
+ else:
102
+ raise ConnectionNotAvailable()
103
+
104
+ async with self._init_lock:
105
+ if not self._sent_connection_init:
106
+ try:
107
+ sci_kwargs = {"request": request}
108
+ async with Trace(
109
+ "send_connection_init", logger, request, sci_kwargs
110
+ ):
111
+ await self._send_connection_init(**sci_kwargs)
112
+ except BaseException as exc:
113
+ with AsyncShieldCancellation():
114
+ await self.aclose()
115
+ raise exc
116
+
117
+ self._sent_connection_init = True
118
+
119
+ # Initially start with just 1 until the remote server provides
120
+ # its max_concurrent_streams value
121
+ self._max_streams = 1
122
+
123
+ local_settings_max_streams = (
124
+ self._h2_state.local_settings.max_concurrent_streams
125
+ )
126
+ self._max_streams_semaphore = AsyncSemaphore(local_settings_max_streams)
127
+
128
+ for _ in range(local_settings_max_streams - self._max_streams):
129
+ await self._max_streams_semaphore.acquire()
130
+
131
+ await self._max_streams_semaphore.acquire()
132
+
133
+ try:
134
+ stream_id = self._h2_state.get_next_available_stream_id()
135
+ self._events[stream_id] = []
136
+ except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover
137
+ self._used_all_stream_ids = True
138
+ self._request_count -= 1
139
+ raise ConnectionNotAvailable()
140
+
141
+ try:
142
+ kwargs = {"request": request, "stream_id": stream_id}
143
+ async with Trace("send_request_headers", logger, request, kwargs):
144
+ await self._send_request_headers(request=request, stream_id=stream_id)
145
+ async with Trace("send_request_body", logger, request, kwargs):
146
+ await self._send_request_body(request=request, stream_id=stream_id)
147
+ async with Trace(
148
+ "receive_response_headers", logger, request, kwargs
149
+ ) as trace:
150
+ status, headers = await self._receive_response(
151
+ request=request, stream_id=stream_id
152
+ )
153
+ trace.return_value = (status, headers)
154
+
155
+ return Response(
156
+ status=status,
157
+ headers=headers,
158
+ content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id),
159
+ extensions={
160
+ "http_version": b"HTTP/2",
161
+ "network_stream": self._network_stream,
162
+ "stream_id": stream_id,
163
+ },
164
+ )
165
+ except BaseException as exc: # noqa: PIE786
166
+ with AsyncShieldCancellation():
167
+ kwargs = {"stream_id": stream_id}
168
+ async with Trace("response_closed", logger, request, kwargs):
169
+ await self._response_closed(stream_id=stream_id)
170
+
171
+ if isinstance(exc, h2.exceptions.ProtocolError):
172
+ # One case where h2 can raise a protocol error is when a
173
+ # closed frame has been seen by the state machine.
174
+ #
175
+ # This happens when one stream is reading, and encounters
176
+ # a GOAWAY event. Other flows of control may then raise
177
+ # a protocol error at any point they interact with the 'h2_state'.
178
+ #
179
+ # In this case we'll have stored the event, and should raise
180
+ # it as a RemoteProtocolError.
181
+ if self._connection_terminated: # pragma: nocover
182
+ raise RemoteProtocolError(self._connection_terminated)
183
+ # If h2 raises a protocol error in some other state then we
184
+ # must somehow have made a protocol violation.
185
+ raise LocalProtocolError(exc) # pragma: nocover
186
+
187
+ raise exc
188
+
189
+ async def _send_connection_init(self, request: Request) -> None:
190
+ """
191
+ The HTTP/2 connection requires some initial setup before we can start
192
+ using individual request/response streams on it.
193
+ """
194
+ # Need to set these manually here instead of manipulating via
195
+ # __setitem__() otherwise the H2Connection will emit SettingsUpdate
196
+ # frames in addition to sending the undesired defaults.
197
+ self._h2_state.local_settings = h2.settings.Settings(
198
+ client=True,
199
+ initial_values={
200
+ # Disable PUSH_PROMISE frames from the server since we don't do anything
201
+ # with them for now. Maybe when we support caching?
202
+ h2.settings.SettingCodes.ENABLE_PUSH: 0,
203
+ # These two are taken from h2 for safe defaults
204
+ h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100,
205
+ h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536,
206
+ },
207
+ )
208
+
209
+ # Some websites (*cough* Yahoo *cough*) balk at this setting being
210
+ # present in the initial handshake since it's not defined in the original
211
+ # RFC despite the RFC mandating ignoring settings you don't know about.
212
+ del self._h2_state.local_settings[
213
+ h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL
214
+ ]
215
+
216
+ self._h2_state.initiate_connection()
217
+ self._h2_state.increment_flow_control_window(2**24)
218
+ await self._write_outgoing_data(request)
219
+
220
+ # Sending the request...
221
+
222
+ async def _send_request_headers(self, request: Request, stream_id: int) -> None:
223
+ """
224
+ Send the request headers to a given stream ID.
225
+ """
226
+ end_stream = not has_body_headers(request)
227
+
228
+ # In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'.
229
+ # In order to gracefully handle HTTP/1.1 and HTTP/2 we always require
230
+ # HTTP/1.1 style headers, and map them appropriately if we end up on
231
+ # an HTTP/2 connection.
232
+ authority = [v for k, v in request.headers if k.lower() == b"host"][0]
233
+
234
+ headers = [
235
+ (b":method", request.method),
236
+ (b":authority", authority),
237
+ (b":scheme", request.url.scheme),
238
+ (b":path", request.url.target),
239
+ ] + [
240
+ (k.lower(), v)
241
+ for k, v in request.headers
242
+ if k.lower()
243
+ not in (
244
+ b"host",
245
+ b"transfer-encoding",
246
+ )
247
+ ]
248
+
249
+ self._h2_state.send_headers(stream_id, headers, end_stream=end_stream)
250
+ self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id)
251
+ await self._write_outgoing_data(request)
252
+
253
+ async def _send_request_body(self, request: Request, stream_id: int) -> None:
254
+ """
255
+ Iterate over the request body sending it to a given stream ID.
256
+ """
257
+ if not has_body_headers(request):
258
+ return
259
+
260
+ assert isinstance(request.stream, typing.AsyncIterable)
261
+ async for data in request.stream:
262
+ await self._send_stream_data(request, stream_id, data)
263
+ await self._send_end_stream(request, stream_id)
264
+
265
+ async def _send_stream_data(
266
+ self, request: Request, stream_id: int, data: bytes
267
+ ) -> None:
268
+ """
269
+ Send a single chunk of data in one or more data frames.
270
+ """
271
+ while data:
272
+ max_flow = await self._wait_for_outgoing_flow(request, stream_id)
273
+ chunk_size = min(len(data), max_flow)
274
+ chunk, data = data[:chunk_size], data[chunk_size:]
275
+ self._h2_state.send_data(stream_id, chunk)
276
+ await self._write_outgoing_data(request)
277
+
278
+ async def _send_end_stream(self, request: Request, stream_id: int) -> None:
279
+ """
280
+ Send an empty data frame on on a given stream ID with the END_STREAM flag set.
281
+ """
282
+ self._h2_state.end_stream(stream_id)
283
+ await self._write_outgoing_data(request)
284
+
285
+ # Receiving the response...
286
+
287
+ async def _receive_response(
288
+ self, request: Request, stream_id: int
289
+ ) -> tuple[int, list[tuple[bytes, bytes]]]:
290
+ """
291
+ Return the response status code and headers for a given stream ID.
292
+ """
293
+ while True:
294
+ event = await self._receive_stream_event(request, stream_id)
295
+ if isinstance(event, h2.events.ResponseReceived):
296
+ break
297
+
298
+ status_code = 200
299
+ headers = []
300
+ assert event.headers is not None
301
+ for k, v in event.headers:
302
+ if k == b":status":
303
+ status_code = int(v.decode("ascii", errors="ignore"))
304
+ elif not k.startswith(b":"):
305
+ headers.append((k, v))
306
+
307
+ return (status_code, headers)
308
+
309
+ async def _receive_response_body(
310
+ self, request: Request, stream_id: int
311
+ ) -> typing.AsyncIterator[bytes]:
312
+ """
313
+ Iterator that returns the bytes of the response body for a given stream ID.
314
+ """
315
+ while True:
316
+ event = await self._receive_stream_event(request, stream_id)
317
+ if isinstance(event, h2.events.DataReceived):
318
+ assert event.flow_controlled_length is not None
319
+ assert event.data is not None
320
+ amount = event.flow_controlled_length
321
+ self._h2_state.acknowledge_received_data(amount, stream_id)
322
+ await self._write_outgoing_data(request)
323
+ yield event.data
324
+ elif isinstance(event, h2.events.StreamEnded):
325
+ break
326
+
327
+ async def _receive_stream_event(
328
+ self, request: Request, stream_id: int
329
+ ) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded:
330
+ """
331
+ Return the next available event for a given stream ID.
332
+
333
+ Will read more data from the network if required.
334
+ """
335
+ while not self._events.get(stream_id):
336
+ await self._receive_events(request, stream_id)
337
+ event = self._events[stream_id].pop(0)
338
+ if isinstance(event, h2.events.StreamReset):
339
+ raise RemoteProtocolError(event)
340
+ return event
341
+
342
+ async def _receive_events(
343
+ self, request: Request, stream_id: int | None = None
344
+ ) -> None:
345
+ """
346
+ Read some data from the network until we see one or more events
347
+ for a given stream ID.
348
+ """
349
+ async with self._read_lock:
350
+ if self._connection_terminated is not None:
351
+ last_stream_id = self._connection_terminated.last_stream_id
352
+ if stream_id and last_stream_id and stream_id > last_stream_id:
353
+ self._request_count -= 1
354
+ raise ConnectionNotAvailable()
355
+ raise RemoteProtocolError(self._connection_terminated)
356
+
357
+ # This conditional is a bit icky. We don't want to block reading if we've
358
+ # actually got an event to return for a given stream. We need to do that
359
+ # check *within* the atomic read lock. Though it also need to be optional,
360
+ # because when we call it from `_wait_for_outgoing_flow` we *do* want to
361
+ # block until we've available flow control, event when we have events
362
+ # pending for the stream ID we're attempting to send on.
363
+ if stream_id is None or not self._events.get(stream_id):
364
+ events = await self._read_incoming_data(request)
365
+ for event in events:
366
+ if isinstance(event, h2.events.RemoteSettingsChanged):
367
+ async with Trace(
368
+ "receive_remote_settings", logger, request
369
+ ) as trace:
370
+ await self._receive_remote_settings_change(event)
371
+ trace.return_value = event
372
+
373
+ elif isinstance(
374
+ event,
375
+ (
376
+ h2.events.ResponseReceived,
377
+ h2.events.DataReceived,
378
+ h2.events.StreamEnded,
379
+ h2.events.StreamReset,
380
+ ),
381
+ ):
382
+ if event.stream_id in self._events:
383
+ self._events[event.stream_id].append(event)
384
+
385
+ elif isinstance(event, h2.events.ConnectionTerminated):
386
+ self._connection_terminated = event
387
+
388
+ await self._write_outgoing_data(request)
389
+
390
+ async def _receive_remote_settings_change(
391
+ self, event: h2.events.RemoteSettingsChanged
392
+ ) -> None:
393
+ max_concurrent_streams = event.changed_settings.get(
394
+ h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS
395
+ )
396
+ if max_concurrent_streams:
397
+ new_max_streams = min(
398
+ max_concurrent_streams.new_value,
399
+ self._h2_state.local_settings.max_concurrent_streams,
400
+ )
401
+ if new_max_streams and new_max_streams != self._max_streams:
402
+ while new_max_streams > self._max_streams:
403
+ await self._max_streams_semaphore.release()
404
+ self._max_streams += 1
405
+ while new_max_streams < self._max_streams:
406
+ await self._max_streams_semaphore.acquire()
407
+ self._max_streams -= 1
408
+
409
+ async def _response_closed(self, stream_id: int) -> None:
410
+ await self._max_streams_semaphore.release()
411
+ del self._events[stream_id]
412
+ async with self._state_lock:
413
+ if self._connection_terminated and not self._events:
414
+ await self.aclose()
415
+
416
+ elif self._state == HTTPConnectionState.ACTIVE and not self._events:
417
+ self._state = HTTPConnectionState.IDLE
418
+ if self._keepalive_expiry is not None:
419
+ now = time.monotonic()
420
+ self._expire_at = now + self._keepalive_expiry
421
+ if self._used_all_stream_ids: # pragma: nocover
422
+ await self.aclose()
423
+
424
+ async def aclose(self) -> None:
425
+ # Note that this method unilaterally closes the connection, and does
426
+ # not have any kind of locking in place around it.
427
+ self._h2_state.close_connection()
428
+ self._state = HTTPConnectionState.CLOSED
429
+ await self._network_stream.aclose()
430
+
431
+ # Wrappers around network read/write operations...
432
+
433
+ async def _read_incoming_data(self, request: Request) -> list[h2.events.Event]:
434
+ timeouts = request.extensions.get("timeout", {})
435
+ timeout = timeouts.get("read", None)
436
+
437
+ if self._read_exception is not None:
438
+ raise self._read_exception # pragma: nocover
439
+
440
+ try:
441
+ data = await self._network_stream.read(self.READ_NUM_BYTES, timeout)
442
+ if data == b"":
443
+ raise RemoteProtocolError("Server disconnected")
444
+ except Exception as exc:
445
+ # If we get a network error we should:
446
+ #
447
+ # 1. Save the exception and just raise it immediately on any future reads.
448
+ # (For example, this means that a single read timeout or disconnect will
449
+ # immediately close all pending streams. Without requiring multiple
450
+ # sequential timeouts.)
451
+ # 2. Mark the connection as errored, so that we don't accept any other
452
+ # incoming requests.
453
+ self._read_exception = exc
454
+ self._connection_error = True
455
+ raise exc
456
+
457
+ events: list[h2.events.Event] = self._h2_state.receive_data(data)
458
+
459
+ return events
460
+
461
+ async def _write_outgoing_data(self, request: Request) -> None:
462
+ timeouts = request.extensions.get("timeout", {})
463
+ timeout = timeouts.get("write", None)
464
+
465
+ async with self._write_lock:
466
+ data_to_send = self._h2_state.data_to_send()
467
+
468
+ if self._write_exception is not None:
469
+ raise self._write_exception # pragma: nocover
470
+
471
+ try:
472
+ await self._network_stream.write(data_to_send, timeout)
473
+ except Exception as exc: # pragma: nocover
474
+ # If we get a network error we should:
475
+ #
476
+ # 1. Save the exception and just raise it immediately on any future write.
477
+ # (For example, this means that a single write timeout or disconnect will
478
+ # immediately close all pending streams. Without requiring multiple
479
+ # sequential timeouts.)
480
+ # 2. Mark the connection as errored, so that we don't accept any other
481
+ # incoming requests.
482
+ self._write_exception = exc
483
+ self._connection_error = True
484
+ raise exc
485
+
486
+ # Flow control...
487
+
488
+ async def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int:
489
+ """
490
+ Returns the maximum allowable outgoing flow for a given stream.
491
+
492
+ If the allowable flow is zero, then waits on the network until
493
+ WindowUpdated frames have increased the flow rate.
494
+ https://tools.ietf.org/html/rfc7540#section-6.9
495
+ """
496
+ local_flow: int = self._h2_state.local_flow_control_window(stream_id)
497
+ max_frame_size: int = self._h2_state.max_outbound_frame_size
498
+ flow = min(local_flow, max_frame_size)
499
+ while flow == 0:
500
+ await self._receive_events(request)
501
+ local_flow = self._h2_state.local_flow_control_window(stream_id)
502
+ max_frame_size = self._h2_state.max_outbound_frame_size
503
+ flow = min(local_flow, max_frame_size)
504
+ return flow
505
+
506
+ # Interface for connection pooling...
507
+
508
+ def can_handle_request(self, origin: Origin) -> bool:
509
+ return origin == self._origin
510
+
511
+ def is_available(self) -> bool:
512
+ return (
513
+ self._state != HTTPConnectionState.CLOSED
514
+ and not self._connection_error
515
+ and not self._used_all_stream_ids
516
+ and not (
517
+ self._h2_state.state_machine.state
518
+ == h2.connection.ConnectionState.CLOSED
519
+ )
520
+ )
521
+
522
+ def has_expired(self) -> bool:
523
+ now = time.monotonic()
524
+ return self._expire_at is not None and now > self._expire_at
525
+
526
+ def is_idle(self) -> bool:
527
+ return self._state == HTTPConnectionState.IDLE
528
+
529
+ def is_closed(self) -> bool:
530
+ return self._state == HTTPConnectionState.CLOSED
531
+
532
+ def info(self) -> str:
533
+ origin = str(self._origin)
534
+ return (
535
+ f"{origin!r}, HTTP/2, {self._state.name}, "
536
+ f"Request Count: {self._request_count}"
537
+ )
538
+
539
+ def __repr__(self) -> str:
540
+ class_name = self.__class__.__name__
541
+ origin = str(self._origin)
542
+ return (
543
+ f"<{class_name} [{origin!r}, {self._state.name}, "
544
+ f"Request Count: {self._request_count}]>"
545
+ )
546
+
547
+ # These context managers are not used in the standard flow, but are
548
+ # useful for testing or working with connection instances directly.
549
+
550
+ async def __aenter__(self) -> AsyncHTTP2Connection:
551
+ return self
552
+
553
+ async def __aexit__(
554
+ self,
555
+ exc_type: type[BaseException] | None = None,
556
+ exc_value: BaseException | None = None,
557
+ traceback: types.TracebackType | None = None,
558
+ ) -> None:
559
+ await self.aclose()
560
+
561
+
562
+ class HTTP2ConnectionByteStream:
563
+ def __init__(
564
+ self, connection: AsyncHTTP2Connection, request: Request, stream_id: int
565
+ ) -> None:
566
+ self._connection = connection
567
+ self._request = request
568
+ self._stream_id = stream_id
569
+ self._closed = False
570
+
571
+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
572
+ kwargs = {"request": self._request, "stream_id": self._stream_id}
573
+ try:
574
+ async with Trace("receive_response_body", logger, self._request, kwargs):
575
+ async for chunk in self._connection._receive_response_body(
576
+ request=self._request, stream_id=self._stream_id
577
+ ):
578
+ yield chunk
579
+ except BaseException as exc:
580
+ # If we get an exception while streaming the response,
581
+ # we want to close the response (and possibly the connection)
582
+ # before raising that exception.
583
+ with AsyncShieldCancellation():
584
+ await self.aclose()
585
+ raise exc
586
+
587
+ async def aclose(self) -> None:
588
+ if not self._closed:
589
+ self._closed = True
590
+ kwargs = {"stream_id": self._stream_id}
591
+ async with Trace("response_closed", logger, self._request, kwargs):
592
+ await self._connection._response_closed(stream_id=self._stream_id)
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http_proxy.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import logging
5
+ import ssl
6
+ import typing
7
+
8
+ from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend
9
+ from .._exceptions import ProxyError
10
+ from .._models import (
11
+ URL,
12
+ Origin,
13
+ Request,
14
+ Response,
15
+ enforce_bytes,
16
+ enforce_headers,
17
+ enforce_url,
18
+ )
19
+ from .._ssl import default_ssl_context
20
+ from .._synchronization import AsyncLock
21
+ from .._trace import Trace
22
+ from .connection import AsyncHTTPConnection
23
+ from .connection_pool import AsyncConnectionPool
24
+ from .http11 import AsyncHTTP11Connection
25
+ from .interfaces import AsyncConnectionInterface
26
+
27
+ ByteOrStr = typing.Union[bytes, str]
28
+ HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]]
29
+ HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr]
30
+
31
+
32
+ logger = logging.getLogger("httpcore.proxy")
33
+
34
+
35
+ def merge_headers(
36
+ default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,
37
+ override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,
38
+ ) -> list[tuple[bytes, bytes]]:
39
+ """
40
+ Append default_headers and override_headers, de-duplicating if a key exists
41
+ in both cases.
42
+ """
43
+ default_headers = [] if default_headers is None else list(default_headers)
44
+ override_headers = [] if override_headers is None else list(override_headers)
45
+ has_override = set(key.lower() for key, value in override_headers)
46
+ default_headers = [
47
+ (key, value)
48
+ for key, value in default_headers
49
+ if key.lower() not in has_override
50
+ ]
51
+ return default_headers + override_headers
52
+
53
+
54
+ class AsyncHTTPProxy(AsyncConnectionPool): # pragma: nocover
55
+ """
56
+ A connection pool that sends requests via an HTTP proxy.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ proxy_url: URL | bytes | str,
62
+ proxy_auth: tuple[bytes | str, bytes | str] | None = None,
63
+ proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None,
64
+ ssl_context: ssl.SSLContext | None = None,
65
+ proxy_ssl_context: ssl.SSLContext | None = None,
66
+ max_connections: int | None = 10,
67
+ max_keepalive_connections: int | None = None,
68
+ keepalive_expiry: float | None = None,
69
+ http1: bool = True,
70
+ http2: bool = False,
71
+ retries: int = 0,
72
+ local_address: str | None = None,
73
+ uds: str | None = None,
74
+ network_backend: AsyncNetworkBackend | None = None,
75
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
76
+ ) -> None:
77
+ """
78
+ A connection pool for making HTTP requests.
79
+
80
+ Parameters:
81
+ proxy_url: The URL to use when connecting to the proxy server.
82
+ For example `"http://127.0.0.1:8080/"`.
83
+ proxy_auth: Any proxy authentication as a two-tuple of
84
+ (username, password). May be either bytes or ascii-only str.
85
+ proxy_headers: Any HTTP headers to use for the proxy requests.
86
+ For example `{"Proxy-Authorization": "Basic <username>:<password>"}`.
87
+ ssl_context: An SSL context to use for verifying connections.
88
+ If not specified, the default `httpcore.default_ssl_context()`
89
+ will be used.
90
+ proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin.
91
+ max_connections: The maximum number of concurrent HTTP connections that
92
+ the pool should allow. Any attempt to send a request on a pool that
93
+ would exceed this amount will block until a connection is available.
94
+ max_keepalive_connections: The maximum number of idle HTTP connections
95
+ that will be maintained in the pool.
96
+ keepalive_expiry: The duration in seconds that an idle HTTP connection
97
+ may be maintained for before being expired from the pool.
98
+ http1: A boolean indicating if HTTP/1.1 requests should be supported
99
+ by the connection pool. Defaults to True.
100
+ http2: A boolean indicating if HTTP/2 requests should be supported by
101
+ the connection pool. Defaults to False.
102
+ retries: The maximum number of retries when trying to establish
103
+ a connection.
104
+ local_address: Local address to connect from. Can also be used to
105
+ connect using a particular address family. Using
106
+ `local_address="0.0.0.0"` will connect using an `AF_INET` address
107
+ (IPv4), while using `local_address="::"` will connect using an
108
+ `AF_INET6` address (IPv6).
109
+ uds: Path to a Unix Domain Socket to use instead of TCP sockets.
110
+ network_backend: A backend instance to use for handling network I/O.
111
+ """
112
+ super().__init__(
113
+ ssl_context=ssl_context,
114
+ max_connections=max_connections,
115
+ max_keepalive_connections=max_keepalive_connections,
116
+ keepalive_expiry=keepalive_expiry,
117
+ http1=http1,
118
+ http2=http2,
119
+ network_backend=network_backend,
120
+ retries=retries,
121
+ local_address=local_address,
122
+ uds=uds,
123
+ socket_options=socket_options,
124
+ )
125
+
126
+ self._proxy_url = enforce_url(proxy_url, name="proxy_url")
127
+ if (
128
+ self._proxy_url.scheme == b"http" and proxy_ssl_context is not None
129
+ ): # pragma: no cover
130
+ raise RuntimeError(
131
+ "The `proxy_ssl_context` argument is not allowed for the http scheme"
132
+ )
133
+
134
+ self._ssl_context = ssl_context
135
+ self._proxy_ssl_context = proxy_ssl_context
136
+ self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers")
137
+ if proxy_auth is not None:
138
+ username = enforce_bytes(proxy_auth[0], name="proxy_auth")
139
+ password = enforce_bytes(proxy_auth[1], name="proxy_auth")
140
+ userpass = username + b":" + password
141
+ authorization = b"Basic " + base64.b64encode(userpass)
142
+ self._proxy_headers = [
143
+ (b"Proxy-Authorization", authorization)
144
+ ] + self._proxy_headers
145
+
146
+ def create_connection(self, origin: Origin) -> AsyncConnectionInterface:
147
+ if origin.scheme == b"http":
148
+ return AsyncForwardHTTPConnection(
149
+ proxy_origin=self._proxy_url.origin,
150
+ proxy_headers=self._proxy_headers,
151
+ remote_origin=origin,
152
+ keepalive_expiry=self._keepalive_expiry,
153
+ network_backend=self._network_backend,
154
+ proxy_ssl_context=self._proxy_ssl_context,
155
+ )
156
+ return AsyncTunnelHTTPConnection(
157
+ proxy_origin=self._proxy_url.origin,
158
+ proxy_headers=self._proxy_headers,
159
+ remote_origin=origin,
160
+ ssl_context=self._ssl_context,
161
+ proxy_ssl_context=self._proxy_ssl_context,
162
+ keepalive_expiry=self._keepalive_expiry,
163
+ http1=self._http1,
164
+ http2=self._http2,
165
+ network_backend=self._network_backend,
166
+ )
167
+
168
+
169
+ class AsyncForwardHTTPConnection(AsyncConnectionInterface):
170
+ def __init__(
171
+ self,
172
+ proxy_origin: Origin,
173
+ remote_origin: Origin,
174
+ proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None,
175
+ keepalive_expiry: float | None = None,
176
+ network_backend: AsyncNetworkBackend | None = None,
177
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
178
+ proxy_ssl_context: ssl.SSLContext | None = None,
179
+ ) -> None:
180
+ self._connection = AsyncHTTPConnection(
181
+ origin=proxy_origin,
182
+ keepalive_expiry=keepalive_expiry,
183
+ network_backend=network_backend,
184
+ socket_options=socket_options,
185
+ ssl_context=proxy_ssl_context,
186
+ )
187
+ self._proxy_origin = proxy_origin
188
+ self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers")
189
+ self._remote_origin = remote_origin
190
+
191
+ async def handle_async_request(self, request: Request) -> Response:
192
+ headers = merge_headers(self._proxy_headers, request.headers)
193
+ url = URL(
194
+ scheme=self._proxy_origin.scheme,
195
+ host=self._proxy_origin.host,
196
+ port=self._proxy_origin.port,
197
+ target=bytes(request.url),
198
+ )
199
+ proxy_request = Request(
200
+ method=request.method,
201
+ url=url,
202
+ headers=headers,
203
+ content=request.stream,
204
+ extensions=request.extensions,
205
+ )
206
+ return await self._connection.handle_async_request(proxy_request)
207
+
208
+ def can_handle_request(self, origin: Origin) -> bool:
209
+ return origin == self._remote_origin
210
+
211
+ async def aclose(self) -> None:
212
+ await self._connection.aclose()
213
+
214
+ def info(self) -> str:
215
+ return self._connection.info()
216
+
217
+ def is_available(self) -> bool:
218
+ return self._connection.is_available()
219
+
220
+ def has_expired(self) -> bool:
221
+ return self._connection.has_expired()
222
+
223
+ def is_idle(self) -> bool:
224
+ return self._connection.is_idle()
225
+
226
+ def is_closed(self) -> bool:
227
+ return self._connection.is_closed()
228
+
229
+ def __repr__(self) -> str:
230
+ return f"<{self.__class__.__name__} [{self.info()}]>"
231
+
232
+
233
+ class AsyncTunnelHTTPConnection(AsyncConnectionInterface):
234
+ def __init__(
235
+ self,
236
+ proxy_origin: Origin,
237
+ remote_origin: Origin,
238
+ ssl_context: ssl.SSLContext | None = None,
239
+ proxy_ssl_context: ssl.SSLContext | None = None,
240
+ proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,
241
+ keepalive_expiry: float | None = None,
242
+ http1: bool = True,
243
+ http2: bool = False,
244
+ network_backend: AsyncNetworkBackend | None = None,
245
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
246
+ ) -> None:
247
+ self._connection: AsyncConnectionInterface = AsyncHTTPConnection(
248
+ origin=proxy_origin,
249
+ keepalive_expiry=keepalive_expiry,
250
+ network_backend=network_backend,
251
+ socket_options=socket_options,
252
+ ssl_context=proxy_ssl_context,
253
+ )
254
+ self._proxy_origin = proxy_origin
255
+ self._remote_origin = remote_origin
256
+ self._ssl_context = ssl_context
257
+ self._proxy_ssl_context = proxy_ssl_context
258
+ self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers")
259
+ self._keepalive_expiry = keepalive_expiry
260
+ self._http1 = http1
261
+ self._http2 = http2
262
+ self._connect_lock = AsyncLock()
263
+ self._connected = False
264
+
265
+ async def handle_async_request(self, request: Request) -> Response:
266
+ timeouts = request.extensions.get("timeout", {})
267
+ timeout = timeouts.get("connect", None)
268
+
269
+ async with self._connect_lock:
270
+ if not self._connected:
271
+ target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port)
272
+
273
+ connect_url = URL(
274
+ scheme=self._proxy_origin.scheme,
275
+ host=self._proxy_origin.host,
276
+ port=self._proxy_origin.port,
277
+ target=target,
278
+ )
279
+ connect_headers = merge_headers(
280
+ [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers
281
+ )
282
+ connect_request = Request(
283
+ method=b"CONNECT",
284
+ url=connect_url,
285
+ headers=connect_headers,
286
+ extensions=request.extensions,
287
+ )
288
+ connect_response = await self._connection.handle_async_request(
289
+ connect_request
290
+ )
291
+
292
+ if connect_response.status < 200 or connect_response.status > 299:
293
+ reason_bytes = connect_response.extensions.get("reason_phrase", b"")
294
+ reason_str = reason_bytes.decode("ascii", errors="ignore")
295
+ msg = "%d %s" % (connect_response.status, reason_str)
296
+ await self._connection.aclose()
297
+ raise ProxyError(msg)
298
+
299
+ stream = connect_response.extensions["network_stream"]
300
+
301
+ # Upgrade the stream to SSL
302
+ ssl_context = (
303
+ default_ssl_context()
304
+ if self._ssl_context is None
305
+ else self._ssl_context
306
+ )
307
+ alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"]
308
+ ssl_context.set_alpn_protocols(alpn_protocols)
309
+
310
+ kwargs = {
311
+ "ssl_context": ssl_context,
312
+ "server_hostname": self._remote_origin.host.decode("ascii"),
313
+ "timeout": timeout,
314
+ }
315
+ async with Trace("start_tls", logger, request, kwargs) as trace:
316
+ stream = await stream.start_tls(**kwargs)
317
+ trace.return_value = stream
318
+
319
+ # Determine if we should be using HTTP/1.1 or HTTP/2
320
+ ssl_object = stream.get_extra_info("ssl_object")
321
+ http2_negotiated = (
322
+ ssl_object is not None
323
+ and ssl_object.selected_alpn_protocol() == "h2"
324
+ )
325
+
326
+ # Create the HTTP/1.1 or HTTP/2 connection
327
+ if http2_negotiated or (self._http2 and not self._http1):
328
+ from .http2 import AsyncHTTP2Connection
329
+
330
+ self._connection = AsyncHTTP2Connection(
331
+ origin=self._remote_origin,
332
+ stream=stream,
333
+ keepalive_expiry=self._keepalive_expiry,
334
+ )
335
+ else:
336
+ self._connection = AsyncHTTP11Connection(
337
+ origin=self._remote_origin,
338
+ stream=stream,
339
+ keepalive_expiry=self._keepalive_expiry,
340
+ )
341
+
342
+ self._connected = True
343
+ return await self._connection.handle_async_request(request)
344
+
345
+ def can_handle_request(self, origin: Origin) -> bool:
346
+ return origin == self._remote_origin
347
+
348
+ async def aclose(self) -> None:
349
+ await self._connection.aclose()
350
+
351
+ def info(self) -> str:
352
+ return self._connection.info()
353
+
354
+ def is_available(self) -> bool:
355
+ return self._connection.is_available()
356
+
357
+ def has_expired(self) -> bool:
358
+ return self._connection.has_expired()
359
+
360
+ def is_idle(self) -> bool:
361
+ return self._connection.is_idle()
362
+
363
+ def is_closed(self) -> bool:
364
+ return self._connection.is_closed()
365
+
366
+ def __repr__(self) -> str:
367
+ return f"<{self.__class__.__name__} [{self.info()}]>"
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/interfaces.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import typing
5
+
6
+ from .._models import (
7
+ URL,
8
+ Extensions,
9
+ HeaderTypes,
10
+ Origin,
11
+ Request,
12
+ Response,
13
+ enforce_bytes,
14
+ enforce_headers,
15
+ enforce_url,
16
+ include_request_headers,
17
+ )
18
+
19
+
20
+ class AsyncRequestInterface:
21
+ async def request(
22
+ self,
23
+ method: bytes | str,
24
+ url: URL | bytes | str,
25
+ *,
26
+ headers: HeaderTypes = None,
27
+ content: bytes | typing.AsyncIterator[bytes] | None = None,
28
+ extensions: Extensions | None = None,
29
+ ) -> Response:
30
+ # Strict type checking on our parameters.
31
+ method = enforce_bytes(method, name="method")
32
+ url = enforce_url(url, name="url")
33
+ headers = enforce_headers(headers, name="headers")
34
+
35
+ # Include Host header, and optionally Content-Length or Transfer-Encoding.
36
+ headers = include_request_headers(headers, url=url, content=content)
37
+
38
+ request = Request(
39
+ method=method,
40
+ url=url,
41
+ headers=headers,
42
+ content=content,
43
+ extensions=extensions,
44
+ )
45
+ response = await self.handle_async_request(request)
46
+ try:
47
+ await response.aread()
48
+ finally:
49
+ await response.aclose()
50
+ return response
51
+
52
+ @contextlib.asynccontextmanager
53
+ async def stream(
54
+ self,
55
+ method: bytes | str,
56
+ url: URL | bytes | str,
57
+ *,
58
+ headers: HeaderTypes = None,
59
+ content: bytes | typing.AsyncIterator[bytes] | None = None,
60
+ extensions: Extensions | None = None,
61
+ ) -> typing.AsyncIterator[Response]:
62
+ # Strict type checking on our parameters.
63
+ method = enforce_bytes(method, name="method")
64
+ url = enforce_url(url, name="url")
65
+ headers = enforce_headers(headers, name="headers")
66
+
67
+ # Include Host header, and optionally Content-Length or Transfer-Encoding.
68
+ headers = include_request_headers(headers, url=url, content=content)
69
+
70
+ request = Request(
71
+ method=method,
72
+ url=url,
73
+ headers=headers,
74
+ content=content,
75
+ extensions=extensions,
76
+ )
77
+ response = await self.handle_async_request(request)
78
+ try:
79
+ yield response
80
+ finally:
81
+ await response.aclose()
82
+
83
+ async def handle_async_request(self, request: Request) -> Response:
84
+ raise NotImplementedError() # pragma: nocover
85
+
86
+
87
+ class AsyncConnectionInterface(AsyncRequestInterface):
88
+ async def aclose(self) -> None:
89
+ raise NotImplementedError() # pragma: nocover
90
+
91
+ def info(self) -> str:
92
+ raise NotImplementedError() # pragma: nocover
93
+
94
+ def can_handle_request(self, origin: Origin) -> bool:
95
+ raise NotImplementedError() # pragma: nocover
96
+
97
+ def is_available(self) -> bool:
98
+ """
99
+ Return `True` if the connection is currently able to accept an
100
+ outgoing request.
101
+
102
+ An HTTP/1.1 connection will only be available if it is currently idle.
103
+
104
+ An HTTP/2 connection will be available so long as the stream ID space is
105
+ not yet exhausted, and the connection is not in an error state.
106
+
107
+ While the connection is being established we may not yet know if it is going
108
+ to result in an HTTP/1.1 or HTTP/2 connection. The connection should be
109
+ treated as being available, but might ultimately raise `NewConnectionRequired`
110
+ required exceptions if multiple requests are attempted over a connection
111
+ that ends up being established as HTTP/1.1.
112
+ """
113
+ raise NotImplementedError() # pragma: nocover
114
+
115
+ def has_expired(self) -> bool:
116
+ """
117
+ Return `True` if the connection is in a state where it should be closed.
118
+
119
+ This either means that the connection is idle and it has passed the
120
+ expiry time on its keep-alive, or that server has sent an EOF.
121
+ """
122
+ raise NotImplementedError() # pragma: nocover
123
+
124
+ def is_idle(self) -> bool:
125
+ """
126
+ Return `True` if the connection is currently idle.
127
+ """
128
+ raise NotImplementedError() # pragma: nocover
129
+
130
+ def is_closed(self) -> bool:
131
+ """
132
+ Return `True` if the connection has been closed.
133
+
134
+ Used when a response is closed to determine if the connection may be
135
+ returned to the connection pool or not.
136
+ """
137
+ raise NotImplementedError() # pragma: nocover
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/socks_proxy.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import ssl
5
+
6
+ import socksio
7
+
8
+ from .._backends.auto import AutoBackend
9
+ from .._backends.base import AsyncNetworkBackend, AsyncNetworkStream
10
+ from .._exceptions import ConnectionNotAvailable, ProxyError
11
+ from .._models import URL, Origin, Request, Response, enforce_bytes, enforce_url
12
+ from .._ssl import default_ssl_context
13
+ from .._synchronization import AsyncLock
14
+ from .._trace import Trace
15
+ from .connection_pool import AsyncConnectionPool
16
+ from .http11 import AsyncHTTP11Connection
17
+ from .interfaces import AsyncConnectionInterface
18
+
19
+ logger = logging.getLogger("httpcore.socks")
20
+
21
+
22
+ AUTH_METHODS = {
23
+ b"\x00": "NO AUTHENTICATION REQUIRED",
24
+ b"\x01": "GSSAPI",
25
+ b"\x02": "USERNAME/PASSWORD",
26
+ b"\xff": "NO ACCEPTABLE METHODS",
27
+ }
28
+
29
+ REPLY_CODES = {
30
+ b"\x00": "Succeeded",
31
+ b"\x01": "General SOCKS server failure",
32
+ b"\x02": "Connection not allowed by ruleset",
33
+ b"\x03": "Network unreachable",
34
+ b"\x04": "Host unreachable",
35
+ b"\x05": "Connection refused",
36
+ b"\x06": "TTL expired",
37
+ b"\x07": "Command not supported",
38
+ b"\x08": "Address type not supported",
39
+ }
40
+
41
+
42
+ async def _init_socks5_connection(
43
+ stream: AsyncNetworkStream,
44
+ *,
45
+ host: bytes,
46
+ port: int,
47
+ auth: tuple[bytes, bytes] | None = None,
48
+ ) -> None:
49
+ conn = socksio.socks5.SOCKS5Connection()
50
+
51
+ # Auth method request
52
+ auth_method = (
53
+ socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED
54
+ if auth is None
55
+ else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD
56
+ )
57
+ conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method]))
58
+ outgoing_bytes = conn.data_to_send()
59
+ await stream.write(outgoing_bytes)
60
+
61
+ # Auth method response
62
+ incoming_bytes = await stream.read(max_bytes=4096)
63
+ response = conn.receive_data(incoming_bytes)
64
+ assert isinstance(response, socksio.socks5.SOCKS5AuthReply)
65
+ if response.method != auth_method:
66
+ requested = AUTH_METHODS.get(auth_method, "UNKNOWN")
67
+ responded = AUTH_METHODS.get(response.method, "UNKNOWN")
68
+ raise ProxyError(
69
+ f"Requested {requested} from proxy server, but got {responded}."
70
+ )
71
+
72
+ if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD:
73
+ # Username/password request
74
+ assert auth is not None
75
+ username, password = auth
76
+ conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password))
77
+ outgoing_bytes = conn.data_to_send()
78
+ await stream.write(outgoing_bytes)
79
+
80
+ # Username/password response
81
+ incoming_bytes = await stream.read(max_bytes=4096)
82
+ response = conn.receive_data(incoming_bytes)
83
+ assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply)
84
+ if not response.success:
85
+ raise ProxyError("Invalid username/password")
86
+
87
+ # Connect request
88
+ conn.send(
89
+ socksio.socks5.SOCKS5CommandRequest.from_address(
90
+ socksio.socks5.SOCKS5Command.CONNECT, (host, port)
91
+ )
92
+ )
93
+ outgoing_bytes = conn.data_to_send()
94
+ await stream.write(outgoing_bytes)
95
+
96
+ # Connect response
97
+ incoming_bytes = await stream.read(max_bytes=4096)
98
+ response = conn.receive_data(incoming_bytes)
99
+ assert isinstance(response, socksio.socks5.SOCKS5Reply)
100
+ if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED:
101
+ reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN")
102
+ raise ProxyError(f"Proxy Server could not connect: {reply_code}.")
103
+
104
+
105
+ class AsyncSOCKSProxy(AsyncConnectionPool): # pragma: nocover
106
+ """
107
+ A connection pool that sends requests via an HTTP proxy.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ proxy_url: URL | bytes | str,
113
+ proxy_auth: tuple[bytes | str, bytes | str] | None = None,
114
+ ssl_context: ssl.SSLContext | None = None,
115
+ max_connections: int | None = 10,
116
+ max_keepalive_connections: int | None = None,
117
+ keepalive_expiry: float | None = None,
118
+ http1: bool = True,
119
+ http2: bool = False,
120
+ retries: int = 0,
121
+ network_backend: AsyncNetworkBackend | None = None,
122
+ ) -> None:
123
+ """
124
+ A connection pool for making HTTP requests.
125
+
126
+ Parameters:
127
+ proxy_url: The URL to use when connecting to the proxy server.
128
+ For example `"http://127.0.0.1:8080/"`.
129
+ ssl_context: An SSL context to use for verifying connections.
130
+ If not specified, the default `httpcore.default_ssl_context()`
131
+ will be used.
132
+ max_connections: The maximum number of concurrent HTTP connections that
133
+ the pool should allow. Any attempt to send a request on a pool that
134
+ would exceed this amount will block until a connection is available.
135
+ max_keepalive_connections: The maximum number of idle HTTP connections
136
+ that will be maintained in the pool.
137
+ keepalive_expiry: The duration in seconds that an idle HTTP connection
138
+ may be maintained for before being expired from the pool.
139
+ http1: A boolean indicating if HTTP/1.1 requests should be supported
140
+ by the connection pool. Defaults to True.
141
+ http2: A boolean indicating if HTTP/2 requests should be supported by
142
+ the connection pool. Defaults to False.
143
+ retries: The maximum number of retries when trying to establish
144
+ a connection.
145
+ local_address: Local address to connect from. Can also be used to
146
+ connect using a particular address family. Using
147
+ `local_address="0.0.0.0"` will connect using an `AF_INET` address
148
+ (IPv4), while using `local_address="::"` will connect using an
149
+ `AF_INET6` address (IPv6).
150
+ uds: Path to a Unix Domain Socket to use instead of TCP sockets.
151
+ network_backend: A backend instance to use for handling network I/O.
152
+ """
153
+ super().__init__(
154
+ ssl_context=ssl_context,
155
+ max_connections=max_connections,
156
+ max_keepalive_connections=max_keepalive_connections,
157
+ keepalive_expiry=keepalive_expiry,
158
+ http1=http1,
159
+ http2=http2,
160
+ network_backend=network_backend,
161
+ retries=retries,
162
+ )
163
+ self._ssl_context = ssl_context
164
+ self._proxy_url = enforce_url(proxy_url, name="proxy_url")
165
+ if proxy_auth is not None:
166
+ username, password = proxy_auth
167
+ username_bytes = enforce_bytes(username, name="proxy_auth")
168
+ password_bytes = enforce_bytes(password, name="proxy_auth")
169
+ self._proxy_auth: tuple[bytes, bytes] | None = (
170
+ username_bytes,
171
+ password_bytes,
172
+ )
173
+ else:
174
+ self._proxy_auth = None
175
+
176
+ def create_connection(self, origin: Origin) -> AsyncConnectionInterface:
177
+ return AsyncSocks5Connection(
178
+ proxy_origin=self._proxy_url.origin,
179
+ remote_origin=origin,
180
+ proxy_auth=self._proxy_auth,
181
+ ssl_context=self._ssl_context,
182
+ keepalive_expiry=self._keepalive_expiry,
183
+ http1=self._http1,
184
+ http2=self._http2,
185
+ network_backend=self._network_backend,
186
+ )
187
+
188
+
189
+ class AsyncSocks5Connection(AsyncConnectionInterface):
190
+ def __init__(
191
+ self,
192
+ proxy_origin: Origin,
193
+ remote_origin: Origin,
194
+ proxy_auth: tuple[bytes, bytes] | None = None,
195
+ ssl_context: ssl.SSLContext | None = None,
196
+ keepalive_expiry: float | None = None,
197
+ http1: bool = True,
198
+ http2: bool = False,
199
+ network_backend: AsyncNetworkBackend | None = None,
200
+ ) -> None:
201
+ self._proxy_origin = proxy_origin
202
+ self._remote_origin = remote_origin
203
+ self._proxy_auth = proxy_auth
204
+ self._ssl_context = ssl_context
205
+ self._keepalive_expiry = keepalive_expiry
206
+ self._http1 = http1
207
+ self._http2 = http2
208
+
209
+ self._network_backend: AsyncNetworkBackend = (
210
+ AutoBackend() if network_backend is None else network_backend
211
+ )
212
+ self._connect_lock = AsyncLock()
213
+ self._connection: AsyncConnectionInterface | None = None
214
+ self._connect_failed = False
215
+
216
+ async def handle_async_request(self, request: Request) -> Response:
217
+ timeouts = request.extensions.get("timeout", {})
218
+ sni_hostname = request.extensions.get("sni_hostname", None)
219
+ timeout = timeouts.get("connect", None)
220
+
221
+ async with self._connect_lock:
222
+ if self._connection is None:
223
+ try:
224
+ # Connect to the proxy
225
+ kwargs = {
226
+ "host": self._proxy_origin.host.decode("ascii"),
227
+ "port": self._proxy_origin.port,
228
+ "timeout": timeout,
229
+ }
230
+ async with Trace("connect_tcp", logger, request, kwargs) as trace:
231
+ stream = await self._network_backend.connect_tcp(**kwargs)
232
+ trace.return_value = stream
233
+
234
+ # Connect to the remote host using socks5
235
+ kwargs = {
236
+ "stream": stream,
237
+ "host": self._remote_origin.host.decode("ascii"),
238
+ "port": self._remote_origin.port,
239
+ "auth": self._proxy_auth,
240
+ }
241
+ async with Trace(
242
+ "setup_socks5_connection", logger, request, kwargs
243
+ ) as trace:
244
+ await _init_socks5_connection(**kwargs)
245
+ trace.return_value = stream
246
+
247
+ # Upgrade the stream to SSL
248
+ if self._remote_origin.scheme == b"https":
249
+ ssl_context = (
250
+ default_ssl_context()
251
+ if self._ssl_context is None
252
+ else self._ssl_context
253
+ )
254
+ alpn_protocols = (
255
+ ["http/1.1", "h2"] if self._http2 else ["http/1.1"]
256
+ )
257
+ ssl_context.set_alpn_protocols(alpn_protocols)
258
+
259
+ kwargs = {
260
+ "ssl_context": ssl_context,
261
+ "server_hostname": sni_hostname
262
+ or self._remote_origin.host.decode("ascii"),
263
+ "timeout": timeout,
264
+ }
265
+ async with Trace("start_tls", logger, request, kwargs) as trace:
266
+ stream = await stream.start_tls(**kwargs)
267
+ trace.return_value = stream
268
+
269
+ # Determine if we should be using HTTP/1.1 or HTTP/2
270
+ ssl_object = stream.get_extra_info("ssl_object")
271
+ http2_negotiated = (
272
+ ssl_object is not None
273
+ and ssl_object.selected_alpn_protocol() == "h2"
274
+ )
275
+
276
+ # Create the HTTP/1.1 or HTTP/2 connection
277
+ if http2_negotiated or (
278
+ self._http2 and not self._http1
279
+ ): # pragma: nocover
280
+ from .http2 import AsyncHTTP2Connection
281
+
282
+ self._connection = AsyncHTTP2Connection(
283
+ origin=self._remote_origin,
284
+ stream=stream,
285
+ keepalive_expiry=self._keepalive_expiry,
286
+ )
287
+ else:
288
+ self._connection = AsyncHTTP11Connection(
289
+ origin=self._remote_origin,
290
+ stream=stream,
291
+ keepalive_expiry=self._keepalive_expiry,
292
+ )
293
+ except Exception as exc:
294
+ self._connect_failed = True
295
+ raise exc
296
+ elif not self._connection.is_available(): # pragma: nocover
297
+ raise ConnectionNotAvailable()
298
+
299
+ return await self._connection.handle_async_request(request)
300
+
301
+ def can_handle_request(self, origin: Origin) -> bool:
302
+ return origin == self._remote_origin
303
+
304
+ async def aclose(self) -> None:
305
+ if self._connection is not None:
306
+ await self._connection.aclose()
307
+
308
+ def is_available(self) -> bool:
309
+ if self._connection is None: # pragma: nocover
310
+ # If HTTP/2 support is enabled, and the resulting connection could
311
+ # end up as HTTP/2 then we should indicate the connection as being
312
+ # available to service multiple requests.
313
+ return (
314
+ self._http2
315
+ and (self._remote_origin.scheme == b"https" or not self._http1)
316
+ and not self._connect_failed
317
+ )
318
+ return self._connection.is_available()
319
+
320
+ def has_expired(self) -> bool:
321
+ if self._connection is None: # pragma: nocover
322
+ return self._connect_failed
323
+ return self._connection.has_expired()
324
+
325
+ def is_idle(self) -> bool:
326
+ if self._connection is None: # pragma: nocover
327
+ return self._connect_failed
328
+ return self._connection.is_idle()
329
+
330
+ def is_closed(self) -> bool:
331
+ if self._connection is None: # pragma: nocover
332
+ return self._connect_failed
333
+ return self._connection.is_closed()
334
+
335
+ def info(self) -> str:
336
+ if self._connection is None: # pragma: nocover
337
+ return "CONNECTION FAILED" if self._connect_failed else "CONNECTING"
338
+ return self._connection.info()
339
+
340
+ def __repr__(self) -> str:
341
+ return f"<{self.__class__.__name__} [{self.info()}]>"
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/__init__.py ADDED
File without changes
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/anyio.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ssl
4
+ import typing
5
+
6
+ import anyio
7
+
8
+ from .._exceptions import (
9
+ ConnectError,
10
+ ConnectTimeout,
11
+ ReadError,
12
+ ReadTimeout,
13
+ WriteError,
14
+ WriteTimeout,
15
+ map_exceptions,
16
+ )
17
+ from .._utils import is_socket_readable
18
+ from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
19
+
20
+
21
+ class AnyIOStream(AsyncNetworkStream):
22
+ def __init__(self, stream: anyio.abc.ByteStream) -> None:
23
+ self._stream = stream
24
+
25
+ async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
26
+ exc_map = {
27
+ TimeoutError: ReadTimeout,
28
+ anyio.BrokenResourceError: ReadError,
29
+ anyio.ClosedResourceError: ReadError,
30
+ anyio.EndOfStream: ReadError,
31
+ }
32
+ with map_exceptions(exc_map):
33
+ with anyio.fail_after(timeout):
34
+ try:
35
+ return await self._stream.receive(max_bytes=max_bytes)
36
+ except anyio.EndOfStream: # pragma: nocover
37
+ return b""
38
+
39
+ async def write(self, buffer: bytes, timeout: float | None = None) -> None:
40
+ if not buffer:
41
+ return
42
+
43
+ exc_map = {
44
+ TimeoutError: WriteTimeout,
45
+ anyio.BrokenResourceError: WriteError,
46
+ anyio.ClosedResourceError: WriteError,
47
+ }
48
+ with map_exceptions(exc_map):
49
+ with anyio.fail_after(timeout):
50
+ await self._stream.send(item=buffer)
51
+
52
+ async def aclose(self) -> None:
53
+ await self._stream.aclose()
54
+
55
+ async def start_tls(
56
+ self,
57
+ ssl_context: ssl.SSLContext,
58
+ server_hostname: str | None = None,
59
+ timeout: float | None = None,
60
+ ) -> AsyncNetworkStream:
61
+ exc_map = {
62
+ TimeoutError: ConnectTimeout,
63
+ anyio.BrokenResourceError: ConnectError,
64
+ anyio.EndOfStream: ConnectError,
65
+ ssl.SSLError: ConnectError,
66
+ }
67
+ with map_exceptions(exc_map):
68
+ try:
69
+ with anyio.fail_after(timeout):
70
+ ssl_stream = await anyio.streams.tls.TLSStream.wrap(
71
+ self._stream,
72
+ ssl_context=ssl_context,
73
+ hostname=server_hostname,
74
+ standard_compatible=False,
75
+ server_side=False,
76
+ )
77
+ except Exception as exc: # pragma: nocover
78
+ await self.aclose()
79
+ raise exc
80
+ return AnyIOStream(ssl_stream)
81
+
82
+ def get_extra_info(self, info: str) -> typing.Any:
83
+ if info == "ssl_object":
84
+ return self._stream.extra(anyio.streams.tls.TLSAttribute.ssl_object, None)
85
+ if info == "client_addr":
86
+ return self._stream.extra(anyio.abc.SocketAttribute.local_address, None)
87
+ if info == "server_addr":
88
+ return self._stream.extra(anyio.abc.SocketAttribute.remote_address, None)
89
+ if info == "socket":
90
+ return self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None)
91
+ if info == "is_readable":
92
+ sock = self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None)
93
+ return is_socket_readable(sock)
94
+ return None
95
+
96
+
97
+ class AnyIOBackend(AsyncNetworkBackend):
98
+ async def connect_tcp(
99
+ self,
100
+ host: str,
101
+ port: int,
102
+ timeout: float | None = None,
103
+ local_address: str | None = None,
104
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
105
+ ) -> AsyncNetworkStream: # pragma: nocover
106
+ if socket_options is None:
107
+ socket_options = []
108
+ exc_map = {
109
+ TimeoutError: ConnectTimeout,
110
+ OSError: ConnectError,
111
+ anyio.BrokenResourceError: ConnectError,
112
+ }
113
+ with map_exceptions(exc_map):
114
+ with anyio.fail_after(timeout):
115
+ stream: anyio.abc.ByteStream = await anyio.connect_tcp(
116
+ remote_host=host,
117
+ remote_port=port,
118
+ local_host=local_address,
119
+ )
120
+ # By default TCP sockets opened in `asyncio` include TCP_NODELAY.
121
+ for option in socket_options:
122
+ stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
123
+ return AnyIOStream(stream)
124
+
125
+ async def connect_unix_socket(
126
+ self,
127
+ path: str,
128
+ timeout: float | None = None,
129
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
130
+ ) -> AsyncNetworkStream: # pragma: nocover
131
+ if socket_options is None:
132
+ socket_options = []
133
+ exc_map = {
134
+ TimeoutError: ConnectTimeout,
135
+ OSError: ConnectError,
136
+ anyio.BrokenResourceError: ConnectError,
137
+ }
138
+ with map_exceptions(exc_map):
139
+ with anyio.fail_after(timeout):
140
+ stream: anyio.abc.ByteStream = await anyio.connect_unix(path)
141
+ for option in socket_options:
142
+ stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
143
+ return AnyIOStream(stream)
144
+
145
+ async def sleep(self, seconds: float) -> None:
146
+ await anyio.sleep(seconds) # pragma: nocover
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/auto.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+
5
+ from .._synchronization import current_async_library
6
+ from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
7
+
8
+
9
+ class AutoBackend(AsyncNetworkBackend):
10
+ async def _init_backend(self) -> None:
11
+ if not (hasattr(self, "_backend")):
12
+ backend = current_async_library()
13
+ if backend == "trio":
14
+ from .trio import TrioBackend
15
+
16
+ self._backend: AsyncNetworkBackend = TrioBackend()
17
+ else:
18
+ from .anyio import AnyIOBackend
19
+
20
+ self._backend = AnyIOBackend()
21
+
22
+ async def connect_tcp(
23
+ self,
24
+ host: str,
25
+ port: int,
26
+ timeout: float | None = None,
27
+ local_address: str | None = None,
28
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
29
+ ) -> AsyncNetworkStream:
30
+ await self._init_backend()
31
+ return await self._backend.connect_tcp(
32
+ host,
33
+ port,
34
+ timeout=timeout,
35
+ local_address=local_address,
36
+ socket_options=socket_options,
37
+ )
38
+
39
+ async def connect_unix_socket(
40
+ self,
41
+ path: str,
42
+ timeout: float | None = None,
43
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
44
+ ) -> AsyncNetworkStream: # pragma: nocover
45
+ await self._init_backend()
46
+ return await self._backend.connect_unix_socket(
47
+ path, timeout=timeout, socket_options=socket_options
48
+ )
49
+
50
+ async def sleep(self, seconds: float) -> None: # pragma: nocover
51
+ await self._init_backend()
52
+ return await self._backend.sleep(seconds)
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/base.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ssl
4
+ import time
5
+ import typing
6
+
7
+ SOCKET_OPTION = typing.Union[
8
+ typing.Tuple[int, int, int],
9
+ typing.Tuple[int, int, typing.Union[bytes, bytearray]],
10
+ typing.Tuple[int, int, None, int],
11
+ ]
12
+
13
+
14
+ class NetworkStream:
15
+ def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
16
+ raise NotImplementedError() # pragma: nocover
17
+
18
+ def write(self, buffer: bytes, timeout: float | None = None) -> None:
19
+ raise NotImplementedError() # pragma: nocover
20
+
21
+ def close(self) -> None:
22
+ raise NotImplementedError() # pragma: nocover
23
+
24
+ def start_tls(
25
+ self,
26
+ ssl_context: ssl.SSLContext,
27
+ server_hostname: str | None = None,
28
+ timeout: float | None = None,
29
+ ) -> NetworkStream:
30
+ raise NotImplementedError() # pragma: nocover
31
+
32
+ def get_extra_info(self, info: str) -> typing.Any:
33
+ return None # pragma: nocover
34
+
35
+
36
+ class NetworkBackend:
37
+ def connect_tcp(
38
+ self,
39
+ host: str,
40
+ port: int,
41
+ timeout: float | None = None,
42
+ local_address: str | None = None,
43
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
44
+ ) -> NetworkStream:
45
+ raise NotImplementedError() # pragma: nocover
46
+
47
+ def connect_unix_socket(
48
+ self,
49
+ path: str,
50
+ timeout: float | None = None,
51
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
52
+ ) -> NetworkStream:
53
+ raise NotImplementedError() # pragma: nocover
54
+
55
+ def sleep(self, seconds: float) -> None:
56
+ time.sleep(seconds) # pragma: nocover
57
+
58
+
59
+ class AsyncNetworkStream:
60
+ async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
61
+ raise NotImplementedError() # pragma: nocover
62
+
63
+ async def write(self, buffer: bytes, timeout: float | None = None) -> None:
64
+ raise NotImplementedError() # pragma: nocover
65
+
66
+ async def aclose(self) -> None:
67
+ raise NotImplementedError() # pragma: nocover
68
+
69
+ async def start_tls(
70
+ self,
71
+ ssl_context: ssl.SSLContext,
72
+ server_hostname: str | None = None,
73
+ timeout: float | None = None,
74
+ ) -> AsyncNetworkStream:
75
+ raise NotImplementedError() # pragma: nocover
76
+
77
+ def get_extra_info(self, info: str) -> typing.Any:
78
+ return None # pragma: nocover
79
+
80
+
81
+ class AsyncNetworkBackend:
82
+ async def connect_tcp(
83
+ self,
84
+ host: str,
85
+ port: int,
86
+ timeout: float | None = None,
87
+ local_address: str | None = None,
88
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
89
+ ) -> AsyncNetworkStream:
90
+ raise NotImplementedError() # pragma: nocover
91
+
92
+ async def connect_unix_socket(
93
+ self,
94
+ path: str,
95
+ timeout: float | None = None,
96
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
97
+ ) -> AsyncNetworkStream:
98
+ raise NotImplementedError() # pragma: nocover
99
+
100
+ async def sleep(self, seconds: float) -> None:
101
+ raise NotImplementedError() # pragma: nocover
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/mock.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ssl
4
+ import typing
5
+
6
+ from .._exceptions import ReadError
7
+ from .base import (
8
+ SOCKET_OPTION,
9
+ AsyncNetworkBackend,
10
+ AsyncNetworkStream,
11
+ NetworkBackend,
12
+ NetworkStream,
13
+ )
14
+
15
+
16
+ class MockSSLObject:
17
+ def __init__(self, http2: bool):
18
+ self._http2 = http2
19
+
20
+ def selected_alpn_protocol(self) -> str:
21
+ return "h2" if self._http2 else "http/1.1"
22
+
23
+
24
+ class MockStream(NetworkStream):
25
+ def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
26
+ self._buffer = buffer
27
+ self._http2 = http2
28
+ self._closed = False
29
+
30
+ def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
31
+ if self._closed:
32
+ raise ReadError("Connection closed")
33
+ if not self._buffer:
34
+ return b""
35
+ return self._buffer.pop(0)
36
+
37
+ def write(self, buffer: bytes, timeout: float | None = None) -> None:
38
+ pass
39
+
40
+ def close(self) -> None:
41
+ self._closed = True
42
+
43
+ def start_tls(
44
+ self,
45
+ ssl_context: ssl.SSLContext,
46
+ server_hostname: str | None = None,
47
+ timeout: float | None = None,
48
+ ) -> NetworkStream:
49
+ return self
50
+
51
+ def get_extra_info(self, info: str) -> typing.Any:
52
+ return MockSSLObject(http2=self._http2) if info == "ssl_object" else None
53
+
54
+ def __repr__(self) -> str:
55
+ return "<httpcore.MockStream>"
56
+
57
+
58
+ class MockBackend(NetworkBackend):
59
+ def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
60
+ self._buffer = buffer
61
+ self._http2 = http2
62
+
63
+ def connect_tcp(
64
+ self,
65
+ host: str,
66
+ port: int,
67
+ timeout: float | None = None,
68
+ local_address: str | None = None,
69
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
70
+ ) -> NetworkStream:
71
+ return MockStream(list(self._buffer), http2=self._http2)
72
+
73
+ def connect_unix_socket(
74
+ self,
75
+ path: str,
76
+ timeout: float | None = None,
77
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
78
+ ) -> NetworkStream:
79
+ return MockStream(list(self._buffer), http2=self._http2)
80
+
81
+ def sleep(self, seconds: float) -> None:
82
+ pass
83
+
84
+
85
+ class AsyncMockStream(AsyncNetworkStream):
86
+ def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
87
+ self._buffer = buffer
88
+ self._http2 = http2
89
+ self._closed = False
90
+
91
+ async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
92
+ if self._closed:
93
+ raise ReadError("Connection closed")
94
+ if not self._buffer:
95
+ return b""
96
+ return self._buffer.pop(0)
97
+
98
+ async def write(self, buffer: bytes, timeout: float | None = None) -> None:
99
+ pass
100
+
101
+ async def aclose(self) -> None:
102
+ self._closed = True
103
+
104
+ async def start_tls(
105
+ self,
106
+ ssl_context: ssl.SSLContext,
107
+ server_hostname: str | None = None,
108
+ timeout: float | None = None,
109
+ ) -> AsyncNetworkStream:
110
+ return self
111
+
112
+ def get_extra_info(self, info: str) -> typing.Any:
113
+ return MockSSLObject(http2=self._http2) if info == "ssl_object" else None
114
+
115
+ def __repr__(self) -> str:
116
+ return "<httpcore.AsyncMockStream>"
117
+
118
+
119
+ class AsyncMockBackend(AsyncNetworkBackend):
120
+ def __init__(self, buffer: list[bytes], http2: bool = False) -> None:
121
+ self._buffer = buffer
122
+ self._http2 = http2
123
+
124
+ async def connect_tcp(
125
+ self,
126
+ host: str,
127
+ port: int,
128
+ timeout: float | None = None,
129
+ local_address: str | None = None,
130
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
131
+ ) -> AsyncNetworkStream:
132
+ return AsyncMockStream(list(self._buffer), http2=self._http2)
133
+
134
+ async def connect_unix_socket(
135
+ self,
136
+ path: str,
137
+ timeout: float | None = None,
138
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
139
+ ) -> AsyncNetworkStream:
140
+ return AsyncMockStream(list(self._buffer), http2=self._http2)
141
+
142
+ async def sleep(self, seconds: float) -> None:
143
+ pass
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/sync.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import socket
5
+ import ssl
6
+ import sys
7
+ import typing
8
+
9
+ from .._exceptions import (
10
+ ConnectError,
11
+ ConnectTimeout,
12
+ ExceptionMapping,
13
+ ReadError,
14
+ ReadTimeout,
15
+ WriteError,
16
+ WriteTimeout,
17
+ map_exceptions,
18
+ )
19
+ from .._utils import is_socket_readable
20
+ from .base import SOCKET_OPTION, NetworkBackend, NetworkStream
21
+
22
+
23
+ class TLSinTLSStream(NetworkStream): # pragma: no cover
24
+ """
25
+ Because the standard `SSLContext.wrap_socket` method does
26
+ not work for `SSLSocket` objects, we need this class
27
+ to implement TLS stream using an underlying `SSLObject`
28
+ instance in order to support TLS on top of TLS.
29
+ """
30
+
31
+ # Defined in RFC 8449
32
+ TLS_RECORD_SIZE = 16384
33
+
34
+ def __init__(
35
+ self,
36
+ sock: socket.socket,
37
+ ssl_context: ssl.SSLContext,
38
+ server_hostname: str | None = None,
39
+ timeout: float | None = None,
40
+ ):
41
+ self._sock = sock
42
+ self._incoming = ssl.MemoryBIO()
43
+ self._outgoing = ssl.MemoryBIO()
44
+
45
+ self.ssl_obj = ssl_context.wrap_bio(
46
+ incoming=self._incoming,
47
+ outgoing=self._outgoing,
48
+ server_hostname=server_hostname,
49
+ )
50
+
51
+ self._sock.settimeout(timeout)
52
+ self._perform_io(self.ssl_obj.do_handshake)
53
+
54
+ def _perform_io(
55
+ self,
56
+ func: typing.Callable[..., typing.Any],
57
+ ) -> typing.Any:
58
+ ret = None
59
+
60
+ while True:
61
+ errno = None
62
+ try:
63
+ ret = func()
64
+ except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e:
65
+ errno = e.errno
66
+
67
+ self._sock.sendall(self._outgoing.read())
68
+
69
+ if errno == ssl.SSL_ERROR_WANT_READ:
70
+ buf = self._sock.recv(self.TLS_RECORD_SIZE)
71
+
72
+ if buf:
73
+ self._incoming.write(buf)
74
+ else:
75
+ self._incoming.write_eof()
76
+ if errno is None:
77
+ return ret
78
+
79
+ def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
80
+ exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError}
81
+ with map_exceptions(exc_map):
82
+ self._sock.settimeout(timeout)
83
+ return typing.cast(
84
+ bytes, self._perform_io(functools.partial(self.ssl_obj.read, max_bytes))
85
+ )
86
+
87
+ def write(self, buffer: bytes, timeout: float | None = None) -> None:
88
+ exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError}
89
+ with map_exceptions(exc_map):
90
+ self._sock.settimeout(timeout)
91
+ while buffer:
92
+ nsent = self._perform_io(functools.partial(self.ssl_obj.write, buffer))
93
+ buffer = buffer[nsent:]
94
+
95
+ def close(self) -> None:
96
+ self._sock.close()
97
+
98
+ def start_tls(
99
+ self,
100
+ ssl_context: ssl.SSLContext,
101
+ server_hostname: str | None = None,
102
+ timeout: float | None = None,
103
+ ) -> NetworkStream:
104
+ raise NotImplementedError()
105
+
106
+ def get_extra_info(self, info: str) -> typing.Any:
107
+ if info == "ssl_object":
108
+ return self.ssl_obj
109
+ if info == "client_addr":
110
+ return self._sock.getsockname()
111
+ if info == "server_addr":
112
+ return self._sock.getpeername()
113
+ if info == "socket":
114
+ return self._sock
115
+ if info == "is_readable":
116
+ return is_socket_readable(self._sock)
117
+ return None
118
+
119
+
120
+ class SyncStream(NetworkStream):
121
+ def __init__(self, sock: socket.socket) -> None:
122
+ self._sock = sock
123
+
124
+ def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
125
+ exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError}
126
+ with map_exceptions(exc_map):
127
+ self._sock.settimeout(timeout)
128
+ return self._sock.recv(max_bytes)
129
+
130
+ def write(self, buffer: bytes, timeout: float | None = None) -> None:
131
+ if not buffer:
132
+ return
133
+
134
+ exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError}
135
+ with map_exceptions(exc_map):
136
+ while buffer:
137
+ self._sock.settimeout(timeout)
138
+ n = self._sock.send(buffer)
139
+ buffer = buffer[n:]
140
+
141
+ def close(self) -> None:
142
+ self._sock.close()
143
+
144
+ def start_tls(
145
+ self,
146
+ ssl_context: ssl.SSLContext,
147
+ server_hostname: str | None = None,
148
+ timeout: float | None = None,
149
+ ) -> NetworkStream:
150
+ exc_map: ExceptionMapping = {
151
+ socket.timeout: ConnectTimeout,
152
+ OSError: ConnectError,
153
+ }
154
+ with map_exceptions(exc_map):
155
+ try:
156
+ if isinstance(self._sock, ssl.SSLSocket): # pragma: no cover
157
+ # If the underlying socket has already been upgraded
158
+ # to the TLS layer (i.e. is an instance of SSLSocket),
159
+ # we need some additional smarts to support TLS-in-TLS.
160
+ return TLSinTLSStream(
161
+ self._sock, ssl_context, server_hostname, timeout
162
+ )
163
+ else:
164
+ self._sock.settimeout(timeout)
165
+ sock = ssl_context.wrap_socket(
166
+ self._sock, server_hostname=server_hostname
167
+ )
168
+ except Exception as exc: # pragma: nocover
169
+ self.close()
170
+ raise exc
171
+ return SyncStream(sock)
172
+
173
+ def get_extra_info(self, info: str) -> typing.Any:
174
+ if info == "ssl_object" and isinstance(self._sock, ssl.SSLSocket):
175
+ return self._sock._sslobj # type: ignore
176
+ if info == "client_addr":
177
+ return self._sock.getsockname()
178
+ if info == "server_addr":
179
+ return self._sock.getpeername()
180
+ if info == "socket":
181
+ return self._sock
182
+ if info == "is_readable":
183
+ return is_socket_readable(self._sock)
184
+ return None
185
+
186
+
187
+ class SyncBackend(NetworkBackend):
188
+ def connect_tcp(
189
+ self,
190
+ host: str,
191
+ port: int,
192
+ timeout: float | None = None,
193
+ local_address: str | None = None,
194
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
195
+ ) -> NetworkStream:
196
+ # Note that we automatically include `TCP_NODELAY`
197
+ # in addition to any other custom socket options.
198
+ if socket_options is None:
199
+ socket_options = [] # pragma: no cover
200
+ address = (host, port)
201
+ source_address = None if local_address is None else (local_address, 0)
202
+ exc_map: ExceptionMapping = {
203
+ socket.timeout: ConnectTimeout,
204
+ OSError: ConnectError,
205
+ }
206
+
207
+ with map_exceptions(exc_map):
208
+ sock = socket.create_connection(
209
+ address,
210
+ timeout,
211
+ source_address=source_address,
212
+ )
213
+ for option in socket_options:
214
+ sock.setsockopt(*option) # pragma: no cover
215
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
216
+ return SyncStream(sock)
217
+
218
+ def connect_unix_socket(
219
+ self,
220
+ path: str,
221
+ timeout: float | None = None,
222
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
223
+ ) -> NetworkStream: # pragma: nocover
224
+ if sys.platform == "win32":
225
+ raise RuntimeError(
226
+ "Attempted to connect to a UNIX socket on a Windows system."
227
+ )
228
+ if socket_options is None:
229
+ socket_options = []
230
+
231
+ exc_map: ExceptionMapping = {
232
+ socket.timeout: ConnectTimeout,
233
+ OSError: ConnectError,
234
+ }
235
+ with map_exceptions(exc_map):
236
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
237
+ for option in socket_options:
238
+ sock.setsockopt(*option)
239
+ sock.settimeout(timeout)
240
+ sock.connect(path)
241
+ return SyncStream(sock)
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/trio.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ssl
4
+ import typing
5
+
6
+ import trio
7
+
8
+ from .._exceptions import (
9
+ ConnectError,
10
+ ConnectTimeout,
11
+ ExceptionMapping,
12
+ ReadError,
13
+ ReadTimeout,
14
+ WriteError,
15
+ WriteTimeout,
16
+ map_exceptions,
17
+ )
18
+ from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
19
+
20
+
21
+ class TrioStream(AsyncNetworkStream):
22
+ def __init__(self, stream: trio.abc.Stream) -> None:
23
+ self._stream = stream
24
+
25
+ async def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
26
+ timeout_or_inf = float("inf") if timeout is None else timeout
27
+ exc_map: ExceptionMapping = {
28
+ trio.TooSlowError: ReadTimeout,
29
+ trio.BrokenResourceError: ReadError,
30
+ trio.ClosedResourceError: ReadError,
31
+ }
32
+ with map_exceptions(exc_map):
33
+ with trio.fail_after(timeout_or_inf):
34
+ data: bytes = await self._stream.receive_some(max_bytes=max_bytes)
35
+ return data
36
+
37
+ async def write(self, buffer: bytes, timeout: float | None = None) -> None:
38
+ if not buffer:
39
+ return
40
+
41
+ timeout_or_inf = float("inf") if timeout is None else timeout
42
+ exc_map: ExceptionMapping = {
43
+ trio.TooSlowError: WriteTimeout,
44
+ trio.BrokenResourceError: WriteError,
45
+ trio.ClosedResourceError: WriteError,
46
+ }
47
+ with map_exceptions(exc_map):
48
+ with trio.fail_after(timeout_or_inf):
49
+ await self._stream.send_all(data=buffer)
50
+
51
+ async def aclose(self) -> None:
52
+ await self._stream.aclose()
53
+
54
+ async def start_tls(
55
+ self,
56
+ ssl_context: ssl.SSLContext,
57
+ server_hostname: str | None = None,
58
+ timeout: float | None = None,
59
+ ) -> AsyncNetworkStream:
60
+ timeout_or_inf = float("inf") if timeout is None else timeout
61
+ exc_map: ExceptionMapping = {
62
+ trio.TooSlowError: ConnectTimeout,
63
+ trio.BrokenResourceError: ConnectError,
64
+ }
65
+ ssl_stream = trio.SSLStream(
66
+ self._stream,
67
+ ssl_context=ssl_context,
68
+ server_hostname=server_hostname,
69
+ https_compatible=True,
70
+ server_side=False,
71
+ )
72
+ with map_exceptions(exc_map):
73
+ try:
74
+ with trio.fail_after(timeout_or_inf):
75
+ await ssl_stream.do_handshake()
76
+ except Exception as exc: # pragma: nocover
77
+ await self.aclose()
78
+ raise exc
79
+ return TrioStream(ssl_stream)
80
+
81
+ def get_extra_info(self, info: str) -> typing.Any:
82
+ if info == "ssl_object" and isinstance(self._stream, trio.SSLStream):
83
+ # Type checkers cannot see `_ssl_object` attribute because trio._ssl.SSLStream uses __getattr__/__setattr__.
84
+ # Tracked at https://github.com/python-trio/trio/issues/542
85
+ return self._stream._ssl_object # type: ignore[attr-defined]
86
+ if info == "client_addr":
87
+ return self._get_socket_stream().socket.getsockname()
88
+ if info == "server_addr":
89
+ return self._get_socket_stream().socket.getpeername()
90
+ if info == "socket":
91
+ stream = self._stream
92
+ while isinstance(stream, trio.SSLStream):
93
+ stream = stream.transport_stream
94
+ assert isinstance(stream, trio.SocketStream)
95
+ return stream.socket
96
+ if info == "is_readable":
97
+ socket = self.get_extra_info("socket")
98
+ return socket.is_readable()
99
+ return None
100
+
101
+ def _get_socket_stream(self) -> trio.SocketStream:
102
+ stream = self._stream
103
+ while isinstance(stream, trio.SSLStream):
104
+ stream = stream.transport_stream
105
+ assert isinstance(stream, trio.SocketStream)
106
+ return stream
107
+
108
+
109
+ class TrioBackend(AsyncNetworkBackend):
110
+ async def connect_tcp(
111
+ self,
112
+ host: str,
113
+ port: int,
114
+ timeout: float | None = None,
115
+ local_address: str | None = None,
116
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
117
+ ) -> AsyncNetworkStream:
118
+ # By default for TCP sockets, trio enables TCP_NODELAY.
119
+ # https://trio.readthedocs.io/en/stable/reference-io.html#trio.SocketStream
120
+ if socket_options is None:
121
+ socket_options = [] # pragma: no cover
122
+ timeout_or_inf = float("inf") if timeout is None else timeout
123
+ exc_map: ExceptionMapping = {
124
+ trio.TooSlowError: ConnectTimeout,
125
+ trio.BrokenResourceError: ConnectError,
126
+ OSError: ConnectError,
127
+ }
128
+ with map_exceptions(exc_map):
129
+ with trio.fail_after(timeout_or_inf):
130
+ stream: trio.abc.Stream = await trio.open_tcp_stream(
131
+ host=host, port=port, local_address=local_address
132
+ )
133
+ for option in socket_options:
134
+ stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
135
+ return TrioStream(stream)
136
+
137
+ async def connect_unix_socket(
138
+ self,
139
+ path: str,
140
+ timeout: float | None = None,
141
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
142
+ ) -> AsyncNetworkStream: # pragma: nocover
143
+ if socket_options is None:
144
+ socket_options = []
145
+ timeout_or_inf = float("inf") if timeout is None else timeout
146
+ exc_map: ExceptionMapping = {
147
+ trio.TooSlowError: ConnectTimeout,
148
+ trio.BrokenResourceError: ConnectError,
149
+ OSError: ConnectError,
150
+ }
151
+ with map_exceptions(exc_map):
152
+ with trio.fail_after(timeout_or_inf):
153
+ stream: trio.abc.Stream = await trio.open_unix_socket(path)
154
+ for option in socket_options:
155
+ stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover
156
+ return TrioStream(stream)
157
+
158
+ async def sleep(self, seconds: float) -> None:
159
+ await trio.sleep(seconds) # pragma: nocover
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .connection import HTTPConnection
2
+ from .connection_pool import ConnectionPool
3
+ from .http11 import HTTP11Connection
4
+ from .http_proxy import HTTPProxy
5
+ from .interfaces import ConnectionInterface
6
+
7
+ try:
8
+ from .http2 import HTTP2Connection
9
+ except ImportError: # pragma: nocover
10
+
11
+ class HTTP2Connection: # type: ignore
12
+ def __init__(self, *args, **kwargs) -> None: # type: ignore
13
+ raise RuntimeError(
14
+ "Attempted to use http2 support, but the `h2` package is not "
15
+ "installed. Use 'pip install httpcore[http2]'."
16
+ )
17
+
18
+
19
+ try:
20
+ from .socks_proxy import SOCKSProxy
21
+ except ImportError: # pragma: nocover
22
+
23
+ class SOCKSProxy: # type: ignore
24
+ def __init__(self, *args, **kwargs) -> None: # type: ignore
25
+ raise RuntimeError(
26
+ "Attempted to use SOCKS support, but the `socksio` package is not "
27
+ "installed. Use 'pip install httpcore[socks]'."
28
+ )
29
+
30
+
31
+ __all__ = [
32
+ "HTTPConnection",
33
+ "ConnectionPool",
34
+ "HTTPProxy",
35
+ "HTTP11Connection",
36
+ "HTTP2Connection",
37
+ "ConnectionInterface",
38
+ "SOCKSProxy",
39
+ ]
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import logging
5
+ import ssl
6
+ import types
7
+ import typing
8
+
9
+ from .._backends.sync import SyncBackend
10
+ from .._backends.base import SOCKET_OPTION, NetworkBackend, NetworkStream
11
+ from .._exceptions import ConnectError, ConnectTimeout
12
+ from .._models import Origin, Request, Response
13
+ from .._ssl import default_ssl_context
14
+ from .._synchronization import Lock
15
+ from .._trace import Trace
16
+ from .http11 import HTTP11Connection
17
+ from .interfaces import ConnectionInterface
18
+
19
+ RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc.
20
+
21
+
22
+ logger = logging.getLogger("httpcore.connection")
23
+
24
+
25
+ def exponential_backoff(factor: float) -> typing.Iterator[float]:
26
+ """
27
+ Generate a geometric sequence that has a ratio of 2 and starts with 0.
28
+
29
+ For example:
30
+ - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...`
31
+ - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...`
32
+ """
33
+ yield 0
34
+ for n in itertools.count():
35
+ yield factor * 2**n
36
+
37
+
38
+ class HTTPConnection(ConnectionInterface):
39
+ def __init__(
40
+ self,
41
+ origin: Origin,
42
+ ssl_context: ssl.SSLContext | None = None,
43
+ keepalive_expiry: float | None = None,
44
+ http1: bool = True,
45
+ http2: bool = False,
46
+ retries: int = 0,
47
+ local_address: str | None = None,
48
+ uds: str | None = None,
49
+ network_backend: NetworkBackend | None = None,
50
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
51
+ ) -> None:
52
+ self._origin = origin
53
+ self._ssl_context = ssl_context
54
+ self._keepalive_expiry = keepalive_expiry
55
+ self._http1 = http1
56
+ self._http2 = http2
57
+ self._retries = retries
58
+ self._local_address = local_address
59
+ self._uds = uds
60
+
61
+ self._network_backend: NetworkBackend = (
62
+ SyncBackend() if network_backend is None else network_backend
63
+ )
64
+ self._connection: ConnectionInterface | None = None
65
+ self._connect_failed: bool = False
66
+ self._request_lock = Lock()
67
+ self._socket_options = socket_options
68
+
69
+ def handle_request(self, request: Request) -> Response:
70
+ if not self.can_handle_request(request.url.origin):
71
+ raise RuntimeError(
72
+ f"Attempted to send request to {request.url.origin} on connection to {self._origin}"
73
+ )
74
+
75
+ try:
76
+ with self._request_lock:
77
+ if self._connection is None:
78
+ stream = self._connect(request)
79
+
80
+ ssl_object = stream.get_extra_info("ssl_object")
81
+ http2_negotiated = (
82
+ ssl_object is not None
83
+ and ssl_object.selected_alpn_protocol() == "h2"
84
+ )
85
+ if http2_negotiated or (self._http2 and not self._http1):
86
+ from .http2 import HTTP2Connection
87
+
88
+ self._connection = HTTP2Connection(
89
+ origin=self._origin,
90
+ stream=stream,
91
+ keepalive_expiry=self._keepalive_expiry,
92
+ )
93
+ else:
94
+ self._connection = HTTP11Connection(
95
+ origin=self._origin,
96
+ stream=stream,
97
+ keepalive_expiry=self._keepalive_expiry,
98
+ )
99
+ except BaseException as exc:
100
+ self._connect_failed = True
101
+ raise exc
102
+
103
+ return self._connection.handle_request(request)
104
+
105
+ def _connect(self, request: Request) -> NetworkStream:
106
+ timeouts = request.extensions.get("timeout", {})
107
+ sni_hostname = request.extensions.get("sni_hostname", None)
108
+ timeout = timeouts.get("connect", None)
109
+
110
+ retries_left = self._retries
111
+ delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
112
+
113
+ while True:
114
+ try:
115
+ if self._uds is None:
116
+ kwargs = {
117
+ "host": self._origin.host.decode("ascii"),
118
+ "port": self._origin.port,
119
+ "local_address": self._local_address,
120
+ "timeout": timeout,
121
+ "socket_options": self._socket_options,
122
+ }
123
+ with Trace("connect_tcp", logger, request, kwargs) as trace:
124
+ stream = self._network_backend.connect_tcp(**kwargs)
125
+ trace.return_value = stream
126
+ else:
127
+ kwargs = {
128
+ "path": self._uds,
129
+ "timeout": timeout,
130
+ "socket_options": self._socket_options,
131
+ }
132
+ with Trace(
133
+ "connect_unix_socket", logger, request, kwargs
134
+ ) as trace:
135
+ stream = self._network_backend.connect_unix_socket(
136
+ **kwargs
137
+ )
138
+ trace.return_value = stream
139
+
140
+ if self._origin.scheme in (b"https", b"wss"):
141
+ ssl_context = (
142
+ default_ssl_context()
143
+ if self._ssl_context is None
144
+ else self._ssl_context
145
+ )
146
+ alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"]
147
+ ssl_context.set_alpn_protocols(alpn_protocols)
148
+
149
+ kwargs = {
150
+ "ssl_context": ssl_context,
151
+ "server_hostname": sni_hostname
152
+ or self._origin.host.decode("ascii"),
153
+ "timeout": timeout,
154
+ }
155
+ with Trace("start_tls", logger, request, kwargs) as trace:
156
+ stream = stream.start_tls(**kwargs)
157
+ trace.return_value = stream
158
+ return stream
159
+ except (ConnectError, ConnectTimeout):
160
+ if retries_left <= 0:
161
+ raise
162
+ retries_left -= 1
163
+ delay = next(delays)
164
+ with Trace("retry", logger, request, kwargs) as trace:
165
+ self._network_backend.sleep(delay)
166
+
167
+ def can_handle_request(self, origin: Origin) -> bool:
168
+ return origin == self._origin
169
+
170
+ def close(self) -> None:
171
+ if self._connection is not None:
172
+ with Trace("close", logger, None, {}):
173
+ self._connection.close()
174
+
175
+ def is_available(self) -> bool:
176
+ if self._connection is None:
177
+ # If HTTP/2 support is enabled, and the resulting connection could
178
+ # end up as HTTP/2 then we should indicate the connection as being
179
+ # available to service multiple requests.
180
+ return (
181
+ self._http2
182
+ and (self._origin.scheme == b"https" or not self._http1)
183
+ and not self._connect_failed
184
+ )
185
+ return self._connection.is_available()
186
+
187
+ def has_expired(self) -> bool:
188
+ if self._connection is None:
189
+ return self._connect_failed
190
+ return self._connection.has_expired()
191
+
192
+ def is_idle(self) -> bool:
193
+ if self._connection is None:
194
+ return self._connect_failed
195
+ return self._connection.is_idle()
196
+
197
+ def is_closed(self) -> bool:
198
+ if self._connection is None:
199
+ return self._connect_failed
200
+ return self._connection.is_closed()
201
+
202
+ def info(self) -> str:
203
+ if self._connection is None:
204
+ return "CONNECTION FAILED" if self._connect_failed else "CONNECTING"
205
+ return self._connection.info()
206
+
207
+ def __repr__(self) -> str:
208
+ return f"<{self.__class__.__name__} [{self.info()}]>"
209
+
210
+ # These context managers are not used in the standard flow, but are
211
+ # useful for testing or working with connection instances directly.
212
+
213
+ def __enter__(self) -> HTTPConnection:
214
+ return self
215
+
216
+ def __exit__(
217
+ self,
218
+ exc_type: type[BaseException] | None = None,
219
+ exc_value: BaseException | None = None,
220
+ traceback: types.TracebackType | None = None,
221
+ ) -> None:
222
+ self.close()
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection_pool.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ssl
4
+ import sys
5
+ import types
6
+ import typing
7
+
8
+ from .._backends.sync import SyncBackend
9
+ from .._backends.base import SOCKET_OPTION, NetworkBackend
10
+ from .._exceptions import ConnectionNotAvailable, UnsupportedProtocol
11
+ from .._models import Origin, Proxy, Request, Response
12
+ from .._synchronization import Event, ShieldCancellation, ThreadLock
13
+ from .connection import HTTPConnection
14
+ from .interfaces import ConnectionInterface, RequestInterface
15
+
16
+
17
+ class PoolRequest:
18
+ def __init__(self, request: Request) -> None:
19
+ self.request = request
20
+ self.connection: ConnectionInterface | None = None
21
+ self._connection_acquired = Event()
22
+
23
+ def assign_to_connection(self, connection: ConnectionInterface | None) -> None:
24
+ self.connection = connection
25
+ self._connection_acquired.set()
26
+
27
+ def clear_connection(self) -> None:
28
+ self.connection = None
29
+ self._connection_acquired = Event()
30
+
31
+ def wait_for_connection(
32
+ self, timeout: float | None = None
33
+ ) -> ConnectionInterface:
34
+ if self.connection is None:
35
+ self._connection_acquired.wait(timeout=timeout)
36
+ assert self.connection is not None
37
+ return self.connection
38
+
39
+ def is_queued(self) -> bool:
40
+ return self.connection is None
41
+
42
+
43
+ class ConnectionPool(RequestInterface):
44
+ """
45
+ A connection pool for making HTTP requests.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ ssl_context: ssl.SSLContext | None = None,
51
+ proxy: Proxy | None = None,
52
+ max_connections: int | None = 10,
53
+ max_keepalive_connections: int | None = None,
54
+ keepalive_expiry: float | None = None,
55
+ http1: bool = True,
56
+ http2: bool = False,
57
+ retries: int = 0,
58
+ local_address: str | None = None,
59
+ uds: str | None = None,
60
+ network_backend: NetworkBackend | None = None,
61
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
62
+ ) -> None:
63
+ """
64
+ A connection pool for making HTTP requests.
65
+
66
+ Parameters:
67
+ ssl_context: An SSL context to use for verifying connections.
68
+ If not specified, the default `httpcore.default_ssl_context()`
69
+ will be used.
70
+ max_connections: The maximum number of concurrent HTTP connections that
71
+ the pool should allow. Any attempt to send a request on a pool that
72
+ would exceed this amount will block until a connection is available.
73
+ max_keepalive_connections: The maximum number of idle HTTP connections
74
+ that will be maintained in the pool.
75
+ keepalive_expiry: The duration in seconds that an idle HTTP connection
76
+ may be maintained for before being expired from the pool.
77
+ http1: A boolean indicating if HTTP/1.1 requests should be supported
78
+ by the connection pool. Defaults to True.
79
+ http2: A boolean indicating if HTTP/2 requests should be supported by
80
+ the connection pool. Defaults to False.
81
+ retries: The maximum number of retries when trying to establish a
82
+ connection.
83
+ local_address: Local address to connect from. Can also be used to connect
84
+ using a particular address family. Using `local_address="0.0.0.0"`
85
+ will connect using an `AF_INET` address (IPv4), while using
86
+ `local_address="::"` will connect using an `AF_INET6` address (IPv6).
87
+ uds: Path to a Unix Domain Socket to use instead of TCP sockets.
88
+ network_backend: A backend instance to use for handling network I/O.
89
+ socket_options: Socket options that have to be included
90
+ in the TCP socket when the connection was established.
91
+ """
92
+ self._ssl_context = ssl_context
93
+ self._proxy = proxy
94
+ self._max_connections = (
95
+ sys.maxsize if max_connections is None else max_connections
96
+ )
97
+ self._max_keepalive_connections = (
98
+ sys.maxsize
99
+ if max_keepalive_connections is None
100
+ else max_keepalive_connections
101
+ )
102
+ self._max_keepalive_connections = min(
103
+ self._max_connections, self._max_keepalive_connections
104
+ )
105
+
106
+ self._keepalive_expiry = keepalive_expiry
107
+ self._http1 = http1
108
+ self._http2 = http2
109
+ self._retries = retries
110
+ self._local_address = local_address
111
+ self._uds = uds
112
+
113
+ self._network_backend = (
114
+ SyncBackend() if network_backend is None else network_backend
115
+ )
116
+ self._socket_options = socket_options
117
+
118
+ # The mutable state on a connection pool is the queue of incoming requests,
119
+ # and the set of connections that are servicing those requests.
120
+ self._connections: list[ConnectionInterface] = []
121
+ self._requests: list[PoolRequest] = []
122
+
123
+ # We only mutate the state of the connection pool within an 'optional_thread_lock'
124
+ # context. This holds a threading lock unless we're running in async mode,
125
+ # in which case it is a no-op.
126
+ self._optional_thread_lock = ThreadLock()
127
+
128
+ def create_connection(self, origin: Origin) -> ConnectionInterface:
129
+ if self._proxy is not None:
130
+ if self._proxy.url.scheme in (b"socks5", b"socks5h"):
131
+ from .socks_proxy import Socks5Connection
132
+
133
+ return Socks5Connection(
134
+ proxy_origin=self._proxy.url.origin,
135
+ proxy_auth=self._proxy.auth,
136
+ remote_origin=origin,
137
+ ssl_context=self._ssl_context,
138
+ keepalive_expiry=self._keepalive_expiry,
139
+ http1=self._http1,
140
+ http2=self._http2,
141
+ network_backend=self._network_backend,
142
+ )
143
+ elif origin.scheme == b"http":
144
+ from .http_proxy import ForwardHTTPConnection
145
+
146
+ return ForwardHTTPConnection(
147
+ proxy_origin=self._proxy.url.origin,
148
+ proxy_headers=self._proxy.headers,
149
+ proxy_ssl_context=self._proxy.ssl_context,
150
+ remote_origin=origin,
151
+ keepalive_expiry=self._keepalive_expiry,
152
+ network_backend=self._network_backend,
153
+ )
154
+ from .http_proxy import TunnelHTTPConnection
155
+
156
+ return TunnelHTTPConnection(
157
+ proxy_origin=self._proxy.url.origin,
158
+ proxy_headers=self._proxy.headers,
159
+ proxy_ssl_context=self._proxy.ssl_context,
160
+ remote_origin=origin,
161
+ ssl_context=self._ssl_context,
162
+ keepalive_expiry=self._keepalive_expiry,
163
+ http1=self._http1,
164
+ http2=self._http2,
165
+ network_backend=self._network_backend,
166
+ )
167
+
168
+ return HTTPConnection(
169
+ origin=origin,
170
+ ssl_context=self._ssl_context,
171
+ keepalive_expiry=self._keepalive_expiry,
172
+ http1=self._http1,
173
+ http2=self._http2,
174
+ retries=self._retries,
175
+ local_address=self._local_address,
176
+ uds=self._uds,
177
+ network_backend=self._network_backend,
178
+ socket_options=self._socket_options,
179
+ )
180
+
181
+ @property
182
+ def connections(self) -> list[ConnectionInterface]:
183
+ """
184
+ Return a list of the connections currently in the pool.
185
+
186
+ For example:
187
+
188
+ ```python
189
+ >>> pool.connections
190
+ [
191
+ <HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 6]>,
192
+ <HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 9]> ,
193
+ <HTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>,
194
+ ]
195
+ ```
196
+ """
197
+ return list(self._connections)
198
+
199
+ def handle_request(self, request: Request) -> Response:
200
+ """
201
+ Send an HTTP request, and return an HTTP response.
202
+
203
+ This is the core implementation that is called into by `.request()` or `.stream()`.
204
+ """
205
+ scheme = request.url.scheme.decode()
206
+ if scheme == "":
207
+ raise UnsupportedProtocol(
208
+ "Request URL is missing an 'http://' or 'https://' protocol."
209
+ )
210
+ if scheme not in ("http", "https", "ws", "wss"):
211
+ raise UnsupportedProtocol(
212
+ f"Request URL has an unsupported protocol '{scheme}://'."
213
+ )
214
+
215
+ timeouts = request.extensions.get("timeout", {})
216
+ timeout = timeouts.get("pool", None)
217
+
218
+ with self._optional_thread_lock:
219
+ # Add the incoming request to our request queue.
220
+ pool_request = PoolRequest(request)
221
+ self._requests.append(pool_request)
222
+
223
+ try:
224
+ while True:
225
+ with self._optional_thread_lock:
226
+ # Assign incoming requests to available connections,
227
+ # closing or creating new connections as required.
228
+ closing = self._assign_requests_to_connections()
229
+ self._close_connections(closing)
230
+
231
+ # Wait until this request has an assigned connection.
232
+ connection = pool_request.wait_for_connection(timeout=timeout)
233
+
234
+ try:
235
+ # Send the request on the assigned connection.
236
+ response = connection.handle_request(
237
+ pool_request.request
238
+ )
239
+ except ConnectionNotAvailable:
240
+ # In some cases a connection may initially be available to
241
+ # handle a request, but then become unavailable.
242
+ #
243
+ # In this case we clear the connection and try again.
244
+ pool_request.clear_connection()
245
+ else:
246
+ break # pragma: nocover
247
+
248
+ except BaseException as exc:
249
+ with self._optional_thread_lock:
250
+ # For any exception or cancellation we remove the request from
251
+ # the queue, and then re-assign requests to connections.
252
+ self._requests.remove(pool_request)
253
+ closing = self._assign_requests_to_connections()
254
+
255
+ self._close_connections(closing)
256
+ raise exc from None
257
+
258
+ # Return the response. Note that in this case we still have to manage
259
+ # the point at which the response is closed.
260
+ assert isinstance(response.stream, typing.Iterable)
261
+ return Response(
262
+ status=response.status,
263
+ headers=response.headers,
264
+ content=PoolByteStream(
265
+ stream=response.stream, pool_request=pool_request, pool=self
266
+ ),
267
+ extensions=response.extensions,
268
+ )
269
+
270
+ def _assign_requests_to_connections(self) -> list[ConnectionInterface]:
271
+ """
272
+ Manage the state of the connection pool, assigning incoming
273
+ requests to connections as available.
274
+
275
+ Called whenever a new request is added or removed from the pool.
276
+
277
+ Any closing connections are returned, allowing the I/O for closing
278
+ those connections to be handled seperately.
279
+ """
280
+ closing_connections = []
281
+
282
+ # First we handle cleaning up any connections that are closed,
283
+ # have expired their keep-alive, or surplus idle connections.
284
+ for connection in list(self._connections):
285
+ if connection.is_closed():
286
+ # log: "removing closed connection"
287
+ self._connections.remove(connection)
288
+ elif connection.has_expired():
289
+ # log: "closing expired connection"
290
+ self._connections.remove(connection)
291
+ closing_connections.append(connection)
292
+ elif (
293
+ connection.is_idle()
294
+ and len([connection.is_idle() for connection in self._connections])
295
+ > self._max_keepalive_connections
296
+ ):
297
+ # log: "closing idle connection"
298
+ self._connections.remove(connection)
299
+ closing_connections.append(connection)
300
+
301
+ # Assign queued requests to connections.
302
+ queued_requests = [request for request in self._requests if request.is_queued()]
303
+ for pool_request in queued_requests:
304
+ origin = pool_request.request.url.origin
305
+ available_connections = [
306
+ connection
307
+ for connection in self._connections
308
+ if connection.can_handle_request(origin) and connection.is_available()
309
+ ]
310
+ idle_connections = [
311
+ connection for connection in self._connections if connection.is_idle()
312
+ ]
313
+
314
+ # There are three cases for how we may be able to handle the request:
315
+ #
316
+ # 1. There is an existing connection that can handle the request.
317
+ # 2. We can create a new connection to handle the request.
318
+ # 3. We can close an idle connection and then create a new connection
319
+ # to handle the request.
320
+ if available_connections:
321
+ # log: "reusing existing connection"
322
+ connection = available_connections[0]
323
+ pool_request.assign_to_connection(connection)
324
+ elif len(self._connections) < self._max_connections:
325
+ # log: "creating new connection"
326
+ connection = self.create_connection(origin)
327
+ self._connections.append(connection)
328
+ pool_request.assign_to_connection(connection)
329
+ elif idle_connections:
330
+ # log: "closing idle connection"
331
+ connection = idle_connections[0]
332
+ self._connections.remove(connection)
333
+ closing_connections.append(connection)
334
+ # log: "creating new connection"
335
+ connection = self.create_connection(origin)
336
+ self._connections.append(connection)
337
+ pool_request.assign_to_connection(connection)
338
+
339
+ return closing_connections
340
+
341
+ def _close_connections(self, closing: list[ConnectionInterface]) -> None:
342
+ # Close connections which have been removed from the pool.
343
+ with ShieldCancellation():
344
+ for connection in closing:
345
+ connection.close()
346
+
347
+ def close(self) -> None:
348
+ # Explicitly close the connection pool.
349
+ # Clears all existing requests and connections.
350
+ with self._optional_thread_lock:
351
+ closing_connections = list(self._connections)
352
+ self._connections = []
353
+ self._close_connections(closing_connections)
354
+
355
+ def __enter__(self) -> ConnectionPool:
356
+ return self
357
+
358
+ def __exit__(
359
+ self,
360
+ exc_type: type[BaseException] | None = None,
361
+ exc_value: BaseException | None = None,
362
+ traceback: types.TracebackType | None = None,
363
+ ) -> None:
364
+ self.close()
365
+
366
+ def __repr__(self) -> str:
367
+ class_name = self.__class__.__name__
368
+ with self._optional_thread_lock:
369
+ request_is_queued = [request.is_queued() for request in self._requests]
370
+ connection_is_idle = [
371
+ connection.is_idle() for connection in self._connections
372
+ ]
373
+
374
+ num_active_requests = request_is_queued.count(False)
375
+ num_queued_requests = request_is_queued.count(True)
376
+ num_active_connections = connection_is_idle.count(False)
377
+ num_idle_connections = connection_is_idle.count(True)
378
+
379
+ requests_info = (
380
+ f"Requests: {num_active_requests} active, {num_queued_requests} queued"
381
+ )
382
+ connection_info = (
383
+ f"Connections: {num_active_connections} active, {num_idle_connections} idle"
384
+ )
385
+
386
+ return f"<{class_name} [{requests_info} | {connection_info}]>"
387
+
388
+
389
+ class PoolByteStream:
390
+ def __init__(
391
+ self,
392
+ stream: typing.Iterable[bytes],
393
+ pool_request: PoolRequest,
394
+ pool: ConnectionPool,
395
+ ) -> None:
396
+ self._stream = stream
397
+ self._pool_request = pool_request
398
+ self._pool = pool
399
+ self._closed = False
400
+
401
+ def __iter__(self) -> typing.Iterator[bytes]:
402
+ try:
403
+ for part in self._stream:
404
+ yield part
405
+ except BaseException as exc:
406
+ self.close()
407
+ raise exc from None
408
+
409
+ def close(self) -> None:
410
+ if not self._closed:
411
+ self._closed = True
412
+ with ShieldCancellation():
413
+ if hasattr(self._stream, "close"):
414
+ self._stream.close()
415
+
416
+ with self._pool._optional_thread_lock:
417
+ self._pool._requests.remove(self._pool_request)
418
+ closing = self._pool._assign_requests_to_connections()
419
+
420
+ self._pool._close_connections(closing)
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/http11.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import logging
5
+ import ssl
6
+ import time
7
+ import types
8
+ import typing
9
+
10
+ import h11
11
+
12
+ from .._backends.base import NetworkStream
13
+ from .._exceptions import (
14
+ ConnectionNotAvailable,
15
+ LocalProtocolError,
16
+ RemoteProtocolError,
17
+ WriteError,
18
+ map_exceptions,
19
+ )
20
+ from .._models import Origin, Request, Response
21
+ from .._synchronization import Lock, ShieldCancellation
22
+ from .._trace import Trace
23
+ from .interfaces import ConnectionInterface
24
+
25
+ logger = logging.getLogger("httpcore.http11")
26
+
27
+
28
+ # A subset of `h11.Event` types supported by `_send_event`
29
+ H11SendEvent = typing.Union[
30
+ h11.Request,
31
+ h11.Data,
32
+ h11.EndOfMessage,
33
+ ]
34
+
35
+
36
+ class HTTPConnectionState(enum.IntEnum):
37
+ NEW = 0
38
+ ACTIVE = 1
39
+ IDLE = 2
40
+ CLOSED = 3
41
+
42
+
43
+ class HTTP11Connection(ConnectionInterface):
44
+ READ_NUM_BYTES = 64 * 1024
45
+ MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024
46
+
47
+ def __init__(
48
+ self,
49
+ origin: Origin,
50
+ stream: NetworkStream,
51
+ keepalive_expiry: float | None = None,
52
+ ) -> None:
53
+ self._origin = origin
54
+ self._network_stream = stream
55
+ self._keepalive_expiry: float | None = keepalive_expiry
56
+ self._expire_at: float | None = None
57
+ self._state = HTTPConnectionState.NEW
58
+ self._state_lock = Lock()
59
+ self._request_count = 0
60
+ self._h11_state = h11.Connection(
61
+ our_role=h11.CLIENT,
62
+ max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE,
63
+ )
64
+
65
+ def handle_request(self, request: Request) -> Response:
66
+ if not self.can_handle_request(request.url.origin):
67
+ raise RuntimeError(
68
+ f"Attempted to send request to {request.url.origin} on connection "
69
+ f"to {self._origin}"
70
+ )
71
+
72
+ with self._state_lock:
73
+ if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE):
74
+ self._request_count += 1
75
+ self._state = HTTPConnectionState.ACTIVE
76
+ self._expire_at = None
77
+ else:
78
+ raise ConnectionNotAvailable()
79
+
80
+ try:
81
+ kwargs = {"request": request}
82
+ try:
83
+ with Trace(
84
+ "send_request_headers", logger, request, kwargs
85
+ ) as trace:
86
+ self._send_request_headers(**kwargs)
87
+ with Trace("send_request_body", logger, request, kwargs) as trace:
88
+ self._send_request_body(**kwargs)
89
+ except WriteError:
90
+ # If we get a write error while we're writing the request,
91
+ # then we supress this error and move on to attempting to
92
+ # read the response. Servers can sometimes close the request
93
+ # pre-emptively and then respond with a well formed HTTP
94
+ # error response.
95
+ pass
96
+
97
+ with Trace(
98
+ "receive_response_headers", logger, request, kwargs
99
+ ) as trace:
100
+ (
101
+ http_version,
102
+ status,
103
+ reason_phrase,
104
+ headers,
105
+ trailing_data,
106
+ ) = self._receive_response_headers(**kwargs)
107
+ trace.return_value = (
108
+ http_version,
109
+ status,
110
+ reason_phrase,
111
+ headers,
112
+ )
113
+
114
+ network_stream = self._network_stream
115
+
116
+ # CONNECT or Upgrade request
117
+ if (status == 101) or (
118
+ (request.method == b"CONNECT") and (200 <= status < 300)
119
+ ):
120
+ network_stream = HTTP11UpgradeStream(network_stream, trailing_data)
121
+
122
+ return Response(
123
+ status=status,
124
+ headers=headers,
125
+ content=HTTP11ConnectionByteStream(self, request),
126
+ extensions={
127
+ "http_version": http_version,
128
+ "reason_phrase": reason_phrase,
129
+ "network_stream": network_stream,
130
+ },
131
+ )
132
+ except BaseException as exc:
133
+ with ShieldCancellation():
134
+ with Trace("response_closed", logger, request) as trace:
135
+ self._response_closed()
136
+ raise exc
137
+
138
+ # Sending the request...
139
+
140
+ def _send_request_headers(self, request: Request) -> None:
141
+ timeouts = request.extensions.get("timeout", {})
142
+ timeout = timeouts.get("write", None)
143
+
144
+ with map_exceptions({h11.LocalProtocolError: LocalProtocolError}):
145
+ event = h11.Request(
146
+ method=request.method,
147
+ target=request.url.target,
148
+ headers=request.headers,
149
+ )
150
+ self._send_event(event, timeout=timeout)
151
+
152
+ def _send_request_body(self, request: Request) -> None:
153
+ timeouts = request.extensions.get("timeout", {})
154
+ timeout = timeouts.get("write", None)
155
+
156
+ assert isinstance(request.stream, typing.Iterable)
157
+ for chunk in request.stream:
158
+ event = h11.Data(data=chunk)
159
+ self._send_event(event, timeout=timeout)
160
+
161
+ self._send_event(h11.EndOfMessage(), timeout=timeout)
162
+
163
+ def _send_event(self, event: h11.Event, timeout: float | None = None) -> None:
164
+ bytes_to_send = self._h11_state.send(event)
165
+ if bytes_to_send is not None:
166
+ self._network_stream.write(bytes_to_send, timeout=timeout)
167
+
168
+ # Receiving the response...
169
+
170
+ def _receive_response_headers(
171
+ self, request: Request
172
+ ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]:
173
+ timeouts = request.extensions.get("timeout", {})
174
+ timeout = timeouts.get("read", None)
175
+
176
+ while True:
177
+ event = self._receive_event(timeout=timeout)
178
+ if isinstance(event, h11.Response):
179
+ break
180
+ if (
181
+ isinstance(event, h11.InformationalResponse)
182
+ and event.status_code == 101
183
+ ):
184
+ break
185
+
186
+ http_version = b"HTTP/" + event.http_version
187
+
188
+ # h11 version 0.11+ supports a `raw_items` interface to get the
189
+ # raw header casing, rather than the enforced lowercase headers.
190
+ headers = event.headers.raw_items()
191
+
192
+ trailing_data, _ = self._h11_state.trailing_data
193
+
194
+ return http_version, event.status_code, event.reason, headers, trailing_data
195
+
196
+ def _receive_response_body(
197
+ self, request: Request
198
+ ) -> typing.Iterator[bytes]:
199
+ timeouts = request.extensions.get("timeout", {})
200
+ timeout = timeouts.get("read", None)
201
+
202
+ while True:
203
+ event = self._receive_event(timeout=timeout)
204
+ if isinstance(event, h11.Data):
205
+ yield bytes(event.data)
206
+ elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)):
207
+ break
208
+
209
+ def _receive_event(
210
+ self, timeout: float | None = None
211
+ ) -> h11.Event | type[h11.PAUSED]:
212
+ while True:
213
+ with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}):
214
+ event = self._h11_state.next_event()
215
+
216
+ if event is h11.NEED_DATA:
217
+ data = self._network_stream.read(
218
+ self.READ_NUM_BYTES, timeout=timeout
219
+ )
220
+
221
+ # If we feed this case through h11 we'll raise an exception like:
222
+ #
223
+ # httpcore.RemoteProtocolError: can't handle event type
224
+ # ConnectionClosed when role=SERVER and state=SEND_RESPONSE
225
+ #
226
+ # Which is accurate, but not very informative from an end-user
227
+ # perspective. Instead we handle this case distinctly and treat
228
+ # it as a ConnectError.
229
+ if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE:
230
+ msg = "Server disconnected without sending a response."
231
+ raise RemoteProtocolError(msg)
232
+
233
+ self._h11_state.receive_data(data)
234
+ else:
235
+ # mypy fails to narrow the type in the above if statement above
236
+ return event # type: ignore[return-value]
237
+
238
+ def _response_closed(self) -> None:
239
+ with self._state_lock:
240
+ if (
241
+ self._h11_state.our_state is h11.DONE
242
+ and self._h11_state.their_state is h11.DONE
243
+ ):
244
+ self._state = HTTPConnectionState.IDLE
245
+ self._h11_state.start_next_cycle()
246
+ if self._keepalive_expiry is not None:
247
+ now = time.monotonic()
248
+ self._expire_at = now + self._keepalive_expiry
249
+ else:
250
+ self.close()
251
+
252
+ # Once the connection is no longer required...
253
+
254
+ def close(self) -> None:
255
+ # Note that this method unilaterally closes the connection, and does
256
+ # not have any kind of locking in place around it.
257
+ self._state = HTTPConnectionState.CLOSED
258
+ self._network_stream.close()
259
+
260
+ # The ConnectionInterface methods provide information about the state of
261
+ # the connection, allowing for a connection pooling implementation to
262
+ # determine when to reuse and when to close the connection...
263
+
264
+ def can_handle_request(self, origin: Origin) -> bool:
265
+ return origin == self._origin
266
+
267
+ def is_available(self) -> bool:
268
+ # Note that HTTP/1.1 connections in the "NEW" state are not treated as
269
+ # being "available". The control flow which created the connection will
270
+ # be able to send an outgoing request, but the connection will not be
271
+ # acquired from the connection pool for any other request.
272
+ return self._state == HTTPConnectionState.IDLE
273
+
274
+ def has_expired(self) -> bool:
275
+ now = time.monotonic()
276
+ keepalive_expired = self._expire_at is not None and now > self._expire_at
277
+
278
+ # If the HTTP connection is idle but the socket is readable, then the
279
+ # only valid state is that the socket is about to return b"", indicating
280
+ # a server-initiated disconnect.
281
+ server_disconnected = (
282
+ self._state == HTTPConnectionState.IDLE
283
+ and self._network_stream.get_extra_info("is_readable")
284
+ )
285
+
286
+ return keepalive_expired or server_disconnected
287
+
288
+ def is_idle(self) -> bool:
289
+ return self._state == HTTPConnectionState.IDLE
290
+
291
+ def is_closed(self) -> bool:
292
+ return self._state == HTTPConnectionState.CLOSED
293
+
294
+ def info(self) -> str:
295
+ origin = str(self._origin)
296
+ return (
297
+ f"{origin!r}, HTTP/1.1, {self._state.name}, "
298
+ f"Request Count: {self._request_count}"
299
+ )
300
+
301
+ def __repr__(self) -> str:
302
+ class_name = self.__class__.__name__
303
+ origin = str(self._origin)
304
+ return (
305
+ f"<{class_name} [{origin!r}, {self._state.name}, "
306
+ f"Request Count: {self._request_count}]>"
307
+ )
308
+
309
+ # These context managers are not used in the standard flow, but are
310
+ # useful for testing or working with connection instances directly.
311
+
312
+ def __enter__(self) -> HTTP11Connection:
313
+ return self
314
+
315
+ def __exit__(
316
+ self,
317
+ exc_type: type[BaseException] | None = None,
318
+ exc_value: BaseException | None = None,
319
+ traceback: types.TracebackType | None = None,
320
+ ) -> None:
321
+ self.close()
322
+
323
+
324
+ class HTTP11ConnectionByteStream:
325
+ def __init__(self, connection: HTTP11Connection, request: Request) -> None:
326
+ self._connection = connection
327
+ self._request = request
328
+ self._closed = False
329
+
330
+ def __iter__(self) -> typing.Iterator[bytes]:
331
+ kwargs = {"request": self._request}
332
+ try:
333
+ with Trace("receive_response_body", logger, self._request, kwargs):
334
+ for chunk in self._connection._receive_response_body(**kwargs):
335
+ yield chunk
336
+ except BaseException as exc:
337
+ # If we get an exception while streaming the response,
338
+ # we want to close the response (and possibly the connection)
339
+ # before raising that exception.
340
+ with ShieldCancellation():
341
+ self.close()
342
+ raise exc
343
+
344
+ def close(self) -> None:
345
+ if not self._closed:
346
+ self._closed = True
347
+ with Trace("response_closed", logger, self._request):
348
+ self._connection._response_closed()
349
+
350
+
351
+ class HTTP11UpgradeStream(NetworkStream):
352
+ def __init__(self, stream: NetworkStream, leading_data: bytes) -> None:
353
+ self._stream = stream
354
+ self._leading_data = leading_data
355
+
356
+ def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
357
+ if self._leading_data:
358
+ buffer = self._leading_data[:max_bytes]
359
+ self._leading_data = self._leading_data[max_bytes:]
360
+ return buffer
361
+ else:
362
+ return self._stream.read(max_bytes, timeout)
363
+
364
+ def write(self, buffer: bytes, timeout: float | None = None) -> None:
365
+ self._stream.write(buffer, timeout)
366
+
367
+ def close(self) -> None:
368
+ self._stream.close()
369
+
370
+ def start_tls(
371
+ self,
372
+ ssl_context: ssl.SSLContext,
373
+ server_hostname: str | None = None,
374
+ timeout: float | None = None,
375
+ ) -> NetworkStream:
376
+ return self._stream.start_tls(ssl_context, server_hostname, timeout)
377
+
378
+ def get_extra_info(self, info: str) -> typing.Any:
379
+ return self._stream.get_extra_info(info)
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/METADATA ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: packaging
3
+ Version: 26.0
4
+ Summary: Core utilities for Python packages
5
+ Author-email: Donald Stufft <donald@stufft.io>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/x-rst
8
+ License-Expression: Apache-2.0 OR BSD-2-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: Implementation :: CPython
22
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
23
+ Classifier: Typing :: Typed
24
+ License-File: LICENSE
25
+ License-File: LICENSE.APACHE
26
+ License-File: LICENSE.BSD
27
+ Project-URL: Documentation, https://packaging.pypa.io/
28
+ Project-URL: Source, https://github.com/pypa/packaging
29
+
30
+ packaging
31
+ =========
32
+
33
+ .. start-intro
34
+
35
+ Reusable core utilities for various Python Packaging
36
+ `interoperability specifications <https://packaging.python.org/specifications/>`_.
37
+
38
+ This library provides utilities that implement the interoperability
39
+ specifications which have clearly one correct behaviour (eg: :pep:`440`)
40
+ or benefit greatly from having a single shared implementation (eg: :pep:`425`).
41
+
42
+ .. end-intro
43
+
44
+ The ``packaging`` project includes the following: version handling, specifiers,
45
+ markers, requirements, tags, metadata, lockfiles, utilities.
46
+
47
+ Documentation
48
+ -------------
49
+
50
+ The `documentation`_ provides information and the API for the following:
51
+
52
+ - Version Handling
53
+ - Specifiers
54
+ - Markers
55
+ - Requirements
56
+ - Tags
57
+ - Metadata
58
+ - Lockfiles
59
+ - Utilities
60
+
61
+ Installation
62
+ ------------
63
+
64
+ Use ``pip`` to install these utilities::
65
+
66
+ pip install packaging
67
+
68
+ The ``packaging`` library uses calendar-based versioning (``YY.N``).
69
+
70
+ Discussion
71
+ ----------
72
+
73
+ If you run into bugs, you can file them in our `issue tracker`_.
74
+
75
+ You can also join ``#pypa`` on Freenode to ask questions or get involved.
76
+
77
+
78
+ .. _`documentation`: https://packaging.pypa.io/
79
+ .. _`issue tracker`: https://github.com/pypa/packaging/issues
80
+
81
+
82
+ Code of Conduct
83
+ ---------------
84
+
85
+ Everyone interacting in the packaging project's codebases, issue trackers, chat
86
+ rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
87
+
88
+ .. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
89
+
90
+ Contributing
91
+ ------------
92
+
93
+ The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as
94
+ well as how to report a potential security issue. The documentation for this
95
+ project also covers information about `project development`_ and `security`_.
96
+
97
+ .. _`project development`: https://packaging.pypa.io/en/latest/development/
98
+ .. _`security`: https://packaging.pypa.io/en/latest/security/
99
+
100
+ Project History
101
+ ---------------
102
+
103
+ Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for
104
+ recent changes and project history.
105
+
106
+ .. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/
107
+
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/RECORD ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494
2
+ packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
3
+ packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
4
+ packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
5
+ packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518
6
+ packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514
7
+ packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421
8
+ packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771
9
+ packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360
10
+ packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537
12
+ packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870
13
+ packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797
14
+ packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856
15
+ packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040
16
+ packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272
17
+ packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819
18
+ packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
19
+ packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
20
+ packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
21
+ packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
22
+ packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
23
+ packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309
24
+ packaging-26.0.dist-info/RECORD,,
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ This software is made available under the terms of *either* of the licenses
2
+ found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made
3
+ under the terms of *both* these licenses.
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.APACHE ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.BSD ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) Donald Stufft and individual contributors.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __title__ = "packaging"
6
+ __summary__ = "Core utilities for Python packages"
7
+ __uri__ = "https://github.com/pypa/packaging"
8
+
9
+ __version__ = "26.0"
10
+
11
+ __author__ = "Donald Stufft and individual contributors"
12
+ __email__ = "donald@stufft.io"
13
+
14
+ __license__ = "BSD-2-Clause or Apache-2.0"
15
+ __copyright__ = f"2014 {__author__}"
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_elffile.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ELF file parser.
3
+
4
+ This provides a class ``ELFFile`` that parses an ELF executable in a similar
5
+ interface to ``ZipFile``. Only the read interface is implemented.
6
+
7
+ ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import enum
13
+ import os
14
+ import struct
15
+ from typing import IO
16
+
17
+
18
+ class ELFInvalid(ValueError):
19
+ pass
20
+
21
+
22
+ class EIClass(enum.IntEnum):
23
+ C32 = 1
24
+ C64 = 2
25
+
26
+
27
+ class EIData(enum.IntEnum):
28
+ Lsb = 1
29
+ Msb = 2
30
+
31
+
32
+ class EMachine(enum.IntEnum):
33
+ I386 = 3
34
+ S390 = 22
35
+ Arm = 40
36
+ X8664 = 62
37
+ AArc64 = 183
38
+
39
+
40
+ class ELFFile:
41
+ """
42
+ Representation of an ELF executable.
43
+ """
44
+
45
+ def __init__(self, f: IO[bytes]) -> None:
46
+ self._f = f
47
+
48
+ try:
49
+ ident = self._read("16B")
50
+ except struct.error as e:
51
+ raise ELFInvalid("unable to parse identification") from e
52
+ magic = bytes(ident[:4])
53
+ if magic != b"\x7fELF":
54
+ raise ELFInvalid(f"invalid magic: {magic!r}")
55
+
56
+ self.capacity = ident[4] # Format for program header (bitness).
57
+ self.encoding = ident[5] # Data structure encoding (endianness).
58
+
59
+ try:
60
+ # e_fmt: Format for program header.
61
+ # p_fmt: Format for section header.
62
+ # p_idx: Indexes to find p_type, p_offset, and p_filesz.
63
+ e_fmt, self._p_fmt, self._p_idx = {
64
+ (1, 1): ("<HHIIIIIHHH", "<IIIIIIII", (0, 1, 4)), # 32-bit LSB.
65
+ (1, 2): (">HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB.
66
+ (2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB.
67
+ (2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB.
68
+ }[(self.capacity, self.encoding)]
69
+ except KeyError as e:
70
+ raise ELFInvalid(
71
+ f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})"
72
+ ) from e
73
+
74
+ try:
75
+ (
76
+ _,
77
+ self.machine, # Architecture type.
78
+ _,
79
+ _,
80
+ self._e_phoff, # Offset of program header.
81
+ _,
82
+ self.flags, # Processor-specific flags.
83
+ _,
84
+ self._e_phentsize, # Size of section.
85
+ self._e_phnum, # Number of sections.
86
+ ) = self._read(e_fmt)
87
+ except struct.error as e:
88
+ raise ELFInvalid("unable to parse machine and section information") from e
89
+
90
+ def _read(self, fmt: str) -> tuple[int, ...]:
91
+ return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
92
+
93
+ @property
94
+ def interpreter(self) -> str | None:
95
+ """
96
+ The path recorded in the ``PT_INTERP`` section header.
97
+ """
98
+ for index in range(self._e_phnum):
99
+ self._f.seek(self._e_phoff + self._e_phentsize * index)
100
+ try:
101
+ data = self._read(self._p_fmt)
102
+ except struct.error:
103
+ continue
104
+ if data[self._p_idx[0]] != 3: # Not PT_INTERP.
105
+ continue
106
+ self._f.seek(data[self._p_idx[1]])
107
+ return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
108
+ return None
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_manylinux.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import contextlib
5
+ import functools
6
+ import os
7
+ import re
8
+ import sys
9
+ import warnings
10
+ from typing import Generator, Iterator, NamedTuple, Sequence
11
+
12
+ from ._elffile import EIClass, EIData, ELFFile, EMachine
13
+
14
+ EF_ARM_ABIMASK = 0xFF000000
15
+ EF_ARM_ABI_VER5 = 0x05000000
16
+ EF_ARM_ABI_FLOAT_HARD = 0x00000400
17
+
18
+ _ALLOWED_ARCHS = {
19
+ "x86_64",
20
+ "aarch64",
21
+ "ppc64",
22
+ "ppc64le",
23
+ "s390x",
24
+ "loongarch64",
25
+ "riscv64",
26
+ }
27
+
28
+
29
+ # `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
30
+ # as the type for `path` until then.
31
+ @contextlib.contextmanager
32
+ def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]:
33
+ try:
34
+ with open(path, "rb") as f:
35
+ yield ELFFile(f)
36
+ except (OSError, TypeError, ValueError):
37
+ yield None
38
+
39
+
40
+ def _is_linux_armhf(executable: str) -> bool:
41
+ # hard-float ABI can be detected from the ELF header of the running
42
+ # process
43
+ # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
44
+ with _parse_elf(executable) as f:
45
+ return (
46
+ f is not None
47
+ and f.capacity == EIClass.C32
48
+ and f.encoding == EIData.Lsb
49
+ and f.machine == EMachine.Arm
50
+ and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
51
+ and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
52
+ )
53
+
54
+
55
+ def _is_linux_i686(executable: str) -> bool:
56
+ with _parse_elf(executable) as f:
57
+ return (
58
+ f is not None
59
+ and f.capacity == EIClass.C32
60
+ and f.encoding == EIData.Lsb
61
+ and f.machine == EMachine.I386
62
+ )
63
+
64
+
65
+ def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
66
+ if "armv7l" in archs:
67
+ return _is_linux_armhf(executable)
68
+ if "i686" in archs:
69
+ return _is_linux_i686(executable)
70
+ return any(arch in _ALLOWED_ARCHS for arch in archs)
71
+
72
+
73
+ # If glibc ever changes its major version, we need to know what the last
74
+ # minor version was, so we can build the complete list of all versions.
75
+ # For now, guess what the highest minor version might be, assume it will
76
+ # be 50 for testing. Once this actually happens, update the dictionary
77
+ # with the actual value.
78
+ _LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
79
+
80
+
81
+ class _GLibCVersion(NamedTuple):
82
+ major: int
83
+ minor: int
84
+
85
+
86
+ def _glibc_version_string_confstr() -> str | None:
87
+ """
88
+ Primary implementation of glibc_version_string using os.confstr.
89
+ """
90
+ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
91
+ # to be broken or missing. This strategy is used in the standard library
92
+ # platform module.
93
+ # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
94
+ try:
95
+ # Should be a string like "glibc 2.17".
96
+ version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION")
97
+ assert version_string is not None
98
+ _, version = version_string.rsplit()
99
+ except (AssertionError, AttributeError, OSError, ValueError):
100
+ # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
101
+ return None
102
+ return version
103
+
104
+
105
+ def _glibc_version_string_ctypes() -> str | None:
106
+ """
107
+ Fallback implementation of glibc_version_string using ctypes.
108
+ """
109
+ try:
110
+ import ctypes # noqa: PLC0415
111
+ except ImportError:
112
+ return None
113
+
114
+ # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
115
+ # manpage says, "If filename is NULL, then the returned handle is for the
116
+ # main program". This way we can let the linker do the work to figure out
117
+ # which libc our process is actually using.
118
+ #
119
+ # We must also handle the special case where the executable is not a
120
+ # dynamically linked executable. This can occur when using musl libc,
121
+ # for example. In this situation, dlopen() will error, leading to an
122
+ # OSError. Interestingly, at least in the case of musl, there is no
123
+ # errno set on the OSError. The single string argument used to construct
124
+ # OSError comes from libc itself and is therefore not portable to
125
+ # hard code here. In any case, failure to call dlopen() means we
126
+ # can proceed, so we bail on our attempt.
127
+ try:
128
+ process_namespace = ctypes.CDLL(None)
129
+ except OSError:
130
+ return None
131
+
132
+ try:
133
+ gnu_get_libc_version = process_namespace.gnu_get_libc_version
134
+ except AttributeError:
135
+ # Symbol doesn't exist -> therefore, we are not linked to
136
+ # glibc.
137
+ return None
138
+
139
+ # Call gnu_get_libc_version, which returns a string like "2.5"
140
+ gnu_get_libc_version.restype = ctypes.c_char_p
141
+ version_str: str = gnu_get_libc_version()
142
+ # py2 / py3 compatibility:
143
+ if not isinstance(version_str, str):
144
+ version_str = version_str.decode("ascii")
145
+
146
+ return version_str
147
+
148
+
149
+ def _glibc_version_string() -> str | None:
150
+ """Returns glibc version string, or None if not using glibc."""
151
+ return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
152
+
153
+
154
+ def _parse_glibc_version(version_str: str) -> _GLibCVersion:
155
+ """Parse glibc version.
156
+
157
+ We use a regexp instead of str.split because we want to discard any
158
+ random junk that might come after the minor version -- this might happen
159
+ in patched/forked versions of glibc (e.g. Linaro's version of glibc
160
+ uses version strings like "2.20-2014.11"). See gh-3588.
161
+ """
162
+ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
163
+ if not m:
164
+ warnings.warn(
165
+ f"Expected glibc version with 2 components major.minor, got: {version_str}",
166
+ RuntimeWarning,
167
+ stacklevel=2,
168
+ )
169
+ return _GLibCVersion(-1, -1)
170
+ return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
171
+
172
+
173
+ @functools.lru_cache
174
+ def _get_glibc_version() -> _GLibCVersion:
175
+ version_str = _glibc_version_string()
176
+ if version_str is None:
177
+ return _GLibCVersion(-1, -1)
178
+ return _parse_glibc_version(version_str)
179
+
180
+
181
+ # From PEP 513, PEP 600
182
+ def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
183
+ sys_glibc = _get_glibc_version()
184
+ if sys_glibc < version:
185
+ return False
186
+ # Check for presence of _manylinux module.
187
+ try:
188
+ import _manylinux # noqa: PLC0415
189
+ except ImportError:
190
+ return True
191
+ if hasattr(_manylinux, "manylinux_compatible"):
192
+ result = _manylinux.manylinux_compatible(version[0], version[1], arch)
193
+ if result is not None:
194
+ return bool(result)
195
+ return True
196
+ if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"):
197
+ return bool(_manylinux.manylinux1_compatible)
198
+ if version == _GLibCVersion(2, 12) and hasattr(
199
+ _manylinux, "manylinux2010_compatible"
200
+ ):
201
+ return bool(_manylinux.manylinux2010_compatible)
202
+ if version == _GLibCVersion(2, 17) and hasattr(
203
+ _manylinux, "manylinux2014_compatible"
204
+ ):
205
+ return bool(_manylinux.manylinux2014_compatible)
206
+ return True
207
+
208
+
209
+ _LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = {
210
+ # CentOS 7 w/ glibc 2.17 (PEP 599)
211
+ _GLibCVersion(2, 17): "manylinux2014",
212
+ # CentOS 6 w/ glibc 2.12 (PEP 571)
213
+ _GLibCVersion(2, 12): "manylinux2010",
214
+ # CentOS 5 w/ glibc 2.5 (PEP 513)
215
+ _GLibCVersion(2, 5): "manylinux1",
216
+ }
217
+
218
+
219
+ def platform_tags(archs: Sequence[str]) -> Iterator[str]:
220
+ """Generate manylinux tags compatible to the current platform.
221
+
222
+ :param archs: Sequence of compatible architectures.
223
+ The first one shall be the closest to the actual architecture and be the part of
224
+ platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
225
+ The ``linux_`` prefix is assumed as a prerequisite for the current platform to
226
+ be manylinux-compatible.
227
+
228
+ :returns: An iterator of compatible manylinux tags.
229
+ """
230
+ if not _have_compatible_abi(sys.executable, archs):
231
+ return
232
+ # Oldest glibc to be supported regardless of architecture is (2, 17).
233
+ too_old_glibc2 = _GLibCVersion(2, 16)
234
+ if set(archs) & {"x86_64", "i686"}:
235
+ # On x86/i686 also oldest glibc to be supported is (2, 5).
236
+ too_old_glibc2 = _GLibCVersion(2, 4)
237
+ current_glibc = _GLibCVersion(*_get_glibc_version())
238
+ glibc_max_list = [current_glibc]
239
+ # We can assume compatibility across glibc major versions.
240
+ # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
241
+ #
242
+ # Build a list of maximum glibc versions so that we can
243
+ # output the canonical list of all glibc from current_glibc
244
+ # down to too_old_glibc2, including all intermediary versions.
245
+ for glibc_major in range(current_glibc.major - 1, 1, -1):
246
+ glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
247
+ glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
248
+ for arch in archs:
249
+ for glibc_max in glibc_max_list:
250
+ if glibc_max.major == too_old_glibc2.major:
251
+ min_minor = too_old_glibc2.minor
252
+ else:
253
+ # For other glibc major versions oldest supported is (x, 0).
254
+ min_minor = -1
255
+ for glibc_minor in range(glibc_max.minor, min_minor, -1):
256
+ glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
257
+ if _is_compatible(arch, glibc_version):
258
+ yield "manylinux_{}_{}_{}".format(*glibc_version, arch)
259
+
260
+ # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
261
+ if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version):
262
+ yield f"{legacy_tag}_{arch}"
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_musllinux.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PEP 656 support.
2
+
3
+ This module implements logic to detect if the currently running Python is
4
+ linked against musl, and what musl version is used.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ from typing import Iterator, NamedTuple, Sequence
14
+
15
+ from ._elffile import ELFFile
16
+
17
+
18
+ class _MuslVersion(NamedTuple):
19
+ major: int
20
+ minor: int
21
+
22
+
23
+ def _parse_musl_version(output: str) -> _MuslVersion | None:
24
+ lines = [n for n in (n.strip() for n in output.splitlines()) if n]
25
+ if len(lines) < 2 or lines[0][:4] != "musl":
26
+ return None
27
+ m = re.match(r"Version (\d+)\.(\d+)", lines[1])
28
+ if not m:
29
+ return None
30
+ return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
31
+
32
+
33
+ @functools.lru_cache
34
+ def _get_musl_version(executable: str) -> _MuslVersion | None:
35
+ """Detect currently-running musl runtime version.
36
+
37
+ This is done by checking the specified executable's dynamic linking
38
+ information, and invoking the loader to parse its output for a version
39
+ string. If the loader is musl, the output would be something like::
40
+
41
+ musl libc (x86_64)
42
+ Version 1.2.2
43
+ Dynamic Program Loader
44
+ """
45
+ try:
46
+ with open(executable, "rb") as f:
47
+ ld = ELFFile(f).interpreter
48
+ except (OSError, TypeError, ValueError):
49
+ return None
50
+ if ld is None or "musl" not in ld:
51
+ return None
52
+ proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True)
53
+ return _parse_musl_version(proc.stderr)
54
+
55
+
56
+ def platform_tags(archs: Sequence[str]) -> Iterator[str]:
57
+ """Generate musllinux tags compatible to the current platform.
58
+
59
+ :param archs: Sequence of compatible architectures.
60
+ The first one shall be the closest to the actual architecture and be the part of
61
+ platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
62
+ The ``linux_`` prefix is assumed as a prerequisite for the current platform to
63
+ be musllinux-compatible.
64
+
65
+ :returns: An iterator of compatible musllinux tags.
66
+ """
67
+ sys_musl = _get_musl_version(sys.executable)
68
+ if sys_musl is None: # Python not dynamically linked against musl.
69
+ return
70
+ for arch in archs:
71
+ for minor in range(sys_musl.minor, -1, -1):
72
+ yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
73
+
74
+
75
+ if __name__ == "__main__": # pragma: no cover
76
+ import sysconfig
77
+
78
+ plat = sysconfig.get_platform()
79
+ assert plat.startswith("linux-"), "not linux"
80
+
81
+ print("plat:", plat)
82
+ print("musl:", _get_musl_version(sys.executable))
83
+ print("tags:", end=" ")
84
+ for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):
85
+ print(t, end="\n ")
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_parser.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handwritten parser of dependency specifiers.
2
+
3
+ The docstring for each __parse_* function contains EBNF-inspired grammar representing
4
+ the implementation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ from typing import List, Literal, NamedTuple, Sequence, Tuple, Union
11
+
12
+ from ._tokenizer import DEFAULT_RULES, Tokenizer
13
+
14
+
15
+ class Node:
16
+ __slots__ = ("value",)
17
+
18
+ def __init__(self, value: str) -> None:
19
+ self.value = value
20
+
21
+ def __str__(self) -> str:
22
+ return self.value
23
+
24
+ def __repr__(self) -> str:
25
+ return f"<{self.__class__.__name__}({self.value!r})>"
26
+
27
+ def serialize(self) -> str:
28
+ raise NotImplementedError
29
+
30
+
31
+ class Variable(Node):
32
+ __slots__ = ()
33
+
34
+ def serialize(self) -> str:
35
+ return str(self)
36
+
37
+
38
+ class Value(Node):
39
+ __slots__ = ()
40
+
41
+ def serialize(self) -> str:
42
+ return f'"{self}"'
43
+
44
+
45
+ class Op(Node):
46
+ __slots__ = ()
47
+
48
+ def serialize(self) -> str:
49
+ return str(self)
50
+
51
+
52
+ MarkerLogical = Literal["and", "or"]
53
+ MarkerVar = Union[Variable, Value]
54
+ MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
55
+ MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
56
+ MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
57
+
58
+
59
+ class ParsedRequirement(NamedTuple):
60
+ name: str
61
+ url: str
62
+ extras: list[str]
63
+ specifier: str
64
+ marker: MarkerList | None
65
+
66
+
67
+ # --------------------------------------------------------------------------------------
68
+ # Recursive descent parser for dependency specifier
69
+ # --------------------------------------------------------------------------------------
70
+ def parse_requirement(source: str) -> ParsedRequirement:
71
+ return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
72
+
73
+
74
+ def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
75
+ """
76
+ requirement = WS? IDENTIFIER WS? extras WS? requirement_details
77
+ """
78
+ tokenizer.consume("WS")
79
+
80
+ name_token = tokenizer.expect(
81
+ "IDENTIFIER", expected="package name at the start of dependency specifier"
82
+ )
83
+ name = name_token.text
84
+ tokenizer.consume("WS")
85
+
86
+ extras = _parse_extras(tokenizer)
87
+ tokenizer.consume("WS")
88
+
89
+ url, specifier, marker = _parse_requirement_details(tokenizer)
90
+ tokenizer.expect("END", expected="end of dependency specifier")
91
+
92
+ return ParsedRequirement(name, url, extras, specifier, marker)
93
+
94
+
95
+ def _parse_requirement_details(
96
+ tokenizer: Tokenizer,
97
+ ) -> tuple[str, str, MarkerList | None]:
98
+ """
99
+ requirement_details = AT URL (WS requirement_marker?)?
100
+ | specifier WS? (requirement_marker)?
101
+ """
102
+
103
+ specifier = ""
104
+ url = ""
105
+ marker = None
106
+
107
+ if tokenizer.check("AT"):
108
+ tokenizer.read()
109
+ tokenizer.consume("WS")
110
+
111
+ url_start = tokenizer.position
112
+ url = tokenizer.expect("URL", expected="URL after @").text
113
+ if tokenizer.check("END", peek=True):
114
+ return (url, specifier, marker)
115
+
116
+ tokenizer.expect("WS", expected="whitespace after URL")
117
+
118
+ # The input might end after whitespace.
119
+ if tokenizer.check("END", peek=True):
120
+ return (url, specifier, marker)
121
+
122
+ marker = _parse_requirement_marker(
123
+ tokenizer,
124
+ span_start=url_start,
125
+ expected="semicolon (after URL and whitespace)",
126
+ )
127
+ else:
128
+ specifier_start = tokenizer.position
129
+ specifier = _parse_specifier(tokenizer)
130
+ tokenizer.consume("WS")
131
+
132
+ if tokenizer.check("END", peek=True):
133
+ return (url, specifier, marker)
134
+
135
+ marker = _parse_requirement_marker(
136
+ tokenizer,
137
+ span_start=specifier_start,
138
+ expected=(
139
+ "comma (within version specifier), semicolon (after version specifier)"
140
+ if specifier
141
+ else "semicolon (after name with no version specifier)"
142
+ ),
143
+ )
144
+
145
+ return (url, specifier, marker)
146
+
147
+
148
+ def _parse_requirement_marker(
149
+ tokenizer: Tokenizer, *, span_start: int, expected: str
150
+ ) -> MarkerList:
151
+ """
152
+ requirement_marker = SEMICOLON marker WS?
153
+ """
154
+
155
+ if not tokenizer.check("SEMICOLON"):
156
+ tokenizer.raise_syntax_error(
157
+ f"Expected {expected} or end",
158
+ span_start=span_start,
159
+ span_end=None,
160
+ )
161
+ tokenizer.read()
162
+
163
+ marker = _parse_marker(tokenizer)
164
+ tokenizer.consume("WS")
165
+
166
+ return marker
167
+
168
+
169
+ def _parse_extras(tokenizer: Tokenizer) -> list[str]:
170
+ """
171
+ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
172
+ """
173
+ if not tokenizer.check("LEFT_BRACKET", peek=True):
174
+ return []
175
+
176
+ with tokenizer.enclosing_tokens(
177
+ "LEFT_BRACKET",
178
+ "RIGHT_BRACKET",
179
+ around="extras",
180
+ ):
181
+ tokenizer.consume("WS")
182
+ extras = _parse_extras_list(tokenizer)
183
+ tokenizer.consume("WS")
184
+
185
+ return extras
186
+
187
+
188
+ def _parse_extras_list(tokenizer: Tokenizer) -> list[str]:
189
+ """
190
+ extras_list = identifier (wsp* ',' wsp* identifier)*
191
+ """
192
+ extras: list[str] = []
193
+
194
+ if not tokenizer.check("IDENTIFIER"):
195
+ return extras
196
+
197
+ extras.append(tokenizer.read().text)
198
+
199
+ while True:
200
+ tokenizer.consume("WS")
201
+ if tokenizer.check("IDENTIFIER", peek=True):
202
+ tokenizer.raise_syntax_error("Expected comma between extra names")
203
+ elif not tokenizer.check("COMMA"):
204
+ break
205
+
206
+ tokenizer.read()
207
+ tokenizer.consume("WS")
208
+
209
+ extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
210
+ extras.append(extra_token.text)
211
+
212
+ return extras
213
+
214
+
215
+ def _parse_specifier(tokenizer: Tokenizer) -> str:
216
+ """
217
+ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
218
+ | WS? version_many WS?
219
+ """
220
+ with tokenizer.enclosing_tokens(
221
+ "LEFT_PARENTHESIS",
222
+ "RIGHT_PARENTHESIS",
223
+ around="version specifier",
224
+ ):
225
+ tokenizer.consume("WS")
226
+ parsed_specifiers = _parse_version_many(tokenizer)
227
+ tokenizer.consume("WS")
228
+
229
+ return parsed_specifiers
230
+
231
+
232
+ def _parse_version_many(tokenizer: Tokenizer) -> str:
233
+ """
234
+ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
235
+ """
236
+ parsed_specifiers = ""
237
+ while tokenizer.check("SPECIFIER"):
238
+ span_start = tokenizer.position
239
+ parsed_specifiers += tokenizer.read().text
240
+ if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
241
+ tokenizer.raise_syntax_error(
242
+ ".* suffix can only be used with `==` or `!=` operators",
243
+ span_start=span_start,
244
+ span_end=tokenizer.position + 1,
245
+ )
246
+ if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
247
+ tokenizer.raise_syntax_error(
248
+ "Local version label can only be used with `==` or `!=` operators",
249
+ span_start=span_start,
250
+ span_end=tokenizer.position,
251
+ )
252
+ tokenizer.consume("WS")
253
+ if not tokenizer.check("COMMA"):
254
+ break
255
+ parsed_specifiers += tokenizer.read().text
256
+ tokenizer.consume("WS")
257
+
258
+ return parsed_specifiers
259
+
260
+
261
+ # --------------------------------------------------------------------------------------
262
+ # Recursive descent parser for marker expression
263
+ # --------------------------------------------------------------------------------------
264
+ def parse_marker(source: str) -> MarkerList:
265
+ return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
266
+
267
+
268
+ def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
269
+ retval = _parse_marker(tokenizer)
270
+ tokenizer.expect("END", expected="end of marker expression")
271
+ return retval
272
+
273
+
274
+ def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
275
+ """
276
+ marker = marker_atom (BOOLOP marker_atom)+
277
+ """
278
+ expression = [_parse_marker_atom(tokenizer)]
279
+ while tokenizer.check("BOOLOP"):
280
+ token = tokenizer.read()
281
+ expr_right = _parse_marker_atom(tokenizer)
282
+ expression.extend((token.text, expr_right))
283
+ return expression
284
+
285
+
286
+ def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
287
+ """
288
+ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
289
+ | WS? marker_item WS?
290
+ """
291
+
292
+ tokenizer.consume("WS")
293
+ if tokenizer.check("LEFT_PARENTHESIS", peek=True):
294
+ with tokenizer.enclosing_tokens(
295
+ "LEFT_PARENTHESIS",
296
+ "RIGHT_PARENTHESIS",
297
+ around="marker expression",
298
+ ):
299
+ tokenizer.consume("WS")
300
+ marker: MarkerAtom = _parse_marker(tokenizer)
301
+ tokenizer.consume("WS")
302
+ else:
303
+ marker = _parse_marker_item(tokenizer)
304
+ tokenizer.consume("WS")
305
+ return marker
306
+
307
+
308
+ def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
309
+ """
310
+ marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
311
+ """
312
+ tokenizer.consume("WS")
313
+ marker_var_left = _parse_marker_var(tokenizer)
314
+ tokenizer.consume("WS")
315
+ marker_op = _parse_marker_op(tokenizer)
316
+ tokenizer.consume("WS")
317
+ marker_var_right = _parse_marker_var(tokenizer)
318
+ tokenizer.consume("WS")
319
+ return (marker_var_left, marker_op, marker_var_right)
320
+
321
+
322
+ def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503
323
+ """
324
+ marker_var = VARIABLE | QUOTED_STRING
325
+ """
326
+ if tokenizer.check("VARIABLE"):
327
+ return process_env_var(tokenizer.read().text.replace(".", "_"))
328
+ elif tokenizer.check("QUOTED_STRING"):
329
+ return process_python_str(tokenizer.read().text)
330
+ else:
331
+ tokenizer.raise_syntax_error(
332
+ message="Expected a marker variable or quoted string"
333
+ )
334
+
335
+
336
+ def process_env_var(env_var: str) -> Variable:
337
+ if env_var in ("platform_python_implementation", "python_implementation"):
338
+ return Variable("platform_python_implementation")
339
+ else:
340
+ return Variable(env_var)
341
+
342
+
343
+ def process_python_str(python_str: str) -> Value:
344
+ value = ast.literal_eval(python_str)
345
+ return Value(str(value))
346
+
347
+
348
+ def _parse_marker_op(tokenizer: Tokenizer) -> Op:
349
+ """
350
+ marker_op = IN | NOT IN | OP
351
+ """
352
+ if tokenizer.check("IN"):
353
+ tokenizer.read()
354
+ return Op("in")
355
+ elif tokenizer.check("NOT"):
356
+ tokenizer.read()
357
+ tokenizer.expect("WS", expected="whitespace after 'not'")
358
+ tokenizer.expect("IN", expected="'in' after 'not'")
359
+ return Op("not in")
360
+ elif tokenizer.check("OP"):
361
+ return Op(tokenizer.read().text)
362
+ else:
363
+ return tokenizer.raise_syntax_error(
364
+ "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in"
365
+ )
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_structures.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+
8
+ @typing.final
9
+ class InfinityType:
10
+ __slots__ = ()
11
+
12
+ def __repr__(self) -> str:
13
+ return "Infinity"
14
+
15
+ def __hash__(self) -> int:
16
+ return hash(repr(self))
17
+
18
+ def __lt__(self, other: object) -> bool:
19
+ return False
20
+
21
+ def __le__(self, other: object) -> bool:
22
+ return False
23
+
24
+ def __eq__(self, other: object) -> bool:
25
+ return isinstance(other, self.__class__)
26
+
27
+ def __gt__(self, other: object) -> bool:
28
+ return True
29
+
30
+ def __ge__(self, other: object) -> bool:
31
+ return True
32
+
33
+ def __neg__(self: object) -> "NegativeInfinityType":
34
+ return NegativeInfinity
35
+
36
+
37
+ Infinity = InfinityType()
38
+
39
+
40
+ @typing.final
41
+ class NegativeInfinityType:
42
+ __slots__ = ()
43
+
44
+ def __repr__(self) -> str:
45
+ return "-Infinity"
46
+
47
+ def __hash__(self) -> int:
48
+ return hash(repr(self))
49
+
50
+ def __lt__(self, other: object) -> bool:
51
+ return True
52
+
53
+ def __le__(self, other: object) -> bool:
54
+ return True
55
+
56
+ def __eq__(self, other: object) -> bool:
57
+ return isinstance(other, self.__class__)
58
+
59
+ def __gt__(self, other: object) -> bool:
60
+ return False
61
+
62
+ def __ge__(self, other: object) -> bool:
63
+ return False
64
+
65
+ def __neg__(self: object) -> InfinityType:
66
+ return Infinity
67
+
68
+
69
+ NegativeInfinity = NegativeInfinityType()
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_tokenizer.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import re
5
+ from dataclasses import dataclass
6
+ from typing import Generator, Mapping, NoReturn
7
+
8
+ from .specifiers import Specifier
9
+
10
+
11
+ @dataclass
12
+ class Token:
13
+ name: str
14
+ text: str
15
+ position: int
16
+
17
+
18
+ class ParserSyntaxError(Exception):
19
+ """The provided source text could not be parsed correctly."""
20
+
21
+ def __init__(
22
+ self,
23
+ message: str,
24
+ *,
25
+ source: str,
26
+ span: tuple[int, int],
27
+ ) -> None:
28
+ self.span = span
29
+ self.message = message
30
+ self.source = source
31
+
32
+ super().__init__()
33
+
34
+ def __str__(self) -> str:
35
+ marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
36
+ return f"{self.message}\n {self.source}\n {marker}"
37
+
38
+
39
+ DEFAULT_RULES: dict[str, re.Pattern[str]] = {
40
+ "LEFT_PARENTHESIS": re.compile(r"\("),
41
+ "RIGHT_PARENTHESIS": re.compile(r"\)"),
42
+ "LEFT_BRACKET": re.compile(r"\["),
43
+ "RIGHT_BRACKET": re.compile(r"\]"),
44
+ "SEMICOLON": re.compile(r";"),
45
+ "COMMA": re.compile(r","),
46
+ "QUOTED_STRING": re.compile(
47
+ r"""
48
+ (
49
+ ('[^']*')
50
+ |
51
+ ("[^"]*")
52
+ )
53
+ """,
54
+ re.VERBOSE,
55
+ ),
56
+ "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"),
57
+ "BOOLOP": re.compile(r"\b(or|and)\b"),
58
+ "IN": re.compile(r"\bin\b"),
59
+ "NOT": re.compile(r"\bnot\b"),
60
+ "VARIABLE": re.compile(
61
+ r"""
62
+ \b(
63
+ python_version
64
+ |python_full_version
65
+ |os[._]name
66
+ |sys[._]platform
67
+ |platform_(release|system)
68
+ |platform[._](version|machine|python_implementation)
69
+ |python_implementation
70
+ |implementation_(name|version)
71
+ |extras?
72
+ |dependency_groups
73
+ )\b
74
+ """,
75
+ re.VERBOSE,
76
+ ),
77
+ "SPECIFIER": re.compile(
78
+ Specifier._operator_regex_str + Specifier._version_regex_str,
79
+ re.VERBOSE | re.IGNORECASE,
80
+ ),
81
+ "AT": re.compile(r"\@"),
82
+ "URL": re.compile(r"[^ \t]+"),
83
+ "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"),
84
+ "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"),
85
+ "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"),
86
+ "WS": re.compile(r"[ \t]+"),
87
+ "END": re.compile(r"$"),
88
+ }
89
+
90
+
91
+ class Tokenizer:
92
+ """Context-sensitive token parsing.
93
+
94
+ Provides methods to examine the input stream to check whether the next token
95
+ matches.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ source: str,
101
+ *,
102
+ rules: Mapping[str, re.Pattern[str]],
103
+ ) -> None:
104
+ self.source = source
105
+ self.rules = rules
106
+ self.next_token: Token | None = None
107
+ self.position = 0
108
+
109
+ def consume(self, name: str) -> None:
110
+ """Move beyond provided token name, if at current position."""
111
+ if self.check(name):
112
+ self.read()
113
+
114
+ def check(self, name: str, *, peek: bool = False) -> bool:
115
+ """Check whether the next token has the provided name.
116
+
117
+ By default, if the check succeeds, the token *must* be read before
118
+ another check. If `peek` is set to `True`, the token is not loaded and
119
+ would need to be checked again.
120
+ """
121
+ assert self.next_token is None, (
122
+ f"Cannot check for {name!r}, already have {self.next_token!r}"
123
+ )
124
+ assert name in self.rules, f"Unknown token name: {name!r}"
125
+
126
+ expression = self.rules[name]
127
+
128
+ match = expression.match(self.source, self.position)
129
+ if match is None:
130
+ return False
131
+ if not peek:
132
+ self.next_token = Token(name, match[0], self.position)
133
+ return True
134
+
135
+ def expect(self, name: str, *, expected: str) -> Token:
136
+ """Expect a certain token name next, failing with a syntax error otherwise.
137
+
138
+ The token is *not* read.
139
+ """
140
+ if not self.check(name):
141
+ raise self.raise_syntax_error(f"Expected {expected}")
142
+ return self.read()
143
+
144
+ def read(self) -> Token:
145
+ """Consume the next token and return it."""
146
+ token = self.next_token
147
+ assert token is not None
148
+
149
+ self.position += len(token.text)
150
+ self.next_token = None
151
+
152
+ return token
153
+
154
+ def raise_syntax_error(
155
+ self,
156
+ message: str,
157
+ *,
158
+ span_start: int | None = None,
159
+ span_end: int | None = None,
160
+ ) -> NoReturn:
161
+ """Raise ParserSyntaxError at the given position."""
162
+ span = (
163
+ self.position if span_start is None else span_start,
164
+ self.position if span_end is None else span_end,
165
+ )
166
+ raise ParserSyntaxError(
167
+ message,
168
+ source=self.source,
169
+ span=span,
170
+ )
171
+
172
+ @contextlib.contextmanager
173
+ def enclosing_tokens(
174
+ self, open_token: str, close_token: str, *, around: str
175
+ ) -> Generator[None, None, None]:
176
+ if self.check(open_token):
177
+ open_position = self.position
178
+ self.read()
179
+ else:
180
+ open_position = None
181
+
182
+ yield
183
+
184
+ if open_position is None:
185
+ return
186
+
187
+ if not self.check(close_token):
188
+ self.raise_syntax_error(
189
+ f"Expected matching {close_token} for {open_token}, after {around}",
190
+ span_start=open_position,
191
+ )
192
+
193
+ self.read()
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/__init__.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #######################################################################################
2
+ #
3
+ # Adapted from:
4
+ # https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py
5
+ #
6
+ # MIT License
7
+ #
8
+ # Copyright (c) 2017-present Ofek Lev <oss@ofek.dev>
9
+ #
10
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this
11
+ # software and associated documentation files (the "Software"), to deal in the Software
12
+ # without restriction, including without limitation the rights to use, copy, modify,
13
+ # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
14
+ # permit persons to whom the Software is furnished to do so, subject to the following
15
+ # conditions:
16
+ #
17
+ # The above copyright notice and this permission notice shall be included in all copies
18
+ # or substantial portions of the Software.
19
+ #
20
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
21
+ # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
22
+ # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
23
+ # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
24
+ # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
25
+ # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
+ #
27
+ #
28
+ # With additional allowance of arbitrary `LicenseRef-` identifiers, not just
29
+ # `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`.
30
+ #
31
+ #######################################################################################
32
+ from __future__ import annotations
33
+
34
+ import re
35
+ from typing import NewType, cast
36
+
37
+ from ._spdx import EXCEPTIONS, LICENSES
38
+
39
+ __all__ = [
40
+ "InvalidLicenseExpression",
41
+ "NormalizedLicenseExpression",
42
+ "canonicalize_license_expression",
43
+ ]
44
+
45
+ license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$")
46
+
47
+ NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str)
48
+
49
+
50
+ class InvalidLicenseExpression(ValueError):
51
+ """Raised when a license-expression string is invalid
52
+
53
+ >>> canonicalize_license_expression("invalid")
54
+ Traceback (most recent call last):
55
+ ...
56
+ packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid'
57
+ """
58
+
59
+
60
+ def canonicalize_license_expression(
61
+ raw_license_expression: str,
62
+ ) -> NormalizedLicenseExpression:
63
+ if not raw_license_expression:
64
+ message = f"Invalid license expression: {raw_license_expression!r}"
65
+ raise InvalidLicenseExpression(message)
66
+
67
+ # Pad any parentheses so tokenization can be achieved by merely splitting on
68
+ # whitespace.
69
+ license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ")
70
+ licenseref_prefix = "LicenseRef-"
71
+ license_refs = {
72
+ ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :]
73
+ for ref in license_expression.split()
74
+ if ref.lower().startswith(licenseref_prefix.lower())
75
+ }
76
+
77
+ # Normalize to lower case so we can look up licenses/exceptions
78
+ # and so boolean operators are Python-compatible.
79
+ license_expression = license_expression.lower()
80
+
81
+ tokens = license_expression.split()
82
+
83
+ # Rather than implementing a parenthesis/boolean logic parser, create an
84
+ # expression that Python can parse. Everything that is not involved with the
85
+ # grammar itself is replaced with the placeholder `False` and the resultant
86
+ # expression should become a valid Python expression.
87
+ python_tokens = []
88
+ for token in tokens:
89
+ if token not in {"or", "and", "with", "(", ")"}:
90
+ python_tokens.append("False")
91
+ elif token == "with":
92
+ python_tokens.append("or")
93
+ elif (
94
+ token == "("
95
+ and python_tokens
96
+ and python_tokens[-1] not in {"or", "and", "("}
97
+ ) or (token == ")" and python_tokens and python_tokens[-1] == "("):
98
+ message = f"Invalid license expression: {raw_license_expression!r}"
99
+ raise InvalidLicenseExpression(message)
100
+ else:
101
+ python_tokens.append(token)
102
+
103
+ python_expression = " ".join(python_tokens)
104
+ try:
105
+ compile(python_expression, "", "eval")
106
+ except SyntaxError:
107
+ message = f"Invalid license expression: {raw_license_expression!r}"
108
+ raise InvalidLicenseExpression(message) from None
109
+
110
+ # Take a final pass to check for unknown licenses/exceptions.
111
+ normalized_tokens = []
112
+ for token in tokens:
113
+ if token in {"or", "and", "with", "(", ")"}:
114
+ normalized_tokens.append(token.upper())
115
+ continue
116
+
117
+ if normalized_tokens and normalized_tokens[-1] == "WITH":
118
+ if token not in EXCEPTIONS:
119
+ message = f"Unknown license exception: {token!r}"
120
+ raise InvalidLicenseExpression(message)
121
+
122
+ normalized_tokens.append(EXCEPTIONS[token]["id"])
123
+ else:
124
+ if token.endswith("+"):
125
+ final_token = token[:-1]
126
+ suffix = "+"
127
+ else:
128
+ final_token = token
129
+ suffix = ""
130
+
131
+ if final_token.startswith("licenseref-"):
132
+ if not license_ref_allowed.match(final_token):
133
+ message = f"Invalid licenseref: {final_token!r}"
134
+ raise InvalidLicenseExpression(message)
135
+ normalized_tokens.append(license_refs[final_token] + suffix)
136
+ else:
137
+ if final_token not in LICENSES:
138
+ message = f"Unknown license: {final_token!r}"
139
+ raise InvalidLicenseExpression(message)
140
+ normalized_tokens.append(LICENSES[final_token]["id"] + suffix)
141
+
142
+ normalized_expression = " ".join(normalized_tokens)
143
+
144
+ return cast(
145
+ "NormalizedLicenseExpression",
146
+ normalized_expression.replace("( ", "(").replace(" )", ")"),
147
+ )
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/_spdx.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from __future__ import annotations
3
+
4
+ from typing import TypedDict
5
+
6
+ class SPDXLicense(TypedDict):
7
+ id: str
8
+ deprecated: bool
9
+
10
+ class SPDXException(TypedDict):
11
+ id: str
12
+ deprecated: bool
13
+
14
+
15
+ VERSION = '3.27.0'
16
+
17
+ LICENSES: dict[str, SPDXLicense] = {
18
+ '0bsd': {'id': '0BSD', 'deprecated': False},
19
+ '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False},
20
+ 'aal': {'id': 'AAL', 'deprecated': False},
21
+ 'abstyles': {'id': 'Abstyles', 'deprecated': False},
22
+ 'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False},
23
+ 'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False},
24
+ 'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False},
25
+ 'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False},
26
+ 'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False},
27
+ 'adsl': {'id': 'ADSL', 'deprecated': False},
28
+ 'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False},
29
+ 'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False},
30
+ 'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False},
31
+ 'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False},
32
+ 'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False},
33
+ 'afmparse': {'id': 'Afmparse', 'deprecated': False},
34
+ 'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True},
35
+ 'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False},
36
+ 'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False},
37
+ 'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True},
38
+ 'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False},
39
+ 'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False},
40
+ 'aladdin': {'id': 'Aladdin', 'deprecated': False},
41
+ 'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False},
42
+ 'amdplpa': {'id': 'AMDPLPA', 'deprecated': False},
43
+ 'aml': {'id': 'AML', 'deprecated': False},
44
+ 'aml-glslang': {'id': 'AML-glslang', 'deprecated': False},
45
+ 'ampas': {'id': 'AMPAS', 'deprecated': False},
46
+ 'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False},
47
+ 'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False},
48
+ 'any-osi': {'id': 'any-OSI', 'deprecated': False},
49
+ 'any-osi-perl-modules': {'id': 'any-OSI-perl-modules', 'deprecated': False},
50
+ 'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False},
51
+ 'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False},
52
+ 'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False},
53
+ 'apafml': {'id': 'APAFML', 'deprecated': False},
54
+ 'apl-1.0': {'id': 'APL-1.0', 'deprecated': False},
55
+ 'app-s2p': {'id': 'App-s2p', 'deprecated': False},
56
+ 'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False},
57
+ 'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False},
58
+ 'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False},
59
+ 'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False},
60
+ 'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False},
61
+ 'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False},
62
+ 'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False},
63
+ 'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False},
64
+ 'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False},
65
+ 'artistic-dist': {'id': 'Artistic-dist', 'deprecated': False},
66
+ 'aspell-ru': {'id': 'Aspell-RU', 'deprecated': False},
67
+ 'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False},
68
+ 'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False},
69
+ 'baekmuk': {'id': 'Baekmuk', 'deprecated': False},
70
+ 'bahyph': {'id': 'Bahyph', 'deprecated': False},
71
+ 'barr': {'id': 'Barr', 'deprecated': False},
72
+ 'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False},
73
+ 'beerware': {'id': 'Beerware', 'deprecated': False},
74
+ 'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False},
75
+ 'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False},
76
+ 'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False},
77
+ 'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False},
78
+ 'blessing': {'id': 'blessing', 'deprecated': False},
79
+ 'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False},
80
+ 'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False},
81
+ 'boehm-gc-without-fee': {'id': 'Boehm-GC-without-fee', 'deprecated': False},
82
+ 'borceux': {'id': 'Borceux', 'deprecated': False},
83
+ 'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False},
84
+ 'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False},
85
+ 'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False},
86
+ 'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False},
87
+ 'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False},
88
+ 'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False},
89
+ 'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True},
90
+ 'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True},
91
+ 'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False},
92
+ 'bsd-2-clause-pkgconf-disclaimer': {'id': 'BSD-2-Clause-pkgconf-disclaimer', 'deprecated': False},
93
+ 'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False},
94
+ 'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False},
95
+ 'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False},
96
+ 'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False},
97
+ 'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False},
98
+ 'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False},
99
+ 'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False},
100
+ 'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False},
101
+ 'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False},
102
+ 'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False},
103
+ 'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False},
104
+ 'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False},
105
+ 'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False},
106
+ 'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False},
107
+ 'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False},
108
+ 'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False},
109
+ 'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False},
110
+ 'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False},
111
+ 'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False},
112
+ 'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False},
113
+ 'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False},
114
+ 'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False},
115
+ 'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False},
116
+ 'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False},
117
+ 'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False},
118
+ 'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False},
119
+ 'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False},
120
+ 'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False},
121
+ 'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False},
122
+ 'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False},
123
+ 'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True},
124
+ 'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False},
125
+ 'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False},
126
+ 'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False},
127
+ 'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False},
128
+ 'caldera': {'id': 'Caldera', 'deprecated': False},
129
+ 'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False},
130
+ 'catharon': {'id': 'Catharon', 'deprecated': False},
131
+ 'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False},
132
+ 'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False},
133
+ 'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False},
134
+ 'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False},
135
+ 'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False},
136
+ 'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False},
137
+ 'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False},
138
+ 'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False},
139
+ 'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False},
140
+ 'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False},
141
+ 'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False},
142
+ 'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False},
143
+ 'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False},
144
+ 'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False},
145
+ 'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False},
146
+ 'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False},
147
+ 'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False},
148
+ 'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False},
149
+ 'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False},
150
+ 'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False},
151
+ 'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False},
152
+ 'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False},
153
+ 'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False},
154
+ 'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False},
155
+ 'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False},
156
+ 'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False},
157
+ 'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False},
158
+ 'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False},
159
+ 'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False},
160
+ 'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False},
161
+ 'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False},
162
+ 'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False},
163
+ 'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False},
164
+ 'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False},
165
+ 'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False},
166
+ 'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False},
167
+ 'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False},
168
+ 'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False},
169
+ 'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False},
170
+ 'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False},
171
+ 'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False},
172
+ 'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False},
173
+ 'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False},
174
+ 'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False},
175
+ 'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False},
176
+ 'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False},
177
+ 'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False},
178
+ 'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False},
179
+ 'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False},
180
+ 'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False},
181
+ 'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False},
182
+ 'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False},
183
+ 'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False},
184
+ 'cc-pdm-1.0': {'id': 'CC-PDM-1.0', 'deprecated': False},
185
+ 'cc-sa-1.0': {'id': 'CC-SA-1.0', 'deprecated': False},
186
+ 'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False},
187
+ 'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False},
188
+ 'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False},
189
+ 'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False},
190
+ 'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False},
191
+ 'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False},
192
+ 'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False},
193
+ 'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False},
194
+ 'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False},
195
+ 'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False},
196
+ 'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False},
197
+ 'cecill-b': {'id': 'CECILL-B', 'deprecated': False},
198
+ 'cecill-c': {'id': 'CECILL-C', 'deprecated': False},
199
+ 'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False},
200
+ 'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False},
201
+ 'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False},
202
+ 'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False},
203
+ 'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False},
204
+ 'cfitsio': {'id': 'CFITSIO', 'deprecated': False},
205
+ 'check-cvs': {'id': 'check-cvs', 'deprecated': False},
206
+ 'checkmk': {'id': 'checkmk', 'deprecated': False},
207
+ 'clartistic': {'id': 'ClArtistic', 'deprecated': False},
208
+ 'clips': {'id': 'Clips', 'deprecated': False},
209
+ 'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False},
210
+ 'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False},
211
+ 'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False},
212
+ 'cnri-python': {'id': 'CNRI-Python', 'deprecated': False},
213
+ 'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False},
214
+ 'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False},
215
+ 'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False},
216
+ 'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False},
217
+ 'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False},
218
+ 'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False},
219
+ 'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False},
220
+ 'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False},
221
+ 'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False},
222
+ 'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False},
223
+ 'cronyx': {'id': 'Cronyx', 'deprecated': False},
224
+ 'crossword': {'id': 'Crossword', 'deprecated': False},
225
+ 'cryptoswift': {'id': 'CryptoSwift', 'deprecated': False},
226
+ 'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False},
227
+ 'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False},
228
+ 'cube': {'id': 'Cube', 'deprecated': False},
229
+ 'curl': {'id': 'curl', 'deprecated': False},
230
+ 'cve-tou': {'id': 'cve-tou', 'deprecated': False},
231
+ 'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False},
232
+ 'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False},
233
+ 'diffmark': {'id': 'diffmark', 'deprecated': False},
234
+ 'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False},
235
+ 'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False},
236
+ 'doc': {'id': 'DOC', 'deprecated': False},
237
+ 'docbook-dtd': {'id': 'DocBook-DTD', 'deprecated': False},
238
+ 'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False},
239
+ 'docbook-stylesheet': {'id': 'DocBook-Stylesheet', 'deprecated': False},
240
+ 'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False},
241
+ 'dotseqn': {'id': 'Dotseqn', 'deprecated': False},
242
+ 'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False},
243
+ 'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False},
244
+ 'dsdp': {'id': 'DSDP', 'deprecated': False},
245
+ 'dtoa': {'id': 'dtoa', 'deprecated': False},
246
+ 'dvipdfm': {'id': 'dvipdfm', 'deprecated': False},
247
+ 'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False},
248
+ 'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False},
249
+ 'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True},
250
+ 'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False},
251
+ 'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False},
252
+ 'egenix': {'id': 'eGenix', 'deprecated': False},
253
+ 'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False},
254
+ 'entessa': {'id': 'Entessa', 'deprecated': False},
255
+ 'epics': {'id': 'EPICS', 'deprecated': False},
256
+ 'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False},
257
+ 'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False},
258
+ 'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False},
259
+ 'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False},
260
+ 'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False},
261
+ 'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False},
262
+ 'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False},
263
+ 'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False},
264
+ 'eurosym': {'id': 'Eurosym', 'deprecated': False},
265
+ 'fair': {'id': 'Fair', 'deprecated': False},
266
+ 'fbm': {'id': 'FBM', 'deprecated': False},
267
+ 'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False},
268
+ 'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False},
269
+ 'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False},
270
+ 'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False},
271
+ 'freeimage': {'id': 'FreeImage', 'deprecated': False},
272
+ 'fsfap': {'id': 'FSFAP', 'deprecated': False},
273
+ 'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False},
274
+ 'fsful': {'id': 'FSFUL', 'deprecated': False},
275
+ 'fsfullr': {'id': 'FSFULLR', 'deprecated': False},
276
+ 'fsfullrsd': {'id': 'FSFULLRSD', 'deprecated': False},
277
+ 'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False},
278
+ 'fsl-1.1-alv2': {'id': 'FSL-1.1-ALv2', 'deprecated': False},
279
+ 'fsl-1.1-mit': {'id': 'FSL-1.1-MIT', 'deprecated': False},
280
+ 'ftl': {'id': 'FTL', 'deprecated': False},
281
+ 'furuseth': {'id': 'Furuseth', 'deprecated': False},
282
+ 'fwlw': {'id': 'fwlw', 'deprecated': False},
283
+ 'game-programming-gems': {'id': 'Game-Programming-Gems', 'deprecated': False},
284
+ 'gcr-docs': {'id': 'GCR-docs', 'deprecated': False},
285
+ 'gd': {'id': 'GD', 'deprecated': False},
286
+ 'generic-xts': {'id': 'generic-xts', 'deprecated': False},
287
+ 'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True},
288
+ 'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False},
289
+ 'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False},
290
+ 'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False},
291
+ 'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False},
292
+ 'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False},
293
+ 'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False},
294
+ 'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True},
295
+ 'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False},
296
+ 'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False},
297
+ 'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False},
298
+ 'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False},
299
+ 'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False},
300
+ 'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False},
301
+ 'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True},
302
+ 'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False},
303
+ 'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False},
304
+ 'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False},
305
+ 'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False},
306
+ 'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False},
307
+ 'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False},
308
+ 'giftware': {'id': 'Giftware', 'deprecated': False},
309
+ 'gl2ps': {'id': 'GL2PS', 'deprecated': False},
310
+ 'glide': {'id': 'Glide', 'deprecated': False},
311
+ 'glulxe': {'id': 'Glulxe', 'deprecated': False},
312
+ 'glwtpl': {'id': 'GLWTPL', 'deprecated': False},
313
+ 'gnuplot': {'id': 'gnuplot', 'deprecated': False},
314
+ 'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True},
315
+ 'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True},
316
+ 'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False},
317
+ 'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False},
318
+ 'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True},
319
+ 'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True},
320
+ 'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False},
321
+ 'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False},
322
+ 'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True},
323
+ 'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True},
324
+ 'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True},
325
+ 'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True},
326
+ 'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True},
327
+ 'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True},
328
+ 'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True},
329
+ 'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False},
330
+ 'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False},
331
+ 'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True},
332
+ 'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True},
333
+ 'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False},
334
+ 'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False},
335
+ 'gtkbook': {'id': 'gtkbook', 'deprecated': False},
336
+ 'gutmann': {'id': 'Gutmann', 'deprecated': False},
337
+ 'haskellreport': {'id': 'HaskellReport', 'deprecated': False},
338
+ 'hdf5': {'id': 'HDF5', 'deprecated': False},
339
+ 'hdparm': {'id': 'hdparm', 'deprecated': False},
340
+ 'hidapi': {'id': 'HIDAPI', 'deprecated': False},
341
+ 'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False},
342
+ 'hp-1986': {'id': 'HP-1986', 'deprecated': False},
343
+ 'hp-1989': {'id': 'HP-1989', 'deprecated': False},
344
+ 'hpnd': {'id': 'HPND', 'deprecated': False},
345
+ 'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False},
346
+ 'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False},
347
+ 'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False},
348
+ 'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False},
349
+ 'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False},
350
+ 'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False},
351
+ 'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False},
352
+ 'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False},
353
+ 'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False},
354
+ 'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False},
355
+ 'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False},
356
+ 'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False},
357
+ 'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False},
358
+ 'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False},
359
+ 'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False},
360
+ 'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False},
361
+ 'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False},
362
+ 'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False},
363
+ 'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False},
364
+ 'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False},
365
+ 'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False},
366
+ 'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False},
367
+ 'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False},
368
+ 'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False},
369
+ 'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False},
370
+ 'icu': {'id': 'ICU', 'deprecated': False},
371
+ 'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False},
372
+ 'ijg': {'id': 'IJG', 'deprecated': False},
373
+ 'ijg-short': {'id': 'IJG-short', 'deprecated': False},
374
+ 'imagemagick': {'id': 'ImageMagick', 'deprecated': False},
375
+ 'imatix': {'id': 'iMatix', 'deprecated': False},
376
+ 'imlib2': {'id': 'Imlib2', 'deprecated': False},
377
+ 'info-zip': {'id': 'Info-ZIP', 'deprecated': False},
378
+ 'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False},
379
+ 'innosetup': {'id': 'InnoSetup', 'deprecated': False},
380
+ 'intel': {'id': 'Intel', 'deprecated': False},
381
+ 'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False},
382
+ 'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False},
383
+ 'ipa': {'id': 'IPA', 'deprecated': False},
384
+ 'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False},
385
+ 'isc': {'id': 'ISC', 'deprecated': False},
386
+ 'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False},
387
+ 'jam': {'id': 'Jam', 'deprecated': False},
388
+ 'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False},
389
+ 'jove': {'id': 'jove', 'deprecated': False},
390
+ 'jpl-image': {'id': 'JPL-image', 'deprecated': False},
391
+ 'jpnic': {'id': 'JPNIC', 'deprecated': False},
392
+ 'json': {'id': 'JSON', 'deprecated': False},
393
+ 'kastrup': {'id': 'Kastrup', 'deprecated': False},
394
+ 'kazlib': {'id': 'Kazlib', 'deprecated': False},
395
+ 'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False},
396
+ 'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False},
397
+ 'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False},
398
+ 'latex2e': {'id': 'Latex2e', 'deprecated': False},
399
+ 'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False},
400
+ 'leptonica': {'id': 'Leptonica', 'deprecated': False},
401
+ 'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True},
402
+ 'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True},
403
+ 'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False},
404
+ 'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False},
405
+ 'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True},
406
+ 'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True},
407
+ 'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False},
408
+ 'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False},
409
+ 'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True},
410
+ 'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True},
411
+ 'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False},
412
+ 'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False},
413
+ 'lgpllr': {'id': 'LGPLLR', 'deprecated': False},
414
+ 'libpng': {'id': 'Libpng', 'deprecated': False},
415
+ 'libpng-1.6.35': {'id': 'libpng-1.6.35', 'deprecated': False},
416
+ 'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False},
417
+ 'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False},
418
+ 'libtiff': {'id': 'libtiff', 'deprecated': False},
419
+ 'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False},
420
+ 'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False},
421
+ 'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False},
422
+ 'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False},
423
+ 'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False},
424
+ 'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False},
425
+ 'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False},
426
+ 'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False},
427
+ 'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False},
428
+ 'loop': {'id': 'LOOP', 'deprecated': False},
429
+ 'lpd-document': {'id': 'LPD-document', 'deprecated': False},
430
+ 'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False},
431
+ 'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False},
432
+ 'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False},
433
+ 'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False},
434
+ 'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False},
435
+ 'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False},
436
+ 'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False},
437
+ 'lsof': {'id': 'lsof', 'deprecated': False},
438
+ 'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False},
439
+ 'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False},
440
+ 'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False},
441
+ 'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False},
442
+ 'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False},
443
+ 'magaz': {'id': 'magaz', 'deprecated': False},
444
+ 'mailprio': {'id': 'mailprio', 'deprecated': False},
445
+ 'makeindex': {'id': 'MakeIndex', 'deprecated': False},
446
+ 'man2html': {'id': 'man2html', 'deprecated': False},
447
+ 'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False},
448
+ 'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False},
449
+ 'metamail': {'id': 'metamail', 'deprecated': False},
450
+ 'minpack': {'id': 'Minpack', 'deprecated': False},
451
+ 'mips': {'id': 'MIPS', 'deprecated': False},
452
+ 'miros': {'id': 'MirOS', 'deprecated': False},
453
+ 'mit': {'id': 'MIT', 'deprecated': False},
454
+ 'mit-0': {'id': 'MIT-0', 'deprecated': False},
455
+ 'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False},
456
+ 'mit-click': {'id': 'MIT-Click', 'deprecated': False},
457
+ 'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False},
458
+ 'mit-enna': {'id': 'MIT-enna', 'deprecated': False},
459
+ 'mit-feh': {'id': 'MIT-feh', 'deprecated': False},
460
+ 'mit-festival': {'id': 'MIT-Festival', 'deprecated': False},
461
+ 'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False},
462
+ 'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False},
463
+ 'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False},
464
+ 'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False},
465
+ 'mit-wu': {'id': 'MIT-Wu', 'deprecated': False},
466
+ 'mitnfa': {'id': 'MITNFA', 'deprecated': False},
467
+ 'mmixware': {'id': 'MMIXware', 'deprecated': False},
468
+ 'motosoto': {'id': 'Motosoto', 'deprecated': False},
469
+ 'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False},
470
+ 'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False},
471
+ 'mpich2': {'id': 'mpich2', 'deprecated': False},
472
+ 'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False},
473
+ 'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False},
474
+ 'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False},
475
+ 'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False},
476
+ 'mplus': {'id': 'mplus', 'deprecated': False},
477
+ 'ms-lpl': {'id': 'MS-LPL', 'deprecated': False},
478
+ 'ms-pl': {'id': 'MS-PL', 'deprecated': False},
479
+ 'ms-rl': {'id': 'MS-RL', 'deprecated': False},
480
+ 'mtll': {'id': 'MTLL', 'deprecated': False},
481
+ 'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False},
482
+ 'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False},
483
+ 'multics': {'id': 'Multics', 'deprecated': False},
484
+ 'mup': {'id': 'Mup', 'deprecated': False},
485
+ 'naist-2003': {'id': 'NAIST-2003', 'deprecated': False},
486
+ 'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False},
487
+ 'naumen': {'id': 'Naumen', 'deprecated': False},
488
+ 'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False},
489
+ 'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False},
490
+ 'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False},
491
+ 'ncl': {'id': 'NCL', 'deprecated': False},
492
+ 'ncsa': {'id': 'NCSA', 'deprecated': False},
493
+ 'net-snmp': {'id': 'Net-SNMP', 'deprecated': True},
494
+ 'netcdf': {'id': 'NetCDF', 'deprecated': False},
495
+ 'newsletr': {'id': 'Newsletr', 'deprecated': False},
496
+ 'ngpl': {'id': 'NGPL', 'deprecated': False},
497
+ 'ngrep': {'id': 'ngrep', 'deprecated': False},
498
+ 'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False},
499
+ 'nist-pd': {'id': 'NIST-PD', 'deprecated': False},
500
+ 'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False},
501
+ 'nist-software': {'id': 'NIST-Software', 'deprecated': False},
502
+ 'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False},
503
+ 'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False},
504
+ 'nlpl': {'id': 'NLPL', 'deprecated': False},
505
+ 'nokia': {'id': 'Nokia', 'deprecated': False},
506
+ 'nosl': {'id': 'NOSL', 'deprecated': False},
507
+ 'noweb': {'id': 'Noweb', 'deprecated': False},
508
+ 'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False},
509
+ 'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False},
510
+ 'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False},
511
+ 'nrl': {'id': 'NRL', 'deprecated': False},
512
+ 'ntia-pd': {'id': 'NTIA-PD', 'deprecated': False},
513
+ 'ntp': {'id': 'NTP', 'deprecated': False},
514
+ 'ntp-0': {'id': 'NTP-0', 'deprecated': False},
515
+ 'nunit': {'id': 'Nunit', 'deprecated': True},
516
+ 'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False},
517
+ 'oar': {'id': 'OAR', 'deprecated': False},
518
+ 'occt-pl': {'id': 'OCCT-PL', 'deprecated': False},
519
+ 'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False},
520
+ 'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False},
521
+ 'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False},
522
+ 'offis': {'id': 'OFFIS', 'deprecated': False},
523
+ 'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False},
524
+ 'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False},
525
+ 'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False},
526
+ 'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False},
527
+ 'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False},
528
+ 'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False},
529
+ 'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False},
530
+ 'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False},
531
+ 'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False},
532
+ 'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False},
533
+ 'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False},
534
+ 'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False},
535
+ 'ogtsl': {'id': 'OGTSL', 'deprecated': False},
536
+ 'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False},
537
+ 'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False},
538
+ 'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False},
539
+ 'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False},
540
+ 'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False},
541
+ 'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False},
542
+ 'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False},
543
+ 'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False},
544
+ 'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False},
545
+ 'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False},
546
+ 'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False},
547
+ 'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False},
548
+ 'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False},
549
+ 'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False},
550
+ 'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False},
551
+ 'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False},
552
+ 'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False},
553
+ 'oml': {'id': 'OML', 'deprecated': False},
554
+ 'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False},
555
+ 'openssl': {'id': 'OpenSSL', 'deprecated': False},
556
+ 'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False},
557
+ 'openvision': {'id': 'OpenVision', 'deprecated': False},
558
+ 'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False},
559
+ 'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False},
560
+ 'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False},
561
+ 'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False},
562
+ 'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False},
563
+ 'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False},
564
+ 'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False},
565
+ 'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False},
566
+ 'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False},
567
+ 'padl': {'id': 'PADL', 'deprecated': False},
568
+ 'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False},
569
+ 'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False},
570
+ 'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False},
571
+ 'php-3.0': {'id': 'PHP-3.0', 'deprecated': False},
572
+ 'php-3.01': {'id': 'PHP-3.01', 'deprecated': False},
573
+ 'pixar': {'id': 'Pixar', 'deprecated': False},
574
+ 'pkgconf': {'id': 'pkgconf', 'deprecated': False},
575
+ 'plexus': {'id': 'Plexus', 'deprecated': False},
576
+ 'pnmstitch': {'id': 'pnmstitch', 'deprecated': False},
577
+ 'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False},
578
+ 'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False},
579
+ 'postgresql': {'id': 'PostgreSQL', 'deprecated': False},
580
+ 'ppl': {'id': 'PPL', 'deprecated': False},
581
+ 'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False},
582
+ 'psfrag': {'id': 'psfrag', 'deprecated': False},
583
+ 'psutils': {'id': 'psutils', 'deprecated': False},
584
+ 'python-2.0': {'id': 'Python-2.0', 'deprecated': False},
585
+ 'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False},
586
+ 'python-ldap': {'id': 'python-ldap', 'deprecated': False},
587
+ 'qhull': {'id': 'Qhull', 'deprecated': False},
588
+ 'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False},
589
+ 'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False},
590
+ 'radvd': {'id': 'radvd', 'deprecated': False},
591
+ 'rdisc': {'id': 'Rdisc', 'deprecated': False},
592
+ 'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False},
593
+ 'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False},
594
+ 'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False},
595
+ 'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False},
596
+ 'rsa-md': {'id': 'RSA-MD', 'deprecated': False},
597
+ 'rscpl': {'id': 'RSCPL', 'deprecated': False},
598
+ 'ruby': {'id': 'Ruby', 'deprecated': False},
599
+ 'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False},
600
+ 'sax-pd': {'id': 'SAX-PD', 'deprecated': False},
601
+ 'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False},
602
+ 'saxpath': {'id': 'Saxpath', 'deprecated': False},
603
+ 'scea': {'id': 'SCEA', 'deprecated': False},
604
+ 'schemereport': {'id': 'SchemeReport', 'deprecated': False},
605
+ 'sendmail': {'id': 'Sendmail', 'deprecated': False},
606
+ 'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False},
607
+ 'sendmail-open-source-1.1': {'id': 'Sendmail-Open-Source-1.1', 'deprecated': False},
608
+ 'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False},
609
+ 'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False},
610
+ 'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False},
611
+ 'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False},
612
+ 'sgp4': {'id': 'SGP4', 'deprecated': False},
613
+ 'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False},
614
+ 'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False},
615
+ 'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False},
616
+ 'sissl': {'id': 'SISSL', 'deprecated': False},
617
+ 'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False},
618
+ 'sl': {'id': 'SL', 'deprecated': False},
619
+ 'sleepycat': {'id': 'Sleepycat', 'deprecated': False},
620
+ 'smail-gpl': {'id': 'SMAIL-GPL', 'deprecated': False},
621
+ 'smlnj': {'id': 'SMLNJ', 'deprecated': False},
622
+ 'smppl': {'id': 'SMPPL', 'deprecated': False},
623
+ 'snia': {'id': 'SNIA', 'deprecated': False},
624
+ 'snprintf': {'id': 'snprintf', 'deprecated': False},
625
+ 'sofa': {'id': 'SOFA', 'deprecated': False},
626
+ 'softsurfer': {'id': 'softSurfer', 'deprecated': False},
627
+ 'soundex': {'id': 'Soundex', 'deprecated': False},
628
+ 'spencer-86': {'id': 'Spencer-86', 'deprecated': False},
629
+ 'spencer-94': {'id': 'Spencer-94', 'deprecated': False},
630
+ 'spencer-99': {'id': 'Spencer-99', 'deprecated': False},
631
+ 'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False},
632
+ 'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False},
633
+ 'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False},
634
+ 'ssh-short': {'id': 'SSH-short', 'deprecated': False},
635
+ 'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False},
636
+ 'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False},
637
+ 'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True},
638
+ 'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False},
639
+ 'sul-1.0': {'id': 'SUL-1.0', 'deprecated': False},
640
+ 'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False},
641
+ 'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False},
642
+ 'sunpro': {'id': 'SunPro', 'deprecated': False},
643
+ 'swl': {'id': 'SWL', 'deprecated': False},
644
+ 'swrule': {'id': 'swrule', 'deprecated': False},
645
+ 'symlinks': {'id': 'Symlinks', 'deprecated': False},
646
+ 'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False},
647
+ 'tcl': {'id': 'TCL', 'deprecated': False},
648
+ 'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False},
649
+ 'termreadkey': {'id': 'TermReadKey', 'deprecated': False},
650
+ 'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False},
651
+ 'thirdeye': {'id': 'ThirdEye', 'deprecated': False},
652
+ 'threeparttable': {'id': 'threeparttable', 'deprecated': False},
653
+ 'tmate': {'id': 'TMate', 'deprecated': False},
654
+ 'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False},
655
+ 'tosl': {'id': 'TOSL', 'deprecated': False},
656
+ 'tpdl': {'id': 'TPDL', 'deprecated': False},
657
+ 'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False},
658
+ 'trustedqsl': {'id': 'TrustedQSL', 'deprecated': False},
659
+ 'ttwl': {'id': 'TTWL', 'deprecated': False},
660
+ 'ttyp0': {'id': 'TTYP0', 'deprecated': False},
661
+ 'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False},
662
+ 'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False},
663
+ 'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False},
664
+ 'ucar': {'id': 'UCAR', 'deprecated': False},
665
+ 'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False},
666
+ 'ulem': {'id': 'ulem', 'deprecated': False},
667
+ 'umich-merit': {'id': 'UMich-Merit', 'deprecated': False},
668
+ 'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False},
669
+ 'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False},
670
+ 'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False},
671
+ 'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False},
672
+ 'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False},
673
+ 'unlicense': {'id': 'Unlicense', 'deprecated': False},
674
+ 'unlicense-libtelnet': {'id': 'Unlicense-libtelnet', 'deprecated': False},
675
+ 'unlicense-libwhirlpool': {'id': 'Unlicense-libwhirlpool', 'deprecated': False},
676
+ 'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False},
677
+ 'urt-rle': {'id': 'URT-RLE', 'deprecated': False},
678
+ 'vim': {'id': 'Vim', 'deprecated': False},
679
+ 'vostrom': {'id': 'VOSTROM', 'deprecated': False},
680
+ 'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False},
681
+ 'w3c': {'id': 'W3C', 'deprecated': False},
682
+ 'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False},
683
+ 'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False},
684
+ 'w3m': {'id': 'w3m', 'deprecated': False},
685
+ 'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False},
686
+ 'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False},
687
+ 'wsuipa': {'id': 'Wsuipa', 'deprecated': False},
688
+ 'wtfpl': {'id': 'WTFPL', 'deprecated': False},
689
+ 'wwl': {'id': 'wwl', 'deprecated': False},
690
+ 'wxwindows': {'id': 'wxWindows', 'deprecated': True},
691
+ 'x11': {'id': 'X11', 'deprecated': False},
692
+ 'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False},
693
+ 'x11-swapped': {'id': 'X11-swapped', 'deprecated': False},
694
+ 'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False},
695
+ 'xerox': {'id': 'Xerox', 'deprecated': False},
696
+ 'xfig': {'id': 'Xfig', 'deprecated': False},
697
+ 'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False},
698
+ 'xinetd': {'id': 'xinetd', 'deprecated': False},
699
+ 'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False},
700
+ 'xlock': {'id': 'xlock', 'deprecated': False},
701
+ 'xnet': {'id': 'Xnet', 'deprecated': False},
702
+ 'xpp': {'id': 'xpp', 'deprecated': False},
703
+ 'xskat': {'id': 'XSkat', 'deprecated': False},
704
+ 'xzoom': {'id': 'xzoom', 'deprecated': False},
705
+ 'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False},
706
+ 'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False},
707
+ 'zed': {'id': 'Zed', 'deprecated': False},
708
+ 'zeeff': {'id': 'Zeeff', 'deprecated': False},
709
+ 'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False},
710
+ 'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False},
711
+ 'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False},
712
+ 'zlib': {'id': 'Zlib', 'deprecated': False},
713
+ 'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False},
714
+ 'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False},
715
+ 'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False},
716
+ 'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False},
717
+ }
718
+
719
+ EXCEPTIONS: dict[str, SPDXException] = {
720
+ '389-exception': {'id': '389-exception', 'deprecated': False},
721
+ 'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False},
722
+ 'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False},
723
+ 'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False},
724
+ 'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False},
725
+ 'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False},
726
+ 'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False},
727
+ 'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False},
728
+ 'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False},
729
+ 'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False},
730
+ 'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False},
731
+ 'cgal-linking-exception': {'id': 'CGAL-linking-exception', 'deprecated': False},
732
+ 'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False},
733
+ 'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False},
734
+ 'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False},
735
+ 'digia-qt-lgpl-exception-1.1': {'id': 'Digia-Qt-LGPL-exception-1.1', 'deprecated': False},
736
+ 'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False},
737
+ 'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False},
738
+ 'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False},
739
+ 'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False},
740
+ 'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False},
741
+ 'fmt-exception': {'id': 'fmt-exception', 'deprecated': False},
742
+ 'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False},
743
+ 'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False},
744
+ 'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False},
745
+ 'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False},
746
+ 'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False},
747
+ 'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False},
748
+ 'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False},
749
+ 'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False},
750
+ 'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False},
751
+ 'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False},
752
+ 'gpl-3.0-389-ds-base-exception': {'id': 'GPL-3.0-389-ds-base-exception', 'deprecated': False},
753
+ 'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False},
754
+ 'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False},
755
+ 'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False},
756
+ 'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False},
757
+ 'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False},
758
+ 'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False},
759
+ 'harbour-exception': {'id': 'harbour-exception', 'deprecated': False},
760
+ 'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False},
761
+ 'independent-modules-exception': {'id': 'Independent-modules-exception', 'deprecated': False},
762
+ 'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False},
763
+ 'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False},
764
+ 'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False},
765
+ 'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False},
766
+ 'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False},
767
+ 'llgpl': {'id': 'LLGPL', 'deprecated': False},
768
+ 'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False},
769
+ 'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False},
770
+ 'mif-exception': {'id': 'mif-exception', 'deprecated': False},
771
+ 'mxml-exception': {'id': 'mxml-exception', 'deprecated': False},
772
+ 'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True},
773
+ 'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False},
774
+ 'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False},
775
+ 'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False},
776
+ 'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False},
777
+ 'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False},
778
+ 'polyparse-exception': {'id': 'polyparse-exception', 'deprecated': False},
779
+ 'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False},
780
+ 'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False},
781
+ 'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False},
782
+ 'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False},
783
+ 'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False},
784
+ 'romic-exception': {'id': 'romic-exception', 'deprecated': False},
785
+ 'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False},
786
+ 'sane-exception': {'id': 'SANE-exception', 'deprecated': False},
787
+ 'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False},
788
+ 'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False},
789
+ 'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False},
790
+ 'swi-exception': {'id': 'SWI-exception', 'deprecated': False},
791
+ 'swift-exception': {'id': 'Swift-exception', 'deprecated': False},
792
+ 'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False},
793
+ 'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False},
794
+ 'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False},
795
+ 'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False},
796
+ 'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False},
797
+ 'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False},
798
+ 'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False},
799
+ }
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/markers.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import operator
8
+ import os
9
+ import platform
10
+ import sys
11
+ from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
12
+
13
+ from ._parser import MarkerAtom, MarkerList, Op, Value, Variable
14
+ from ._parser import parse_marker as _parse_marker
15
+ from ._tokenizer import ParserSyntaxError
16
+ from .specifiers import InvalidSpecifier, Specifier
17
+ from .utils import canonicalize_name
18
+
19
+ __all__ = [
20
+ "Environment",
21
+ "EvaluateContext",
22
+ "InvalidMarker",
23
+ "Marker",
24
+ "UndefinedComparison",
25
+ "UndefinedEnvironmentName",
26
+ "default_environment",
27
+ ]
28
+
29
+ Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]
30
+ EvaluateContext = Literal["metadata", "lock_file", "requirement"]
31
+ MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}
32
+ MARKERS_REQUIRING_VERSION = {
33
+ "implementation_version",
34
+ "platform_release",
35
+ "python_full_version",
36
+ "python_version",
37
+ }
38
+
39
+
40
+ class InvalidMarker(ValueError):
41
+ """
42
+ An invalid marker was found, users should refer to PEP 508.
43
+ """
44
+
45
+
46
+ class UndefinedComparison(ValueError):
47
+ """
48
+ An invalid operation was attempted on a value that doesn't support it.
49
+ """
50
+
51
+
52
+ class UndefinedEnvironmentName(ValueError):
53
+ """
54
+ A name was attempted to be used that does not exist inside of the
55
+ environment.
56
+ """
57
+
58
+
59
+ class Environment(TypedDict):
60
+ implementation_name: str
61
+ """The implementation's identifier, e.g. ``'cpython'``."""
62
+
63
+ implementation_version: str
64
+ """
65
+ The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or
66
+ ``'7.3.13'`` for PyPy3.10 v7.3.13.
67
+ """
68
+
69
+ os_name: str
70
+ """
71
+ The value of :py:data:`os.name`. The name of the operating system dependent module
72
+ imported, e.g. ``'posix'``.
73
+ """
74
+
75
+ platform_machine: str
76
+ """
77
+ Returns the machine type, e.g. ``'i386'``.
78
+
79
+ An empty string if the value cannot be determined.
80
+ """
81
+
82
+ platform_release: str
83
+ """
84
+ The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
85
+
86
+ An empty string if the value cannot be determined.
87
+ """
88
+
89
+ platform_system: str
90
+ """
91
+ The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
92
+
93
+ An empty string if the value cannot be determined.
94
+ """
95
+
96
+ platform_version: str
97
+ """
98
+ The system's release version, e.g. ``'#3 on degas'``.
99
+
100
+ An empty string if the value cannot be determined.
101
+ """
102
+
103
+ python_full_version: str
104
+ """
105
+ The Python version as string ``'major.minor.patchlevel'``.
106
+
107
+ Note that unlike the Python :py:data:`sys.version`, this value will always include
108
+ the patchlevel (it defaults to 0).
109
+ """
110
+
111
+ platform_python_implementation: str
112
+ """
113
+ A string identifying the Python implementation, e.g. ``'CPython'``.
114
+ """
115
+
116
+ python_version: str
117
+ """The Python version as string ``'major.minor'``."""
118
+
119
+ sys_platform: str
120
+ """
121
+ This string contains a platform identifier that can be used to append
122
+ platform-specific components to :py:data:`sys.path`, for instance.
123
+
124
+ For Unix systems, except on Linux and AIX, this is the lowercased OS name as
125
+ returned by ``uname -s`` with the first part of the version as returned by
126
+ ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python
127
+ was built.
128
+ """
129
+
130
+
131
+ def _normalize_extras(
132
+ result: MarkerList | MarkerAtom | str,
133
+ ) -> MarkerList | MarkerAtom | str:
134
+ if not isinstance(result, tuple):
135
+ return result
136
+
137
+ lhs, op, rhs = result
138
+ if isinstance(lhs, Variable) and lhs.value == "extra":
139
+ normalized_extra = canonicalize_name(rhs.value)
140
+ rhs = Value(normalized_extra)
141
+ elif isinstance(rhs, Variable) and rhs.value == "extra":
142
+ normalized_extra = canonicalize_name(lhs.value)
143
+ lhs = Value(normalized_extra)
144
+ return lhs, op, rhs
145
+
146
+
147
+ def _normalize_extra_values(results: MarkerList) -> MarkerList:
148
+ """
149
+ Normalize extra values.
150
+ """
151
+
152
+ return [_normalize_extras(r) for r in results]
153
+
154
+
155
+ def _format_marker(
156
+ marker: list[str] | MarkerAtom | str, first: bool | None = True
157
+ ) -> str:
158
+ assert isinstance(marker, (list, tuple, str))
159
+
160
+ # Sometimes we have a structure like [[...]] which is a single item list
161
+ # where the single item is itself it's own list. In that case we want skip
162
+ # the rest of this function so that we don't get extraneous () on the
163
+ # outside.
164
+ if (
165
+ isinstance(marker, list)
166
+ and len(marker) == 1
167
+ and isinstance(marker[0], (list, tuple))
168
+ ):
169
+ return _format_marker(marker[0])
170
+
171
+ if isinstance(marker, list):
172
+ inner = (_format_marker(m, first=False) for m in marker)
173
+ if first:
174
+ return " ".join(inner)
175
+ else:
176
+ return "(" + " ".join(inner) + ")"
177
+ elif isinstance(marker, tuple):
178
+ return " ".join([m.serialize() for m in marker])
179
+ else:
180
+ return marker
181
+
182
+
183
+ _operators: dict[str, Operator] = {
184
+ "in": lambda lhs, rhs: lhs in rhs,
185
+ "not in": lambda lhs, rhs: lhs not in rhs,
186
+ "<": lambda _lhs, _rhs: False,
187
+ "<=": operator.eq,
188
+ "==": operator.eq,
189
+ "!=": operator.ne,
190
+ ">=": operator.eq,
191
+ ">": lambda _lhs, _rhs: False,
192
+ }
193
+
194
+
195
+ def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool:
196
+ op_str = op.serialize()
197
+ if key in MARKERS_REQUIRING_VERSION:
198
+ try:
199
+ spec = Specifier(f"{op_str}{rhs}")
200
+ except InvalidSpecifier:
201
+ pass
202
+ else:
203
+ return spec.contains(lhs, prereleases=True)
204
+
205
+ oper: Operator | None = _operators.get(op_str)
206
+ if oper is None:
207
+ raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
208
+
209
+ return oper(lhs, rhs)
210
+
211
+
212
+ def _normalize(
213
+ lhs: str, rhs: str | AbstractSet[str], key: str
214
+ ) -> tuple[str, str | AbstractSet[str]]:
215
+ # PEP 685 - Comparison of extra names for optional distribution dependencies
216
+ # https://peps.python.org/pep-0685/
217
+ # > When comparing extra names, tools MUST normalize the names being
218
+ # > compared using the semantics outlined in PEP 503 for names
219
+ if key == "extra":
220
+ assert isinstance(rhs, str), "extra value must be a string"
221
+ # Both sides are normalized at this point already
222
+ return (lhs, rhs)
223
+ if key in MARKERS_ALLOWING_SET:
224
+ if isinstance(rhs, str): # pragma: no cover
225
+ return (canonicalize_name(lhs), canonicalize_name(rhs))
226
+ else:
227
+ return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})
228
+
229
+ # other environment markers don't have such standards
230
+ return lhs, rhs
231
+
232
+
233
+ def _evaluate_markers(
234
+ markers: MarkerList, environment: dict[str, str | AbstractSet[str]]
235
+ ) -> bool:
236
+ groups: list[list[bool]] = [[]]
237
+
238
+ for marker in markers:
239
+ if isinstance(marker, list):
240
+ groups[-1].append(_evaluate_markers(marker, environment))
241
+ elif isinstance(marker, tuple):
242
+ lhs, op, rhs = marker
243
+
244
+ if isinstance(lhs, Variable):
245
+ environment_key = lhs.value
246
+ lhs_value = environment[environment_key]
247
+ rhs_value = rhs.value
248
+ else:
249
+ lhs_value = lhs.value
250
+ environment_key = rhs.value
251
+ rhs_value = environment[environment_key]
252
+
253
+ assert isinstance(lhs_value, str), "lhs must be a string"
254
+ lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
255
+ groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key))
256
+ elif marker == "or":
257
+ groups.append([])
258
+ elif marker == "and":
259
+ pass
260
+ else: # pragma: nocover
261
+ raise TypeError(f"Unexpected marker {marker!r}")
262
+
263
+ return any(all(item) for item in groups)
264
+
265
+
266
+ def format_full_version(info: sys._version_info) -> str:
267
+ version = f"{info.major}.{info.minor}.{info.micro}"
268
+ kind = info.releaselevel
269
+ if kind != "final":
270
+ version += kind[0] + str(info.serial)
271
+ return version
272
+
273
+
274
+ def default_environment() -> Environment:
275
+ iver = format_full_version(sys.implementation.version)
276
+ implementation_name = sys.implementation.name
277
+ return {
278
+ "implementation_name": implementation_name,
279
+ "implementation_version": iver,
280
+ "os_name": os.name,
281
+ "platform_machine": platform.machine(),
282
+ "platform_release": platform.release(),
283
+ "platform_system": platform.system(),
284
+ "platform_version": platform.version(),
285
+ "python_full_version": platform.python_version(),
286
+ "platform_python_implementation": platform.python_implementation(),
287
+ "python_version": ".".join(platform.python_version_tuple()[:2]),
288
+ "sys_platform": sys.platform,
289
+ }
290
+
291
+
292
+ class Marker:
293
+ def __init__(self, marker: str) -> None:
294
+ # Note: We create a Marker object without calling this constructor in
295
+ # packaging.requirements.Requirement. If any additional logic is
296
+ # added here, make sure to mirror/adapt Requirement.
297
+
298
+ # If this fails and throws an error, the repr still expects _markers to
299
+ # be defined.
300
+ self._markers: MarkerList = []
301
+
302
+ try:
303
+ self._markers = _normalize_extra_values(_parse_marker(marker))
304
+ # The attribute `_markers` can be described in terms of a recursive type:
305
+ # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
306
+ #
307
+ # For example, the following expression:
308
+ # python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
309
+ #
310
+ # is parsed into:
311
+ # [
312
+ # (<Variable('python_version')>, <Op('>')>, <Value('3.6')>),
313
+ # 'and',
314
+ # [
315
+ # (<Variable('python_version')>, <Op('==')>, <Value('3.6')>),
316
+ # 'or',
317
+ # (<Variable('os_name')>, <Op('==')>, <Value('unix')>)
318
+ # ]
319
+ # ]
320
+ except ParserSyntaxError as e:
321
+ raise InvalidMarker(str(e)) from e
322
+
323
+ def __str__(self) -> str:
324
+ return _format_marker(self._markers)
325
+
326
+ def __repr__(self) -> str:
327
+ return f"<{self.__class__.__name__}('{self}')>"
328
+
329
+ def __hash__(self) -> int:
330
+ return hash(str(self))
331
+
332
+ def __eq__(self, other: object) -> bool:
333
+ if not isinstance(other, Marker):
334
+ return NotImplemented
335
+
336
+ return str(self) == str(other)
337
+
338
+ def evaluate(
339
+ self,
340
+ environment: Mapping[str, str | AbstractSet[str]] | None = None,
341
+ context: EvaluateContext = "metadata",
342
+ ) -> bool:
343
+ """Evaluate a marker.
344
+
345
+ Return the boolean from evaluating the given marker against the
346
+ environment. environment is an optional argument to override all or
347
+ part of the determined environment. The *context* parameter specifies what
348
+ context the markers are being evaluated for, which influences what markers
349
+ are considered valid. Acceptable values are "metadata" (for core metadata;
350
+ default), "lock_file", and "requirement" (i.e. all other situations).
351
+
352
+ The environment is determined from the current Python process.
353
+ """
354
+ current_environment = cast(
355
+ "dict[str, str | AbstractSet[str]]", default_environment()
356
+ )
357
+ if context == "lock_file":
358
+ current_environment.update(
359
+ extras=frozenset(), dependency_groups=frozenset()
360
+ )
361
+ elif context == "metadata":
362
+ current_environment["extra"] = ""
363
+
364
+ if environment is not None:
365
+ current_environment.update(environment)
366
+ if "extra" in current_environment:
367
+ # The API used to allow setting extra to None. We need to handle
368
+ # this case for backwards compatibility. Also skip running
369
+ # normalize name if extra is empty.
370
+ extra = cast("str | None", current_environment["extra"])
371
+ current_environment["extra"] = canonicalize_name(extra) if extra else ""
372
+
373
+ return _evaluate_markers(
374
+ self._markers, _repair_python_full_version(current_environment)
375
+ )
376
+
377
+
378
+ def _repair_python_full_version(
379
+ env: dict[str, str | AbstractSet[str]],
380
+ ) -> dict[str, str | AbstractSet[str]]:
381
+ """
382
+ Work around platform.python_version() returning something that is not PEP 440
383
+ compliant for non-tagged Python builds.
384
+ """
385
+ python_full_version = cast("str", env["python_full_version"])
386
+ if python_full_version.endswith("+"):
387
+ env["python_full_version"] = f"{python_full_version}local"
388
+ return env
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/metadata.py ADDED
@@ -0,0 +1,978 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import email.feedparser
4
+ import email.header
5
+ import email.message
6
+ import email.parser
7
+ import email.policy
8
+ import keyword
9
+ import pathlib
10
+ import sys
11
+ import typing
12
+ from typing import (
13
+ Any,
14
+ Callable,
15
+ Generic,
16
+ Literal,
17
+ TypedDict,
18
+ cast,
19
+ )
20
+
21
+ from . import licenses, requirements, specifiers, utils
22
+ from . import version as version_module
23
+
24
+ if typing.TYPE_CHECKING:
25
+ from .licenses import NormalizedLicenseExpression
26
+
27
+ T = typing.TypeVar("T")
28
+
29
+
30
+ if sys.version_info >= (3, 11): # pragma: no cover
31
+ ExceptionGroup = ExceptionGroup # noqa: F821
32
+ else: # pragma: no cover
33
+
34
+ class ExceptionGroup(Exception):
35
+ """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
36
+
37
+ If :external:exc:`ExceptionGroup` is already defined by Python itself,
38
+ that version is used instead.
39
+ """
40
+
41
+ message: str
42
+ exceptions: list[Exception]
43
+
44
+ def __init__(self, message: str, exceptions: list[Exception]) -> None:
45
+ self.message = message
46
+ self.exceptions = exceptions
47
+
48
+ def __repr__(self) -> str:
49
+ return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
50
+
51
+
52
+ class InvalidMetadata(ValueError):
53
+ """A metadata field contains invalid data."""
54
+
55
+ field: str
56
+ """The name of the field that contains invalid data."""
57
+
58
+ def __init__(self, field: str, message: str) -> None:
59
+ self.field = field
60
+ super().__init__(message)
61
+
62
+
63
+ # The RawMetadata class attempts to make as few assumptions about the underlying
64
+ # serialization formats as possible. The idea is that as long as a serialization
65
+ # formats offer some very basic primitives in *some* way then we can support
66
+ # serializing to and from that format.
67
+ class RawMetadata(TypedDict, total=False):
68
+ """A dictionary of raw core metadata.
69
+
70
+ Each field in core metadata maps to a key of this dictionary (when data is
71
+ provided). The key is lower-case and underscores are used instead of dashes
72
+ compared to the equivalent core metadata field. Any core metadata field that
73
+ can be specified multiple times or can hold multiple values in a single
74
+ field have a key with a plural name. See :class:`Metadata` whose attributes
75
+ match the keys of this dictionary.
76
+
77
+ Core metadata fields that can be specified multiple times are stored as a
78
+ list or dict depending on which is appropriate for the field. Any fields
79
+ which hold multiple values in a single field are stored as a list.
80
+
81
+ """
82
+
83
+ # Metadata 1.0 - PEP 241
84
+ metadata_version: str
85
+ name: str
86
+ version: str
87
+ platforms: list[str]
88
+ summary: str
89
+ description: str
90
+ keywords: list[str]
91
+ home_page: str
92
+ author: str
93
+ author_email: str
94
+ license: str
95
+
96
+ # Metadata 1.1 - PEP 314
97
+ supported_platforms: list[str]
98
+ download_url: str
99
+ classifiers: list[str]
100
+ requires: list[str]
101
+ provides: list[str]
102
+ obsoletes: list[str]
103
+
104
+ # Metadata 1.2 - PEP 345
105
+ maintainer: str
106
+ maintainer_email: str
107
+ requires_dist: list[str]
108
+ provides_dist: list[str]
109
+ obsoletes_dist: list[str]
110
+ requires_python: str
111
+ requires_external: list[str]
112
+ project_urls: dict[str, str]
113
+
114
+ # Metadata 2.0
115
+ # PEP 426 attempted to completely revamp the metadata format
116
+ # but got stuck without ever being able to build consensus on
117
+ # it and ultimately ended up withdrawn.
118
+ #
119
+ # However, a number of tools had started emitting METADATA with
120
+ # `2.0` Metadata-Version, so for historical reasons, this version
121
+ # was skipped.
122
+
123
+ # Metadata 2.1 - PEP 566
124
+ description_content_type: str
125
+ provides_extra: list[str]
126
+
127
+ # Metadata 2.2 - PEP 643
128
+ dynamic: list[str]
129
+
130
+ # Metadata 2.3 - PEP 685
131
+ # No new fields were added in PEP 685, just some edge case were
132
+ # tightened up to provide better interoperability.
133
+
134
+ # Metadata 2.4 - PEP 639
135
+ license_expression: str
136
+ license_files: list[str]
137
+
138
+ # Metadata 2.5 - PEP 794
139
+ import_names: list[str]
140
+ import_namespaces: list[str]
141
+
142
+
143
+ # 'keywords' is special as it's a string in the core metadata spec, but we
144
+ # represent it as a list.
145
+ _STRING_FIELDS = {
146
+ "author",
147
+ "author_email",
148
+ "description",
149
+ "description_content_type",
150
+ "download_url",
151
+ "home_page",
152
+ "license",
153
+ "license_expression",
154
+ "maintainer",
155
+ "maintainer_email",
156
+ "metadata_version",
157
+ "name",
158
+ "requires_python",
159
+ "summary",
160
+ "version",
161
+ }
162
+
163
+ _LIST_FIELDS = {
164
+ "classifiers",
165
+ "dynamic",
166
+ "license_files",
167
+ "obsoletes",
168
+ "obsoletes_dist",
169
+ "platforms",
170
+ "provides",
171
+ "provides_dist",
172
+ "provides_extra",
173
+ "requires",
174
+ "requires_dist",
175
+ "requires_external",
176
+ "supported_platforms",
177
+ "import_names",
178
+ "import_namespaces",
179
+ }
180
+
181
+ _DICT_FIELDS = {
182
+ "project_urls",
183
+ }
184
+
185
+
186
+ def _parse_keywords(data: str) -> list[str]:
187
+ """Split a string of comma-separated keywords into a list of keywords."""
188
+ return [k.strip() for k in data.split(",")]
189
+
190
+
191
+ def _parse_project_urls(data: list[str]) -> dict[str, str]:
192
+ """Parse a list of label/URL string pairings separated by a comma."""
193
+ urls = {}
194
+ for pair in data:
195
+ # Our logic is slightly tricky here as we want to try and do
196
+ # *something* reasonable with malformed data.
197
+ #
198
+ # The main thing that we have to worry about, is data that does
199
+ # not have a ',' at all to split the label from the Value. There
200
+ # isn't a singular right answer here, and we will fail validation
201
+ # later on (if the caller is validating) so it doesn't *really*
202
+ # matter, but since the missing value has to be an empty str
203
+ # and our return value is dict[str, str], if we let the key
204
+ # be the missing value, then they'd have multiple '' values that
205
+ # overwrite each other in a accumulating dict.
206
+ #
207
+ # The other potential issue is that it's possible to have the
208
+ # same label multiple times in the metadata, with no solid "right"
209
+ # answer with what to do in that case. As such, we'll do the only
210
+ # thing we can, which is treat the field as unparsable and add it
211
+ # to our list of unparsed fields.
212
+ #
213
+ # TODO: The spec doesn't say anything about if the keys should be
214
+ # considered case sensitive or not... logically they should
215
+ # be case-preserving and case-insensitive, but doing that
216
+ # would open up more cases where we might have duplicate
217
+ # entries.
218
+ label, _, url = (s.strip() for s in pair.partition(","))
219
+
220
+ if label in urls:
221
+ # The label already exists in our set of urls, so this field
222
+ # is unparsable, and we can just add the whole thing to our
223
+ # unparsable data and stop processing it.
224
+ raise KeyError("duplicate labels in project urls")
225
+ urls[label] = url
226
+
227
+ return urls
228
+
229
+
230
+ def _get_payload(msg: email.message.Message, source: bytes | str) -> str:
231
+ """Get the body of the message."""
232
+ # If our source is a str, then our caller has managed encodings for us,
233
+ # and we don't need to deal with it.
234
+ if isinstance(source, str):
235
+ payload = msg.get_payload()
236
+ assert isinstance(payload, str)
237
+ return payload
238
+ # If our source is a bytes, then we're managing the encoding and we need
239
+ # to deal with it.
240
+ else:
241
+ bpayload = msg.get_payload(decode=True)
242
+ assert isinstance(bpayload, bytes)
243
+ try:
244
+ return bpayload.decode("utf8", "strict")
245
+ except UnicodeDecodeError as exc:
246
+ raise ValueError("payload in an invalid encoding") from exc
247
+
248
+
249
+ # The various parse_FORMAT functions here are intended to be as lenient as
250
+ # possible in their parsing, while still returning a correctly typed
251
+ # RawMetadata.
252
+ #
253
+ # To aid in this, we also generally want to do as little touching of the
254
+ # data as possible, except where there are possibly some historic holdovers
255
+ # that make valid data awkward to work with.
256
+ #
257
+ # While this is a lower level, intermediate format than our ``Metadata``
258
+ # class, some light touch ups can make a massive difference in usability.
259
+
260
+ # Map METADATA fields to RawMetadata.
261
+ _EMAIL_TO_RAW_MAPPING = {
262
+ "author": "author",
263
+ "author-email": "author_email",
264
+ "classifier": "classifiers",
265
+ "description": "description",
266
+ "description-content-type": "description_content_type",
267
+ "download-url": "download_url",
268
+ "dynamic": "dynamic",
269
+ "home-page": "home_page",
270
+ "import-name": "import_names",
271
+ "import-namespace": "import_namespaces",
272
+ "keywords": "keywords",
273
+ "license": "license",
274
+ "license-expression": "license_expression",
275
+ "license-file": "license_files",
276
+ "maintainer": "maintainer",
277
+ "maintainer-email": "maintainer_email",
278
+ "metadata-version": "metadata_version",
279
+ "name": "name",
280
+ "obsoletes": "obsoletes",
281
+ "obsoletes-dist": "obsoletes_dist",
282
+ "platform": "platforms",
283
+ "project-url": "project_urls",
284
+ "provides": "provides",
285
+ "provides-dist": "provides_dist",
286
+ "provides-extra": "provides_extra",
287
+ "requires": "requires",
288
+ "requires-dist": "requires_dist",
289
+ "requires-external": "requires_external",
290
+ "requires-python": "requires_python",
291
+ "summary": "summary",
292
+ "supported-platform": "supported_platforms",
293
+ "version": "version",
294
+ }
295
+ _RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
296
+
297
+
298
+ # This class is for writing RFC822 messages
299
+ class RFC822Policy(email.policy.EmailPolicy):
300
+ """
301
+ This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse``
302
+ implementation that handles multi-line values, and some nice defaults.
303
+ """
304
+
305
+ utf8 = True
306
+ mangle_from_ = False
307
+ max_line_length = 0
308
+
309
+ def header_store_parse(self, name: str, value: str) -> tuple[str, str]:
310
+ size = len(name) + 2
311
+ value = value.replace("\n", "\n" + " " * size)
312
+ return (name, value)
313
+
314
+
315
+ # This class is for writing RFC822 messages
316
+ class RFC822Message(email.message.EmailMessage):
317
+ """
318
+ This is :class:`email.message.EmailMessage` with two small changes: it defaults to
319
+ our `RFC822Policy`, and it correctly writes unicode when being called
320
+ with `bytes()`.
321
+ """
322
+
323
+ def __init__(self) -> None:
324
+ super().__init__(policy=RFC822Policy())
325
+
326
+ def as_bytes(
327
+ self, unixfrom: bool = False, policy: email.policy.Policy | None = None
328
+ ) -> bytes:
329
+ """
330
+ Return the bytes representation of the message.
331
+
332
+ This handles unicode encoding.
333
+ """
334
+ return self.as_string(unixfrom, policy=policy).encode("utf-8")
335
+
336
+
337
+ def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]:
338
+ """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
339
+
340
+ This function returns a two-item tuple of dicts. The first dict is of
341
+ recognized fields from the core metadata specification. Fields that can be
342
+ parsed and translated into Python's built-in types are converted
343
+ appropriately. All other fields are left as-is. Fields that are allowed to
344
+ appear multiple times are stored as lists.
345
+
346
+ The second dict contains all other fields from the metadata. This includes
347
+ any unrecognized fields. It also includes any fields which are expected to
348
+ be parsed into a built-in type but were not formatted appropriately. Finally,
349
+ any fields that are expected to appear only once but are repeated are
350
+ included in this dict.
351
+
352
+ """
353
+ raw: dict[str, str | list[str] | dict[str, str]] = {}
354
+ unparsed: dict[str, list[str]] = {}
355
+
356
+ if isinstance(data, str):
357
+ parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data)
358
+ else:
359
+ parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
360
+
361
+ # We have to wrap parsed.keys() in a set, because in the case of multiple
362
+ # values for a key (a list), the key will appear multiple times in the
363
+ # list of keys, but we're avoiding that by using get_all().
364
+ for name_with_case in frozenset(parsed.keys()):
365
+ # Header names in RFC are case insensitive, so we'll normalize to all
366
+ # lower case to make comparisons easier.
367
+ name = name_with_case.lower()
368
+
369
+ # We use get_all() here, even for fields that aren't multiple use,
370
+ # because otherwise someone could have e.g. two Name fields, and we
371
+ # would just silently ignore it rather than doing something about it.
372
+ headers = parsed.get_all(name) or []
373
+
374
+ # The way the email module works when parsing bytes is that it
375
+ # unconditionally decodes the bytes as ascii using the surrogateescape
376
+ # handler. When you pull that data back out (such as with get_all() ),
377
+ # it looks to see if the str has any surrogate escapes, and if it does
378
+ # it wraps it in a Header object instead of returning the string.
379
+ #
380
+ # As such, we'll look for those Header objects, and fix up the encoding.
381
+ value = []
382
+ # Flag if we have run into any issues processing the headers, thus
383
+ # signalling that the data belongs in 'unparsed'.
384
+ valid_encoding = True
385
+ for h in headers:
386
+ # It's unclear if this can return more types than just a Header or
387
+ # a str, so we'll just assert here to make sure.
388
+ assert isinstance(h, (email.header.Header, str))
389
+
390
+ # If it's a header object, we need to do our little dance to get
391
+ # the real data out of it. In cases where there is invalid data
392
+ # we're going to end up with mojibake, but there's no obvious, good
393
+ # way around that without reimplementing parts of the Header object
394
+ # ourselves.
395
+ #
396
+ # That should be fine since, if mojibacked happens, this key is
397
+ # going into the unparsed dict anyways.
398
+ if isinstance(h, email.header.Header):
399
+ # The Header object stores it's data as chunks, and each chunk
400
+ # can be independently encoded, so we'll need to check each
401
+ # of them.
402
+ chunks: list[tuple[bytes, str | None]] = []
403
+ for binary, _encoding in email.header.decode_header(h):
404
+ try:
405
+ binary.decode("utf8", "strict")
406
+ except UnicodeDecodeError:
407
+ # Enable mojibake.
408
+ encoding = "latin1"
409
+ valid_encoding = False
410
+ else:
411
+ encoding = "utf8"
412
+ chunks.append((binary, encoding))
413
+
414
+ # Turn our chunks back into a Header object, then let that
415
+ # Header object do the right thing to turn them into a
416
+ # string for us.
417
+ value.append(str(email.header.make_header(chunks)))
418
+ # This is already a string, so just add it.
419
+ else:
420
+ value.append(h)
421
+
422
+ # We've processed all of our values to get them into a list of str,
423
+ # but we may have mojibake data, in which case this is an unparsed
424
+ # field.
425
+ if not valid_encoding:
426
+ unparsed[name] = value
427
+ continue
428
+
429
+ raw_name = _EMAIL_TO_RAW_MAPPING.get(name)
430
+ if raw_name is None:
431
+ # This is a bit of a weird situation, we've encountered a key that
432
+ # we don't know what it means, so we don't know whether it's meant
433
+ # to be a list or not.
434
+ #
435
+ # Since we can't really tell one way or another, we'll just leave it
436
+ # as a list, even though it may be a single item list, because that's
437
+ # what makes the most sense for email headers.
438
+ unparsed[name] = value
439
+ continue
440
+
441
+ # If this is one of our string fields, then we'll check to see if our
442
+ # value is a list of a single item. If it is then we'll assume that
443
+ # it was emitted as a single string, and unwrap the str from inside
444
+ # the list.
445
+ #
446
+ # If it's any other kind of data, then we haven't the faintest clue
447
+ # what we should parse it as, and we have to just add it to our list
448
+ # of unparsed stuff.
449
+ if raw_name in _STRING_FIELDS and len(value) == 1:
450
+ raw[raw_name] = value[0]
451
+ # If this is import_names, we need to special case the empty field
452
+ # case, which converts to an empty list instead of None. We can't let
453
+ # the empty case slip through, as it will fail validation.
454
+ elif raw_name == "import_names" and value == [""]:
455
+ raw[raw_name] = []
456
+ # If this is one of our list of string fields, then we can just assign
457
+ # the value, since email *only* has strings, and our get_all() call
458
+ # above ensures that this is a list.
459
+ elif raw_name in _LIST_FIELDS:
460
+ raw[raw_name] = value
461
+ # Special Case: Keywords
462
+ # The keywords field is implemented in the metadata spec as a str,
463
+ # but it conceptually is a list of strings, and is serialized using
464
+ # ", ".join(keywords), so we'll do some light data massaging to turn
465
+ # this into what it logically is.
466
+ elif raw_name == "keywords" and len(value) == 1:
467
+ raw[raw_name] = _parse_keywords(value[0])
468
+ # Special Case: Project-URL
469
+ # The project urls is implemented in the metadata spec as a list of
470
+ # specially-formatted strings that represent a key and a value, which
471
+ # is fundamentally a mapping, however the email format doesn't support
472
+ # mappings in a sane way, so it was crammed into a list of strings
473
+ # instead.
474
+ #
475
+ # We will do a little light data massaging to turn this into a map as
476
+ # it logically should be.
477
+ elif raw_name == "project_urls":
478
+ try:
479
+ raw[raw_name] = _parse_project_urls(value)
480
+ except KeyError:
481
+ unparsed[name] = value
482
+ # Nothing that we've done has managed to parse this, so it'll just
483
+ # throw it in our unparsable data and move on.
484
+ else:
485
+ unparsed[name] = value
486
+
487
+ # We need to support getting the Description from the message payload in
488
+ # addition to getting it from the the headers. This does mean, though, there
489
+ # is the possibility of it being set both ways, in which case we put both
490
+ # in 'unparsed' since we don't know which is right.
491
+ try:
492
+ payload = _get_payload(parsed, data)
493
+ except ValueError:
494
+ unparsed.setdefault("description", []).append(
495
+ parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload]
496
+ )
497
+ else:
498
+ if payload:
499
+ # Check to see if we've already got a description, if so then both
500
+ # it, and this body move to unparsable.
501
+ if "description" in raw:
502
+ description_header = cast("str", raw.pop("description"))
503
+ unparsed.setdefault("description", []).extend(
504
+ [description_header, payload]
505
+ )
506
+ elif "description" in unparsed:
507
+ unparsed["description"].append(payload)
508
+ else:
509
+ raw["description"] = payload
510
+
511
+ # We need to cast our `raw` to a metadata, because a TypedDict only support
512
+ # literal key names, but we're computing our key names on purpose, but the
513
+ # way this function is implemented, our `TypedDict` can only have valid key
514
+ # names.
515
+ return cast("RawMetadata", raw), unparsed
516
+
517
+
518
+ _NOT_FOUND = object()
519
+
520
+
521
+ # Keep the two values in sync.
522
+ _VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
523
+ _MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
524
+
525
+ _REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
526
+
527
+
528
+ class _Validator(Generic[T]):
529
+ """Validate a metadata field.
530
+
531
+ All _process_*() methods correspond to a core metadata field. The method is
532
+ called with the field's raw value. If the raw value is valid it is returned
533
+ in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field).
534
+ If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause
535
+ as appropriate).
536
+ """
537
+
538
+ name: str
539
+ raw_name: str
540
+ added: _MetadataVersion
541
+
542
+ def __init__(
543
+ self,
544
+ *,
545
+ added: _MetadataVersion = "1.0",
546
+ ) -> None:
547
+ self.added = added
548
+
549
+ def __set_name__(self, _owner: Metadata, name: str) -> None:
550
+ self.name = name
551
+ self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
552
+
553
+ def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T:
554
+ # With Python 3.8, the caching can be replaced with functools.cached_property().
555
+ # No need to check the cache as attribute lookup will resolve into the
556
+ # instance's __dict__ before __get__ is called.
557
+ cache = instance.__dict__
558
+ value = instance._raw.get(self.name)
559
+
560
+ # To make the _process_* methods easier, we'll check if the value is None
561
+ # and if this field is NOT a required attribute, and if both of those
562
+ # things are true, we'll skip the the converter. This will mean that the
563
+ # converters never have to deal with the None union.
564
+ if self.name in _REQUIRED_ATTRS or value is not None:
565
+ try:
566
+ converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}")
567
+ except AttributeError:
568
+ pass
569
+ else:
570
+ value = converter(value)
571
+
572
+ cache[self.name] = value
573
+ try:
574
+ del instance._raw[self.name] # type: ignore[misc]
575
+ except KeyError:
576
+ pass
577
+
578
+ return cast("T", value)
579
+
580
+ def _invalid_metadata(
581
+ self, msg: str, cause: Exception | None = None
582
+ ) -> InvalidMetadata:
583
+ exc = InvalidMetadata(
584
+ self.raw_name, msg.format_map({"field": repr(self.raw_name)})
585
+ )
586
+ exc.__cause__ = cause
587
+ return exc
588
+
589
+ def _process_metadata_version(self, value: str) -> _MetadataVersion:
590
+ # Implicitly makes Metadata-Version required.
591
+ if value not in _VALID_METADATA_VERSIONS:
592
+ raise self._invalid_metadata(f"{value!r} is not a valid metadata version")
593
+ return cast("_MetadataVersion", value)
594
+
595
+ def _process_name(self, value: str) -> str:
596
+ if not value:
597
+ raise self._invalid_metadata("{field} is a required field")
598
+ # Validate the name as a side-effect.
599
+ try:
600
+ utils.canonicalize_name(value, validate=True)
601
+ except utils.InvalidName as exc:
602
+ raise self._invalid_metadata(
603
+ f"{value!r} is invalid for {{field}}", cause=exc
604
+ ) from exc
605
+ else:
606
+ return value
607
+
608
+ def _process_version(self, value: str) -> version_module.Version:
609
+ if not value:
610
+ raise self._invalid_metadata("{field} is a required field")
611
+ try:
612
+ return version_module.parse(value)
613
+ except version_module.InvalidVersion as exc:
614
+ raise self._invalid_metadata(
615
+ f"{value!r} is invalid for {{field}}", cause=exc
616
+ ) from exc
617
+
618
+ def _process_summary(self, value: str) -> str:
619
+ """Check the field contains no newlines."""
620
+ if "\n" in value:
621
+ raise self._invalid_metadata("{field} must be a single line")
622
+ return value
623
+
624
+ def _process_description_content_type(self, value: str) -> str:
625
+ content_types = {"text/plain", "text/x-rst", "text/markdown"}
626
+ message = email.message.EmailMessage()
627
+ message["content-type"] = value
628
+
629
+ content_type, parameters = (
630
+ # Defaults to `text/plain` if parsing failed.
631
+ message.get_content_type().lower(),
632
+ message["content-type"].params,
633
+ )
634
+ # Check if content-type is valid or defaulted to `text/plain` and thus was
635
+ # not parseable.
636
+ if content_type not in content_types or content_type not in value.lower():
637
+ raise self._invalid_metadata(
638
+ f"{{field}} must be one of {list(content_types)}, not {value!r}"
639
+ )
640
+
641
+ charset = parameters.get("charset", "UTF-8")
642
+ if charset != "UTF-8":
643
+ raise self._invalid_metadata(
644
+ f"{{field}} can only specify the UTF-8 charset, not {list(charset)}"
645
+ )
646
+
647
+ markdown_variants = {"GFM", "CommonMark"}
648
+ variant = parameters.get("variant", "GFM") # Use an acceptable default.
649
+ if content_type == "text/markdown" and variant not in markdown_variants:
650
+ raise self._invalid_metadata(
651
+ f"valid Markdown variants for {{field}} are {list(markdown_variants)}, "
652
+ f"not {variant!r}",
653
+ )
654
+ return value
655
+
656
+ def _process_dynamic(self, value: list[str]) -> list[str]:
657
+ for dynamic_field in map(str.lower, value):
658
+ if dynamic_field in {"name", "version", "metadata-version"}:
659
+ raise self._invalid_metadata(
660
+ f"{dynamic_field!r} is not allowed as a dynamic field"
661
+ )
662
+ elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:
663
+ raise self._invalid_metadata(
664
+ f"{dynamic_field!r} is not a valid dynamic field"
665
+ )
666
+ return list(map(str.lower, value))
667
+
668
+ def _process_provides_extra(
669
+ self,
670
+ value: list[str],
671
+ ) -> list[utils.NormalizedName]:
672
+ normalized_names = []
673
+ try:
674
+ for name in value:
675
+ normalized_names.append(utils.canonicalize_name(name, validate=True))
676
+ except utils.InvalidName as exc:
677
+ raise self._invalid_metadata(
678
+ f"{name!r} is invalid for {{field}}", cause=exc
679
+ ) from exc
680
+ else:
681
+ return normalized_names
682
+
683
+ def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
684
+ try:
685
+ return specifiers.SpecifierSet(value)
686
+ except specifiers.InvalidSpecifier as exc:
687
+ raise self._invalid_metadata(
688
+ f"{value!r} is invalid for {{field}}", cause=exc
689
+ ) from exc
690
+
691
+ def _process_requires_dist(
692
+ self,
693
+ value: list[str],
694
+ ) -> list[requirements.Requirement]:
695
+ reqs = []
696
+ try:
697
+ for req in value:
698
+ reqs.append(requirements.Requirement(req))
699
+ except requirements.InvalidRequirement as exc:
700
+ raise self._invalid_metadata(
701
+ f"{req!r} is invalid for {{field}}", cause=exc
702
+ ) from exc
703
+ else:
704
+ return reqs
705
+
706
+ def _process_license_expression(self, value: str) -> NormalizedLicenseExpression:
707
+ try:
708
+ return licenses.canonicalize_license_expression(value)
709
+ except ValueError as exc:
710
+ raise self._invalid_metadata(
711
+ f"{value!r} is invalid for {{field}}", cause=exc
712
+ ) from exc
713
+
714
+ def _process_license_files(self, value: list[str]) -> list[str]:
715
+ paths = []
716
+ for path in value:
717
+ if ".." in path:
718
+ raise self._invalid_metadata(
719
+ f"{path!r} is invalid for {{field}}, "
720
+ "parent directory indicators are not allowed"
721
+ )
722
+ if "*" in path:
723
+ raise self._invalid_metadata(
724
+ f"{path!r} is invalid for {{field}}, paths must be resolved"
725
+ )
726
+ if (
727
+ pathlib.PurePosixPath(path).is_absolute()
728
+ or pathlib.PureWindowsPath(path).is_absolute()
729
+ ):
730
+ raise self._invalid_metadata(
731
+ f"{path!r} is invalid for {{field}}, paths must be relative"
732
+ )
733
+ if pathlib.PureWindowsPath(path).as_posix() != path:
734
+ raise self._invalid_metadata(
735
+ f"{path!r} is invalid for {{field}}, paths must use '/' delimiter"
736
+ )
737
+ paths.append(path)
738
+ return paths
739
+
740
+ def _process_import_names(self, value: list[str]) -> list[str]:
741
+ for import_name in value:
742
+ name, semicolon, private = import_name.partition(";")
743
+ name = name.rstrip()
744
+ for identifier in name.split("."):
745
+ if not identifier.isidentifier():
746
+ raise self._invalid_metadata(
747
+ f"{name!r} is invalid for {{field}}; "
748
+ f"{identifier!r} is not a valid identifier"
749
+ )
750
+ elif keyword.iskeyword(identifier):
751
+ raise self._invalid_metadata(
752
+ f"{name!r} is invalid for {{field}}; "
753
+ f"{identifier!r} is a keyword"
754
+ )
755
+ if semicolon and private.lstrip() != "private":
756
+ raise self._invalid_metadata(
757
+ f"{import_name!r} is invalid for {{field}}; "
758
+ "the only valid option is 'private'"
759
+ )
760
+ return value
761
+
762
+ _process_import_namespaces = _process_import_names
763
+
764
+
765
+ class Metadata:
766
+ """Representation of distribution metadata.
767
+
768
+ Compared to :class:`RawMetadata`, this class provides objects representing
769
+ metadata fields instead of only using built-in types. Any invalid metadata
770
+ will cause :exc:`InvalidMetadata` to be raised (with a
771
+ :py:attr:`~BaseException.__cause__` attribute as appropriate).
772
+ """
773
+
774
+ _raw: RawMetadata
775
+
776
+ @classmethod
777
+ def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata:
778
+ """Create an instance from :class:`RawMetadata`.
779
+
780
+ If *validate* is true, all metadata will be validated. All exceptions
781
+ related to validation will be gathered and raised as an :class:`ExceptionGroup`.
782
+ """
783
+ ins = cls()
784
+ ins._raw = data.copy() # Mutations occur due to caching enriched values.
785
+
786
+ if validate:
787
+ exceptions: list[Exception] = []
788
+ try:
789
+ metadata_version = ins.metadata_version
790
+ metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
791
+ except InvalidMetadata as metadata_version_exc:
792
+ exceptions.append(metadata_version_exc)
793
+ metadata_version = None
794
+
795
+ # Make sure to check for the fields that are present, the required
796
+ # fields (so their absence can be reported).
797
+ fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS
798
+ # Remove fields that have already been checked.
799
+ fields_to_check -= {"metadata_version"}
800
+
801
+ for key in fields_to_check:
802
+ try:
803
+ if metadata_version:
804
+ # Can't use getattr() as that triggers descriptor protocol which
805
+ # will fail due to no value for the instance argument.
806
+ try:
807
+ field_metadata_version = cls.__dict__[key].added
808
+ except KeyError:
809
+ exc = InvalidMetadata(key, f"unrecognized field: {key!r}")
810
+ exceptions.append(exc)
811
+ continue
812
+ field_age = _VALID_METADATA_VERSIONS.index(
813
+ field_metadata_version
814
+ )
815
+ if field_age > metadata_age:
816
+ field = _RAW_TO_EMAIL_MAPPING[key]
817
+ exc = InvalidMetadata(
818
+ field,
819
+ f"{field} introduced in metadata version "
820
+ f"{field_metadata_version}, not {metadata_version}",
821
+ )
822
+ exceptions.append(exc)
823
+ continue
824
+ getattr(ins, key)
825
+ except InvalidMetadata as exc:
826
+ exceptions.append(exc)
827
+
828
+ if exceptions:
829
+ raise ExceptionGroup("invalid metadata", exceptions)
830
+
831
+ return ins
832
+
833
+ @classmethod
834
+ def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata:
835
+ """Parse metadata from email headers.
836
+
837
+ If *validate* is true, the metadata will be validated. All exceptions
838
+ related to validation will be gathered and raised as an :class:`ExceptionGroup`.
839
+ """
840
+ raw, unparsed = parse_email(data)
841
+
842
+ if validate:
843
+ exceptions: list[Exception] = []
844
+ for unparsed_key in unparsed:
845
+ if unparsed_key in _EMAIL_TO_RAW_MAPPING:
846
+ message = f"{unparsed_key!r} has invalid data"
847
+ else:
848
+ message = f"unrecognized field: {unparsed_key!r}"
849
+ exceptions.append(InvalidMetadata(unparsed_key, message))
850
+
851
+ if exceptions:
852
+ raise ExceptionGroup("unparsed", exceptions)
853
+
854
+ try:
855
+ return cls.from_raw(raw, validate=validate)
856
+ except ExceptionGroup as exc_group:
857
+ raise ExceptionGroup(
858
+ "invalid or unparsed metadata", exc_group.exceptions
859
+ ) from None
860
+
861
+ metadata_version: _Validator[_MetadataVersion] = _Validator()
862
+ """:external:ref:`core-metadata-metadata-version`
863
+ (required; validated to be a valid metadata version)"""
864
+ # `name` is not normalized/typed to NormalizedName so as to provide access to
865
+ # the original/raw name.
866
+ name: _Validator[str] = _Validator()
867
+ """:external:ref:`core-metadata-name`
868
+ (required; validated using :func:`~packaging.utils.canonicalize_name` and its
869
+ *validate* parameter)"""
870
+ version: _Validator[version_module.Version] = _Validator()
871
+ """:external:ref:`core-metadata-version` (required)"""
872
+ dynamic: _Validator[list[str] | None] = _Validator(
873
+ added="2.2",
874
+ )
875
+ """:external:ref:`core-metadata-dynamic`
876
+ (validated against core metadata field names and lowercased)"""
877
+ platforms: _Validator[list[str] | None] = _Validator()
878
+ """:external:ref:`core-metadata-platform`"""
879
+ supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1")
880
+ """:external:ref:`core-metadata-supported-platform`"""
881
+ summary: _Validator[str | None] = _Validator()
882
+ """:external:ref:`core-metadata-summary` (validated to contain no newlines)"""
883
+ description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body
884
+ """:external:ref:`core-metadata-description`"""
885
+ description_content_type: _Validator[str | None] = _Validator(added="2.1")
886
+ """:external:ref:`core-metadata-description-content-type` (validated)"""
887
+ keywords: _Validator[list[str] | None] = _Validator()
888
+ """:external:ref:`core-metadata-keywords`"""
889
+ home_page: _Validator[str | None] = _Validator()
890
+ """:external:ref:`core-metadata-home-page`"""
891
+ download_url: _Validator[str | None] = _Validator(added="1.1")
892
+ """:external:ref:`core-metadata-download-url`"""
893
+ author: _Validator[str | None] = _Validator()
894
+ """:external:ref:`core-metadata-author`"""
895
+ author_email: _Validator[str | None] = _Validator()
896
+ """:external:ref:`core-metadata-author-email`"""
897
+ maintainer: _Validator[str | None] = _Validator(added="1.2")
898
+ """:external:ref:`core-metadata-maintainer`"""
899
+ maintainer_email: _Validator[str | None] = _Validator(added="1.2")
900
+ """:external:ref:`core-metadata-maintainer-email`"""
901
+ license: _Validator[str | None] = _Validator()
902
+ """:external:ref:`core-metadata-license`"""
903
+ license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator(
904
+ added="2.4"
905
+ )
906
+ """:external:ref:`core-metadata-license-expression`"""
907
+ license_files: _Validator[list[str] | None] = _Validator(added="2.4")
908
+ """:external:ref:`core-metadata-license-file`"""
909
+ classifiers: _Validator[list[str] | None] = _Validator(added="1.1")
910
+ """:external:ref:`core-metadata-classifier`"""
911
+ requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator(
912
+ added="1.2"
913
+ )
914
+ """:external:ref:`core-metadata-requires-dist`"""
915
+ requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator(
916
+ added="1.2"
917
+ )
918
+ """:external:ref:`core-metadata-requires-python`"""
919
+ # Because `Requires-External` allows for non-PEP 440 version specifiers, we
920
+ # don't do any processing on the values.
921
+ requires_external: _Validator[list[str] | None] = _Validator(added="1.2")
922
+ """:external:ref:`core-metadata-requires-external`"""
923
+ project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2")
924
+ """:external:ref:`core-metadata-project-url`"""
925
+ # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation
926
+ # regardless of metadata version.
927
+ provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator(
928
+ added="2.1",
929
+ )
930
+ """:external:ref:`core-metadata-provides-extra`"""
931
+ provides_dist: _Validator[list[str] | None] = _Validator(added="1.2")
932
+ """:external:ref:`core-metadata-provides-dist`"""
933
+ obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2")
934
+ """:external:ref:`core-metadata-obsoletes-dist`"""
935
+ import_names: _Validator[list[str] | None] = _Validator(added="2.5")
936
+ """:external:ref:`core-metadata-import-name`"""
937
+ import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5")
938
+ """:external:ref:`core-metadata-import-namespace`"""
939
+ requires: _Validator[list[str] | None] = _Validator(added="1.1")
940
+ """``Requires`` (deprecated)"""
941
+ provides: _Validator[list[str] | None] = _Validator(added="1.1")
942
+ """``Provides`` (deprecated)"""
943
+ obsoletes: _Validator[list[str] | None] = _Validator(added="1.1")
944
+ """``Obsoletes`` (deprecated)"""
945
+
946
+ def as_rfc822(self) -> RFC822Message:
947
+ """
948
+ Return an RFC822 message with the metadata.
949
+ """
950
+ message = RFC822Message()
951
+ self._write_metadata(message)
952
+ return message
953
+
954
+ def _write_metadata(self, message: RFC822Message) -> None:
955
+ """
956
+ Return an RFC822 message with the metadata.
957
+ """
958
+ for name, validator in self.__class__.__dict__.items():
959
+ if isinstance(validator, _Validator) and name != "description":
960
+ value = getattr(self, name)
961
+ email_name = _RAW_TO_EMAIL_MAPPING[name]
962
+ if value is not None:
963
+ if email_name == "project-url":
964
+ for label, url in value.items():
965
+ message[email_name] = f"{label}, {url}"
966
+ elif email_name == "keywords":
967
+ message[email_name] = ",".join(value)
968
+ elif email_name == "import-name" and value == []:
969
+ message[email_name] = ""
970
+ elif isinstance(value, list):
971
+ for item in value:
972
+ message[email_name] = str(item)
973
+ else:
974
+ message[email_name] = str(value)
975
+
976
+ # The description is a special case because it is in the body of the message.
977
+ if self.description is not None:
978
+ message.set_payload(self.description)
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/py.typed ADDED
File without changes
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/pylock.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import logging
5
+ import re
6
+ from collections.abc import Mapping, Sequence
7
+ from dataclasses import dataclass
8
+ from datetime import datetime
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Callable,
13
+ Protocol,
14
+ TypeVar,
15
+ )
16
+
17
+ from .markers import Marker
18
+ from .specifiers import SpecifierSet
19
+ from .utils import NormalizedName, is_normalized_name
20
+ from .version import Version
21
+
22
+ if TYPE_CHECKING: # pragma: no cover
23
+ from pathlib import Path
24
+
25
+ from typing_extensions import Self
26
+
27
+ _logger = logging.getLogger(__name__)
28
+
29
+ __all__ = [
30
+ "Package",
31
+ "PackageArchive",
32
+ "PackageDirectory",
33
+ "PackageSdist",
34
+ "PackageVcs",
35
+ "PackageWheel",
36
+ "Pylock",
37
+ "PylockUnsupportedVersionError",
38
+ "PylockValidationError",
39
+ "is_valid_pylock_path",
40
+ ]
41
+
42
+ _T = TypeVar("_T")
43
+ _T2 = TypeVar("_T2")
44
+
45
+
46
+ class _FromMappingProtocol(Protocol): # pragma: no cover
47
+ @classmethod
48
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
49
+
50
+
51
+ _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
52
+
53
+
54
+ _PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$")
55
+
56
+
57
+ def is_valid_pylock_path(path: Path) -> bool:
58
+ """Check if the given path is a valid pylock file path."""
59
+ return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))
60
+
61
+
62
+ def _toml_key(key: str) -> str:
63
+ return key.replace("_", "-")
64
+
65
+
66
+ def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401
67
+ if isinstance(value, (Version, Marker, SpecifierSet)):
68
+ return str(value)
69
+ if isinstance(value, Sequence) and key == "environments":
70
+ return [str(v) for v in value]
71
+ return value
72
+
73
+
74
+ def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:
75
+ return {
76
+ _toml_key(key): _toml_value(key, value)
77
+ for key, value in data
78
+ if value is not None
79
+ }
80
+
81
+
82
+ def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:
83
+ """Get a value from the dictionary and verify it's the expected type."""
84
+ if (value := d.get(key)) is None:
85
+ return None
86
+ if not isinstance(value, expected_type):
87
+ raise PylockValidationError(
88
+ f"Unexpected type {type(value).__name__} "
89
+ f"(expected {expected_type.__name__})",
90
+ context=key,
91
+ )
92
+ return value
93
+
94
+
95
+ def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:
96
+ """Get a required value from the dictionary and verify it's the expected type."""
97
+ if (value := _get(d, expected_type, key)) is None:
98
+ raise _PylockRequiredKeyError(key)
99
+ return value
100
+
101
+
102
+ def _get_sequence(
103
+ d: Mapping[str, Any], expected_item_type: type[_T], key: str
104
+ ) -> Sequence[_T] | None:
105
+ """Get a list value from the dictionary and verify it's the expected items type."""
106
+ if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract]
107
+ return None
108
+ if isinstance(value, (str, bytes)):
109
+ # special case: str and bytes are Sequences, but we want to reject it
110
+ raise PylockValidationError(
111
+ f"Unexpected type {type(value).__name__} (expected Sequence)",
112
+ context=key,
113
+ )
114
+ for i, item in enumerate(value):
115
+ if not isinstance(item, expected_item_type):
116
+ raise PylockValidationError(
117
+ f"Unexpected type {type(item).__name__} "
118
+ f"(expected {expected_item_type.__name__})",
119
+ context=f"{key}[{i}]",
120
+ )
121
+ return value
122
+
123
+
124
+ def _get_as(
125
+ d: Mapping[str, Any],
126
+ expected_type: type[_T],
127
+ target_type: Callable[[_T], _T2],
128
+ key: str,
129
+ ) -> _T2 | None:
130
+ """Get a value from the dictionary, verify it's the expected type,
131
+ and convert to the target type.
132
+
133
+ This assumes the target_type constructor accepts the value.
134
+ """
135
+ if (value := _get(d, expected_type, key)) is None:
136
+ return None
137
+ try:
138
+ return target_type(value)
139
+ except Exception as e:
140
+ raise PylockValidationError(e, context=key) from e
141
+
142
+
143
+ def _get_required_as(
144
+ d: Mapping[str, Any],
145
+ expected_type: type[_T],
146
+ target_type: Callable[[_T], _T2],
147
+ key: str,
148
+ ) -> _T2:
149
+ """Get a required value from the dict, verify it's the expected type,
150
+ and convert to the target type."""
151
+ if (value := _get_as(d, expected_type, target_type, key)) is None:
152
+ raise _PylockRequiredKeyError(key)
153
+ return value
154
+
155
+
156
+ def _get_sequence_as(
157
+ d: Mapping[str, Any],
158
+ expected_item_type: type[_T],
159
+ target_item_type: Callable[[_T], _T2],
160
+ key: str,
161
+ ) -> list[_T2] | None:
162
+ """Get list value from dictionary and verify expected items type."""
163
+ if (value := _get_sequence(d, expected_item_type, key)) is None:
164
+ return None
165
+ result = []
166
+ try:
167
+ for item in value:
168
+ typed_item = target_item_type(item)
169
+ result.append(typed_item)
170
+ except Exception as e:
171
+ raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
172
+ return result
173
+
174
+
175
+ def _get_object(
176
+ d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str
177
+ ) -> _FromMappingProtocolT | None:
178
+ """Get a dictionary value from the dictionary and convert it to a dataclass."""
179
+ if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract]
180
+ return None
181
+ try:
182
+ return target_type._from_dict(value)
183
+ except Exception as e:
184
+ raise PylockValidationError(e, context=key) from e
185
+
186
+
187
+ def _get_sequence_of_objects(
188
+ d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
189
+ ) -> list[_FromMappingProtocolT] | None:
190
+ """Get a list value from the dictionary and convert its items to a dataclass."""
191
+ if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract]
192
+ return None
193
+ result: list[_FromMappingProtocolT] = []
194
+ try:
195
+ for item in value:
196
+ typed_item = target_item_type._from_dict(item)
197
+ result.append(typed_item)
198
+ except Exception as e:
199
+ raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
200
+ return result
201
+
202
+
203
+ def _get_required_sequence_of_objects(
204
+ d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
205
+ ) -> Sequence[_FromMappingProtocolT]:
206
+ """Get a required list value from the dictionary and convert its items to a
207
+ dataclass."""
208
+ if (result := _get_sequence_of_objects(d, target_item_type, key)) is None:
209
+ raise _PylockRequiredKeyError(key)
210
+ return result
211
+
212
+
213
+ def _validate_normalized_name(name: str) -> NormalizedName:
214
+ """Validate that a string is a NormalizedName."""
215
+ if not is_normalized_name(name):
216
+ raise PylockValidationError(f"Name {name!r} is not normalized")
217
+ return NormalizedName(name)
218
+
219
+
220
+ def _validate_path_url(path: str | None, url: str | None) -> None:
221
+ if not path and not url:
222
+ raise PylockValidationError("path or url must be provided")
223
+
224
+
225
+ def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]:
226
+ if not hashes:
227
+ raise PylockValidationError("At least one hash must be provided")
228
+ if not all(isinstance(hash_val, str) for hash_val in hashes.values()):
229
+ raise PylockValidationError("Hash values must be strings")
230
+ return hashes
231
+
232
+
233
+ class PylockValidationError(Exception):
234
+ """Raised when when input data is not spec-compliant."""
235
+
236
+ context: str | None = None
237
+ message: str
238
+
239
+ def __init__(
240
+ self,
241
+ cause: str | Exception,
242
+ *,
243
+ context: str | None = None,
244
+ ) -> None:
245
+ if isinstance(cause, PylockValidationError):
246
+ if cause.context:
247
+ self.context = (
248
+ f"{context}.{cause.context}" if context else cause.context
249
+ )
250
+ else:
251
+ self.context = context
252
+ self.message = cause.message
253
+ else:
254
+ self.context = context
255
+ self.message = str(cause)
256
+
257
+ def __str__(self) -> str:
258
+ if self.context:
259
+ return f"{self.message} in {self.context!r}"
260
+ return self.message
261
+
262
+
263
+ class _PylockRequiredKeyError(PylockValidationError):
264
+ def __init__(self, key: str) -> None:
265
+ super().__init__("Missing required value", context=key)
266
+
267
+
268
+ class PylockUnsupportedVersionError(PylockValidationError):
269
+ """Raised when encountering an unsupported `lock_version`."""
270
+
271
+
272
+ @dataclass(frozen=True, init=False)
273
+ class PackageVcs:
274
+ type: str
275
+ url: str | None = None
276
+ path: str | None = None
277
+ requested_revision: str | None = None
278
+ commit_id: str # type: ignore[misc]
279
+ subdirectory: str | None = None
280
+
281
+ def __init__(
282
+ self,
283
+ *,
284
+ type: str,
285
+ url: str | None = None,
286
+ path: str | None = None,
287
+ requested_revision: str | None = None,
288
+ commit_id: str,
289
+ subdirectory: str | None = None,
290
+ ) -> None:
291
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
292
+ object.__setattr__(self, "type", type)
293
+ object.__setattr__(self, "url", url)
294
+ object.__setattr__(self, "path", path)
295
+ object.__setattr__(self, "requested_revision", requested_revision)
296
+ object.__setattr__(self, "commit_id", commit_id)
297
+ object.__setattr__(self, "subdirectory", subdirectory)
298
+
299
+ @classmethod
300
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
301
+ package_vcs = cls(
302
+ type=_get_required(d, str, "type"),
303
+ url=_get(d, str, "url"),
304
+ path=_get(d, str, "path"),
305
+ requested_revision=_get(d, str, "requested-revision"),
306
+ commit_id=_get_required(d, str, "commit-id"),
307
+ subdirectory=_get(d, str, "subdirectory"),
308
+ )
309
+ _validate_path_url(package_vcs.path, package_vcs.url)
310
+ return package_vcs
311
+
312
+
313
+ @dataclass(frozen=True, init=False)
314
+ class PackageDirectory:
315
+ path: str
316
+ editable: bool | None = None
317
+ subdirectory: str | None = None
318
+
319
+ def __init__(
320
+ self,
321
+ *,
322
+ path: str,
323
+ editable: bool | None = None,
324
+ subdirectory: str | None = None,
325
+ ) -> None:
326
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
327
+ object.__setattr__(self, "path", path)
328
+ object.__setattr__(self, "editable", editable)
329
+ object.__setattr__(self, "subdirectory", subdirectory)
330
+
331
+ @classmethod
332
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
333
+ return cls(
334
+ path=_get_required(d, str, "path"),
335
+ editable=_get(d, bool, "editable"),
336
+ subdirectory=_get(d, str, "subdirectory"),
337
+ )
338
+
339
+
340
+ @dataclass(frozen=True, init=False)
341
+ class PackageArchive:
342
+ url: str | None = None
343
+ path: str | None = None
344
+ size: int | None = None
345
+ upload_time: datetime | None = None
346
+ hashes: Mapping[str, str] # type: ignore[misc]
347
+ subdirectory: str | None = None
348
+
349
+ def __init__(
350
+ self,
351
+ *,
352
+ url: str | None = None,
353
+ path: str | None = None,
354
+ size: int | None = None,
355
+ upload_time: datetime | None = None,
356
+ hashes: Mapping[str, str],
357
+ subdirectory: str | None = None,
358
+ ) -> None:
359
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
360
+ object.__setattr__(self, "url", url)
361
+ object.__setattr__(self, "path", path)
362
+ object.__setattr__(self, "size", size)
363
+ object.__setattr__(self, "upload_time", upload_time)
364
+ object.__setattr__(self, "hashes", hashes)
365
+ object.__setattr__(self, "subdirectory", subdirectory)
366
+
367
+ @classmethod
368
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
369
+ package_archive = cls(
370
+ url=_get(d, str, "url"),
371
+ path=_get(d, str, "path"),
372
+ size=_get(d, int, "size"),
373
+ upload_time=_get(d, datetime, "upload-time"),
374
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
375
+ subdirectory=_get(d, str, "subdirectory"),
376
+ )
377
+ _validate_path_url(package_archive.path, package_archive.url)
378
+ return package_archive
379
+
380
+
381
+ @dataclass(frozen=True, init=False)
382
+ class PackageSdist:
383
+ name: str | None = None
384
+ upload_time: datetime | None = None
385
+ url: str | None = None
386
+ path: str | None = None
387
+ size: int | None = None
388
+ hashes: Mapping[str, str] # type: ignore[misc]
389
+
390
+ def __init__(
391
+ self,
392
+ *,
393
+ name: str | None = None,
394
+ upload_time: datetime | None = None,
395
+ url: str | None = None,
396
+ path: str | None = None,
397
+ size: int | None = None,
398
+ hashes: Mapping[str, str],
399
+ ) -> None:
400
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
401
+ object.__setattr__(self, "name", name)
402
+ object.__setattr__(self, "upload_time", upload_time)
403
+ object.__setattr__(self, "url", url)
404
+ object.__setattr__(self, "path", path)
405
+ object.__setattr__(self, "size", size)
406
+ object.__setattr__(self, "hashes", hashes)
407
+
408
+ @classmethod
409
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
410
+ package_sdist = cls(
411
+ name=_get(d, str, "name"),
412
+ upload_time=_get(d, datetime, "upload-time"),
413
+ url=_get(d, str, "url"),
414
+ path=_get(d, str, "path"),
415
+ size=_get(d, int, "size"),
416
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
417
+ )
418
+ _validate_path_url(package_sdist.path, package_sdist.url)
419
+ return package_sdist
420
+
421
+
422
+ @dataclass(frozen=True, init=False)
423
+ class PackageWheel:
424
+ name: str | None = None
425
+ upload_time: datetime | None = None
426
+ url: str | None = None
427
+ path: str | None = None
428
+ size: int | None = None
429
+ hashes: Mapping[str, str] # type: ignore[misc]
430
+
431
+ def __init__(
432
+ self,
433
+ *,
434
+ name: str | None = None,
435
+ upload_time: datetime | None = None,
436
+ url: str | None = None,
437
+ path: str | None = None,
438
+ size: int | None = None,
439
+ hashes: Mapping[str, str],
440
+ ) -> None:
441
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
442
+ object.__setattr__(self, "name", name)
443
+ object.__setattr__(self, "upload_time", upload_time)
444
+ object.__setattr__(self, "url", url)
445
+ object.__setattr__(self, "path", path)
446
+ object.__setattr__(self, "size", size)
447
+ object.__setattr__(self, "hashes", hashes)
448
+
449
+ @classmethod
450
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
451
+ package_wheel = cls(
452
+ name=_get(d, str, "name"),
453
+ upload_time=_get(d, datetime, "upload-time"),
454
+ url=_get(d, str, "url"),
455
+ path=_get(d, str, "path"),
456
+ size=_get(d, int, "size"),
457
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
458
+ )
459
+ _validate_path_url(package_wheel.path, package_wheel.url)
460
+ return package_wheel
461
+
462
+
463
+ @dataclass(frozen=True, init=False)
464
+ class Package:
465
+ name: NormalizedName
466
+ version: Version | None = None
467
+ marker: Marker | None = None
468
+ requires_python: SpecifierSet | None = None
469
+ dependencies: Sequence[Mapping[str, Any]] | None = None
470
+ vcs: PackageVcs | None = None
471
+ directory: PackageDirectory | None = None
472
+ archive: PackageArchive | None = None
473
+ index: str | None = None
474
+ sdist: PackageSdist | None = None
475
+ wheels: Sequence[PackageWheel] | None = None
476
+ attestation_identities: Sequence[Mapping[str, Any]] | None = None
477
+ tool: Mapping[str, Any] | None = None
478
+
479
+ def __init__(
480
+ self,
481
+ *,
482
+ name: NormalizedName,
483
+ version: Version | None = None,
484
+ marker: Marker | None = None,
485
+ requires_python: SpecifierSet | None = None,
486
+ dependencies: Sequence[Mapping[str, Any]] | None = None,
487
+ vcs: PackageVcs | None = None,
488
+ directory: PackageDirectory | None = None,
489
+ archive: PackageArchive | None = None,
490
+ index: str | None = None,
491
+ sdist: PackageSdist | None = None,
492
+ wheels: Sequence[PackageWheel] | None = None,
493
+ attestation_identities: Sequence[Mapping[str, Any]] | None = None,
494
+ tool: Mapping[str, Any] | None = None,
495
+ ) -> None:
496
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
497
+ object.__setattr__(self, "name", name)
498
+ object.__setattr__(self, "version", version)
499
+ object.__setattr__(self, "marker", marker)
500
+ object.__setattr__(self, "requires_python", requires_python)
501
+ object.__setattr__(self, "dependencies", dependencies)
502
+ object.__setattr__(self, "vcs", vcs)
503
+ object.__setattr__(self, "directory", directory)
504
+ object.__setattr__(self, "archive", archive)
505
+ object.__setattr__(self, "index", index)
506
+ object.__setattr__(self, "sdist", sdist)
507
+ object.__setattr__(self, "wheels", wheels)
508
+ object.__setattr__(self, "attestation_identities", attestation_identities)
509
+ object.__setattr__(self, "tool", tool)
510
+
511
+ @classmethod
512
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
513
+ package = cls(
514
+ name=_get_required_as(d, str, _validate_normalized_name, "name"),
515
+ version=_get_as(d, str, Version, "version"),
516
+ requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
517
+ dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract]
518
+ marker=_get_as(d, str, Marker, "marker"),
519
+ vcs=_get_object(d, PackageVcs, "vcs"),
520
+ directory=_get_object(d, PackageDirectory, "directory"),
521
+ archive=_get_object(d, PackageArchive, "archive"),
522
+ index=_get(d, str, "index"),
523
+ sdist=_get_object(d, PackageSdist, "sdist"),
524
+ wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"),
525
+ attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract]
526
+ tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract]
527
+ )
528
+ distributions = bool(package.sdist) + len(package.wheels or [])
529
+ direct_urls = (
530
+ bool(package.vcs) + bool(package.directory) + bool(package.archive)
531
+ )
532
+ if distributions > 0 and direct_urls > 0:
533
+ raise PylockValidationError(
534
+ "None of vcs, directory, archive must be set if sdist or wheels are set"
535
+ )
536
+ if distributions == 0 and direct_urls != 1:
537
+ raise PylockValidationError(
538
+ "Exactly one of vcs, directory, archive must be set "
539
+ "if sdist and wheels are not set"
540
+ )
541
+ try:
542
+ for i, attestation_identity in enumerate( # noqa: B007
543
+ package.attestation_identities or []
544
+ ):
545
+ _get_required(attestation_identity, str, "kind")
546
+ except Exception as e:
547
+ raise PylockValidationError(
548
+ e, context=f"attestation-identities[{i}]"
549
+ ) from e
550
+ return package
551
+
552
+ @property
553
+ def is_direct(self) -> bool:
554
+ return not (self.sdist or self.wheels)
555
+
556
+
557
+ @dataclass(frozen=True, init=False)
558
+ class Pylock:
559
+ """A class representing a pylock file."""
560
+
561
+ lock_version: Version
562
+ environments: Sequence[Marker] | None = None
563
+ requires_python: SpecifierSet | None = None
564
+ extras: Sequence[NormalizedName] | None = None
565
+ dependency_groups: Sequence[str] | None = None
566
+ default_groups: Sequence[str] | None = None
567
+ created_by: str # type: ignore[misc]
568
+ packages: Sequence[Package] # type: ignore[misc]
569
+ tool: Mapping[str, Any] | None = None
570
+
571
+ def __init__(
572
+ self,
573
+ *,
574
+ lock_version: Version,
575
+ environments: Sequence[Marker] | None = None,
576
+ requires_python: SpecifierSet | None = None,
577
+ extras: Sequence[NormalizedName] | None = None,
578
+ dependency_groups: Sequence[str] | None = None,
579
+ default_groups: Sequence[str] | None = None,
580
+ created_by: str,
581
+ packages: Sequence[Package],
582
+ tool: Mapping[str, Any] | None = None,
583
+ ) -> None:
584
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
585
+ object.__setattr__(self, "lock_version", lock_version)
586
+ object.__setattr__(self, "environments", environments)
587
+ object.__setattr__(self, "requires_python", requires_python)
588
+ object.__setattr__(self, "extras", extras)
589
+ object.__setattr__(self, "dependency_groups", dependency_groups)
590
+ object.__setattr__(self, "default_groups", default_groups)
591
+ object.__setattr__(self, "created_by", created_by)
592
+ object.__setattr__(self, "packages", packages)
593
+ object.__setattr__(self, "tool", tool)
594
+
595
+ @classmethod
596
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
597
+ pylock = cls(
598
+ lock_version=_get_required_as(d, str, Version, "lock-version"),
599
+ environments=_get_sequence_as(d, str, Marker, "environments"),
600
+ extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"),
601
+ dependency_groups=_get_sequence(d, str, "dependency-groups"),
602
+ default_groups=_get_sequence(d, str, "default-groups"),
603
+ created_by=_get_required(d, str, "created-by"),
604
+ requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
605
+ packages=_get_required_sequence_of_objects(d, Package, "packages"),
606
+ tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract]
607
+ )
608
+ if not Version("1") <= pylock.lock_version < Version("2"):
609
+ raise PylockUnsupportedVersionError(
610
+ f"pylock version {pylock.lock_version} is not supported"
611
+ )
612
+ if pylock.lock_version > Version("1.0"):
613
+ _logger.warning(
614
+ "pylock minor version %s is not supported", pylock.lock_version
615
+ )
616
+ return pylock
617
+
618
+ @classmethod
619
+ def from_dict(cls, d: Mapping[str, Any], /) -> Self:
620
+ """Create and validate a Pylock instance from a TOML dictionary.
621
+
622
+ Raises :class:`PylockValidationError` if the input data is not
623
+ spec-compliant.
624
+ """
625
+ return cls._from_dict(d)
626
+
627
+ def to_dict(self) -> Mapping[str, Any]:
628
+ """Convert the Pylock instance to a TOML dictionary."""
629
+ return dataclasses.asdict(self, dict_factory=_toml_dict_factory)
630
+
631
+ def validate(self) -> None:
632
+ """Validate the Pylock instance against the specification.
633
+
634
+ Raises :class:`PylockValidationError` otherwise."""
635
+ self.from_dict(self.to_dict())
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/requirements.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+ from __future__ import annotations
5
+
6
+ from typing import Iterator
7
+
8
+ from ._parser import parse_requirement as _parse_requirement
9
+ from ._tokenizer import ParserSyntaxError
10
+ from .markers import Marker, _normalize_extra_values
11
+ from .specifiers import SpecifierSet
12
+ from .utils import canonicalize_name
13
+
14
+
15
+ class InvalidRequirement(ValueError):
16
+ """
17
+ An invalid requirement was found, users should refer to PEP 508.
18
+ """
19
+
20
+
21
+ class Requirement:
22
+ """Parse a requirement.
23
+
24
+ Parse a given requirement string into its parts, such as name, specifier,
25
+ URL, and extras. Raises InvalidRequirement on a badly-formed requirement
26
+ string.
27
+ """
28
+
29
+ # TODO: Can we test whether something is contained within a requirement?
30
+ # If so how do we do that? Do we need to test against the _name_ of
31
+ # the thing as well as the version? What about the markers?
32
+ # TODO: Can we normalize the name and extra name?
33
+
34
+ def __init__(self, requirement_string: str) -> None:
35
+ try:
36
+ parsed = _parse_requirement(requirement_string)
37
+ except ParserSyntaxError as e:
38
+ raise InvalidRequirement(str(e)) from e
39
+
40
+ self.name: str = parsed.name
41
+ self.url: str | None = parsed.url or None
42
+ self.extras: set[str] = set(parsed.extras or [])
43
+ self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
44
+ self.marker: Marker | None = None
45
+ if parsed.marker is not None:
46
+ self.marker = Marker.__new__(Marker)
47
+ self.marker._markers = _normalize_extra_values(parsed.marker)
48
+
49
+ def _iter_parts(self, name: str) -> Iterator[str]:
50
+ yield name
51
+
52
+ if self.extras:
53
+ formatted_extras = ",".join(sorted(self.extras))
54
+ yield f"[{formatted_extras}]"
55
+
56
+ if self.specifier:
57
+ yield str(self.specifier)
58
+
59
+ if self.url:
60
+ yield f" @ {self.url}"
61
+ if self.marker:
62
+ yield " "
63
+
64
+ if self.marker:
65
+ yield f"; {self.marker}"
66
+
67
+ def __str__(self) -> str:
68
+ return "".join(self._iter_parts(self.name))
69
+
70
+ def __repr__(self) -> str:
71
+ return f"<{self.__class__.__name__}('{self}')>"
72
+
73
+ def __hash__(self) -> int:
74
+ return hash(tuple(self._iter_parts(canonicalize_name(self.name))))
75
+
76
+ def __eq__(self, other: object) -> bool:
77
+ if not isinstance(other, Requirement):
78
+ return NotImplemented
79
+
80
+ return (
81
+ canonicalize_name(self.name) == canonicalize_name(other.name)
82
+ and self.extras == other.extras
83
+ and self.specifier == other.specifier
84
+ and self.url == other.url
85
+ and self.marker == other.marker
86
+ )
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/specifiers.py ADDED
@@ -0,0 +1,1068 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+ """
5
+ .. testsetup::
6
+
7
+ from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier
8
+ from packaging.version import Version
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import abc
14
+ import itertools
15
+ import re
16
+ from typing import Callable, Final, Iterable, Iterator, TypeVar, Union
17
+
18
+ from .utils import canonicalize_version
19
+ from .version import InvalidVersion, Version
20
+
21
+ UnparsedVersion = Union[Version, str]
22
+ UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
23
+ CallableOperator = Callable[[Version, str], bool]
24
+
25
+
26
+ def _coerce_version(version: UnparsedVersion) -> Version | None:
27
+ if not isinstance(version, Version):
28
+ try:
29
+ version = Version(version)
30
+ except InvalidVersion:
31
+ return None
32
+ return version
33
+
34
+
35
+ def _public_version(version: Version) -> Version:
36
+ return version.__replace__(local=None)
37
+
38
+
39
+ def _base_version(version: Version) -> Version:
40
+ return version.__replace__(pre=None, post=None, dev=None, local=None)
41
+
42
+
43
+ class InvalidSpecifier(ValueError):
44
+ """
45
+ Raised when attempting to create a :class:`Specifier` with a specifier
46
+ string that is invalid.
47
+
48
+ >>> Specifier("lolwat")
49
+ Traceback (most recent call last):
50
+ ...
51
+ packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
52
+ """
53
+
54
+
55
+ class BaseSpecifier(metaclass=abc.ABCMeta):
56
+ __slots__ = ()
57
+ __match_args__ = ("_str",)
58
+
59
+ @property
60
+ def _str(self) -> str:
61
+ """Internal property for match_args"""
62
+ return str(self)
63
+
64
+ @abc.abstractmethod
65
+ def __str__(self) -> str:
66
+ """
67
+ Returns the str representation of this Specifier-like object. This
68
+ should be representative of the Specifier itself.
69
+ """
70
+
71
+ @abc.abstractmethod
72
+ def __hash__(self) -> int:
73
+ """
74
+ Returns a hash value for this Specifier-like object.
75
+ """
76
+
77
+ @abc.abstractmethod
78
+ def __eq__(self, other: object) -> bool:
79
+ """
80
+ Returns a boolean representing whether or not the two Specifier-like
81
+ objects are equal.
82
+
83
+ :param other: The other object to check against.
84
+ """
85
+
86
+ @property
87
+ @abc.abstractmethod
88
+ def prereleases(self) -> bool | None:
89
+ """Whether or not pre-releases as a whole are allowed.
90
+
91
+ This can be set to either ``True`` or ``False`` to explicitly enable or disable
92
+ prereleases or it can be set to ``None`` (the default) to use default semantics.
93
+ """
94
+
95
+ @prereleases.setter # noqa: B027
96
+ def prereleases(self, value: bool) -> None:
97
+ """Setter for :attr:`prereleases`.
98
+
99
+ :param value: The value to set.
100
+ """
101
+
102
+ @abc.abstractmethod
103
+ def contains(self, item: str, prereleases: bool | None = None) -> bool:
104
+ """
105
+ Determines if the given item is contained within this specifier.
106
+ """
107
+
108
+ @abc.abstractmethod
109
+ def filter(
110
+ self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
111
+ ) -> Iterator[UnparsedVersionVar]:
112
+ """
113
+ Takes an iterable of items and filters them so that only items which
114
+ are contained within this specifier are allowed in it.
115
+ """
116
+
117
+
118
+ class Specifier(BaseSpecifier):
119
+ """This class abstracts handling of version specifiers.
120
+
121
+ .. tip::
122
+
123
+ It is generally not required to instantiate this manually. You should instead
124
+ prefer to work with :class:`SpecifierSet` instead, which can parse
125
+ comma-separated version specifiers (which is what package metadata contains).
126
+ """
127
+
128
+ __slots__ = ("_prereleases", "_spec", "_spec_version")
129
+
130
+ _operator_regex_str = r"""
131
+ (?P<operator>(~=|==|!=|<=|>=|<|>|===))
132
+ """
133
+ _version_regex_str = r"""
134
+ (?P<version>
135
+ (?:
136
+ # The identity operators allow for an escape hatch that will
137
+ # do an exact string match of the version you wish to install.
138
+ # This will not be parsed by PEP 440 and we cannot determine
139
+ # any semantic meaning from it. This operator is discouraged
140
+ # but included entirely as an escape hatch.
141
+ (?<====) # Only match for the identity operator
142
+ \s*
143
+ [^\s;)]* # The arbitrary version can be just about anything,
144
+ # we match everything except for whitespace, a
145
+ # semi-colon for marker support, and a closing paren
146
+ # since versions can be enclosed in them.
147
+ )
148
+ |
149
+ (?:
150
+ # The (non)equality operators allow for wild card and local
151
+ # versions to be specified so we have to define these two
152
+ # operators separately to enable that.
153
+ (?<===|!=) # Only match for equals and not equals
154
+
155
+ \s*
156
+ v?
157
+ (?:[0-9]+!)? # epoch
158
+ [0-9]+(?:\.[0-9]+)* # release
159
+
160
+ # You cannot use a wild card and a pre-release, post-release, a dev or
161
+ # local version together so group them with a | and make them optional.
162
+ (?:
163
+ \.\* # Wild card syntax of .*
164
+ |
165
+ (?: # pre release
166
+ [-_\.]?
167
+ (alpha|beta|preview|pre|a|b|c|rc)
168
+ [-_\.]?
169
+ [0-9]*
170
+ )?
171
+ (?: # post release
172
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
173
+ )?
174
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
175
+ (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
176
+ )?
177
+ )
178
+ |
179
+ (?:
180
+ # The compatible operator requires at least two digits in the
181
+ # release segment.
182
+ (?<=~=) # Only match for the compatible operator
183
+
184
+ \s*
185
+ v?
186
+ (?:[0-9]+!)? # epoch
187
+ [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *)
188
+ (?: # pre release
189
+ [-_\.]?
190
+ (alpha|beta|preview|pre|a|b|c|rc)
191
+ [-_\.]?
192
+ [0-9]*
193
+ )?
194
+ (?: # post release
195
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
196
+ )?
197
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
198
+ )
199
+ |
200
+ (?:
201
+ # All other operators only allow a sub set of what the
202
+ # (non)equality operators do. Specifically they do not allow
203
+ # local versions to be specified nor do they allow the prefix
204
+ # matching wild cards.
205
+ (?<!==|!=|~=) # We have special cases for these
206
+ # operators so we want to make sure they
207
+ # don't match here.
208
+
209
+ \s*
210
+ v?
211
+ (?:[0-9]+!)? # epoch
212
+ [0-9]+(?:\.[0-9]+)* # release
213
+ (?: # pre release
214
+ [-_\.]?
215
+ (alpha|beta|preview|pre|a|b|c|rc)
216
+ [-_\.]?
217
+ [0-9]*
218
+ )?
219
+ (?: # post release
220
+ (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
221
+ )?
222
+ (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
223
+ )
224
+ )
225
+ """
226
+
227
+ _regex = re.compile(
228
+ r"\s*" + _operator_regex_str + _version_regex_str + r"\s*",
229
+ re.VERBOSE | re.IGNORECASE,
230
+ )
231
+
232
+ _operators: Final = {
233
+ "~=": "compatible",
234
+ "==": "equal",
235
+ "!=": "not_equal",
236
+ "<=": "less_than_equal",
237
+ ">=": "greater_than_equal",
238
+ "<": "less_than",
239
+ ">": "greater_than",
240
+ "===": "arbitrary",
241
+ }
242
+
243
+ def __init__(self, spec: str = "", prereleases: bool | None = None) -> None:
244
+ """Initialize a Specifier instance.
245
+
246
+ :param spec:
247
+ The string representation of a specifier which will be parsed and
248
+ normalized before use.
249
+ :param prereleases:
250
+ This tells the specifier if it should accept prerelease versions if
251
+ applicable or not. The default of ``None`` will autodetect it from the
252
+ given specifiers.
253
+ :raises InvalidSpecifier:
254
+ If the given specifier is invalid (i.e. bad syntax).
255
+ """
256
+ match = self._regex.fullmatch(spec)
257
+ if not match:
258
+ raise InvalidSpecifier(f"Invalid specifier: {spec!r}")
259
+
260
+ self._spec: tuple[str, str] = (
261
+ match.group("operator").strip(),
262
+ match.group("version").strip(),
263
+ )
264
+
265
+ # Store whether or not this Specifier should accept prereleases
266
+ self._prereleases = prereleases
267
+
268
+ # Specifier version cache
269
+ self._spec_version: tuple[str, Version] | None = None
270
+
271
+ def _get_spec_version(self, version: str) -> Version | None:
272
+ """One element cache, as only one spec Version is needed per Specifier."""
273
+ if self._spec_version is not None and self._spec_version[0] == version:
274
+ return self._spec_version[1]
275
+
276
+ version_specifier = _coerce_version(version)
277
+ if version_specifier is None:
278
+ return None
279
+
280
+ self._spec_version = (version, version_specifier)
281
+ return version_specifier
282
+
283
+ def _require_spec_version(self, version: str) -> Version:
284
+ """Get spec version, asserting it's valid (not for === operator).
285
+
286
+ This method should only be called for operators where version
287
+ strings are guaranteed to be valid PEP 440 versions (not ===).
288
+ """
289
+ spec_version = self._get_spec_version(version)
290
+ assert spec_version is not None
291
+ return spec_version
292
+
293
+ @property
294
+ def prereleases(self) -> bool | None:
295
+ # If there is an explicit prereleases set for this, then we'll just
296
+ # blindly use that.
297
+ if self._prereleases is not None:
298
+ return self._prereleases
299
+
300
+ # Only the "!=" operator does not imply prereleases when
301
+ # the version in the specifier is a prerelease.
302
+ operator, version_str = self._spec
303
+ if operator != "!=":
304
+ # The == specifier with trailing .* cannot include prereleases
305
+ # e.g. "==1.0a1.*" is not valid.
306
+ if operator == "==" and version_str.endswith(".*"):
307
+ return False
308
+
309
+ # "===" can have arbitrary string versions, so we cannot parse
310
+ # those, we take prereleases as unknown (None) for those.
311
+ version = self._get_spec_version(version_str)
312
+ if version is None:
313
+ return None
314
+
315
+ # For all other operators, use the check if spec Version
316
+ # object implies pre-releases.
317
+ if version.is_prerelease:
318
+ return True
319
+
320
+ return False
321
+
322
+ @prereleases.setter
323
+ def prereleases(self, value: bool | None) -> None:
324
+ self._prereleases = value
325
+
326
+ @property
327
+ def operator(self) -> str:
328
+ """The operator of this specifier.
329
+
330
+ >>> Specifier("==1.2.3").operator
331
+ '=='
332
+ """
333
+ return self._spec[0]
334
+
335
+ @property
336
+ def version(self) -> str:
337
+ """The version of this specifier.
338
+
339
+ >>> Specifier("==1.2.3").version
340
+ '1.2.3'
341
+ """
342
+ return self._spec[1]
343
+
344
+ def __repr__(self) -> str:
345
+ """A representation of the Specifier that shows all internal state.
346
+
347
+ >>> Specifier('>=1.0.0')
348
+ <Specifier('>=1.0.0')>
349
+ >>> Specifier('>=1.0.0', prereleases=False)
350
+ <Specifier('>=1.0.0', prereleases=False)>
351
+ >>> Specifier('>=1.0.0', prereleases=True)
352
+ <Specifier('>=1.0.0', prereleases=True)>
353
+ """
354
+ pre = (
355
+ f", prereleases={self.prereleases!r}"
356
+ if self._prereleases is not None
357
+ else ""
358
+ )
359
+
360
+ return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
361
+
362
+ def __str__(self) -> str:
363
+ """A string representation of the Specifier that can be round-tripped.
364
+
365
+ >>> str(Specifier('>=1.0.0'))
366
+ '>=1.0.0'
367
+ >>> str(Specifier('>=1.0.0', prereleases=False))
368
+ '>=1.0.0'
369
+ """
370
+ return "{}{}".format(*self._spec)
371
+
372
+ @property
373
+ def _canonical_spec(self) -> tuple[str, str]:
374
+ operator, version = self._spec
375
+ if operator == "===" or version.endswith(".*"):
376
+ return operator, version
377
+
378
+ spec_version = self._require_spec_version(version)
379
+
380
+ canonical_version = canonicalize_version(
381
+ spec_version, strip_trailing_zero=(operator != "~=")
382
+ )
383
+
384
+ return operator, canonical_version
385
+
386
+ def __hash__(self) -> int:
387
+ return hash(self._canonical_spec)
388
+
389
+ def __eq__(self, other: object) -> bool:
390
+ """Whether or not the two Specifier-like objects are equal.
391
+
392
+ :param other: The other object to check against.
393
+
394
+ The value of :attr:`prereleases` is ignored.
395
+
396
+ >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0")
397
+ True
398
+ >>> (Specifier("==1.2.3", prereleases=False) ==
399
+ ... Specifier("==1.2.3", prereleases=True))
400
+ True
401
+ >>> Specifier("==1.2.3") == "==1.2.3"
402
+ True
403
+ >>> Specifier("==1.2.3") == Specifier("==1.2.4")
404
+ False
405
+ >>> Specifier("==1.2.3") == Specifier("~=1.2.3")
406
+ False
407
+ """
408
+ if isinstance(other, str):
409
+ try:
410
+ other = self.__class__(str(other))
411
+ except InvalidSpecifier:
412
+ return NotImplemented
413
+ elif not isinstance(other, self.__class__):
414
+ return NotImplemented
415
+
416
+ return self._canonical_spec == other._canonical_spec
417
+
418
+ def _get_operator(self, op: str) -> CallableOperator:
419
+ operator_callable: CallableOperator = getattr(
420
+ self, f"_compare_{self._operators[op]}"
421
+ )
422
+ return operator_callable
423
+
424
+ def _compare_compatible(self, prospective: Version, spec: str) -> bool:
425
+ # Compatible releases have an equivalent combination of >= and ==. That
426
+ # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
427
+ # implement this in terms of the other specifiers instead of
428
+ # implementing it ourselves. The only thing we need to do is construct
429
+ # the other specifiers.
430
+
431
+ # We want everything but the last item in the version, but we want to
432
+ # ignore suffix segments.
433
+ prefix = _version_join(
434
+ list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
435
+ )
436
+
437
+ # Add the prefix notation to the end of our string
438
+ prefix += ".*"
439
+
440
+ return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
441
+ prospective, prefix
442
+ )
443
+
444
+ def _compare_equal(self, prospective: Version, spec: str) -> bool:
445
+ # We need special logic to handle prefix matching
446
+ if spec.endswith(".*"):
447
+ # In the case of prefix matching we want to ignore local segment.
448
+ normalized_prospective = canonicalize_version(
449
+ _public_version(prospective), strip_trailing_zero=False
450
+ )
451
+ # Get the normalized version string ignoring the trailing .*
452
+ normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)
453
+ # Split the spec out by bangs and dots, and pretend that there is
454
+ # an implicit dot in between a release segment and a pre-release segment.
455
+ split_spec = _version_split(normalized_spec)
456
+
457
+ # Split the prospective version out by bangs and dots, and pretend
458
+ # that there is an implicit dot in between a release segment and
459
+ # a pre-release segment.
460
+ split_prospective = _version_split(normalized_prospective)
461
+
462
+ # 0-pad the prospective version before shortening it to get the correct
463
+ # shortened version.
464
+ padded_prospective, _ = _pad_version(split_prospective, split_spec)
465
+
466
+ # Shorten the prospective version to be the same length as the spec
467
+ # so that we can determine if the specifier is a prefix of the
468
+ # prospective version or not.
469
+ shortened_prospective = padded_prospective[: len(split_spec)]
470
+
471
+ return shortened_prospective == split_spec
472
+ else:
473
+ # Convert our spec string into a Version
474
+ spec_version = self._require_spec_version(spec)
475
+
476
+ # If the specifier does not have a local segment, then we want to
477
+ # act as if the prospective version also does not have a local
478
+ # segment.
479
+ if not spec_version.local:
480
+ prospective = _public_version(prospective)
481
+
482
+ return prospective == spec_version
483
+
484
+ def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
485
+ return not self._compare_equal(prospective, spec)
486
+
487
+ def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:
488
+ # NB: Local version identifiers are NOT permitted in the version
489
+ # specifier, so local version labels can be universally removed from
490
+ # the prospective version.
491
+ return _public_version(prospective) <= self._require_spec_version(spec)
492
+
493
+ def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:
494
+ # NB: Local version identifiers are NOT permitted in the version
495
+ # specifier, so local version labels can be universally removed from
496
+ # the prospective version.
497
+ return _public_version(prospective) >= self._require_spec_version(spec)
498
+
499
+ def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
500
+ # Convert our spec to a Version instance, since we'll want to work with
501
+ # it as a version.
502
+ spec = self._require_spec_version(spec_str)
503
+
504
+ # Check to see if the prospective version is less than the spec
505
+ # version. If it's not we can short circuit and just return False now
506
+ # instead of doing extra unneeded work.
507
+ if not prospective < spec:
508
+ return False
509
+
510
+ # This special case is here so that, unless the specifier itself
511
+ # includes is a pre-release version, that we do not accept pre-release
512
+ # versions for the version mentioned in the specifier (e.g. <3.1 should
513
+ # not match 3.1.dev0, but should match 3.0.dev0).
514
+ if (
515
+ not spec.is_prerelease
516
+ and prospective.is_prerelease
517
+ and _base_version(prospective) == _base_version(spec)
518
+ ):
519
+ return False
520
+
521
+ # If we've gotten to here, it means that prospective version is both
522
+ # less than the spec version *and* it's not a pre-release of the same
523
+ # version in the spec.
524
+ return True
525
+
526
+ def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
527
+ # Convert our spec to a Version instance, since we'll want to work with
528
+ # it as a version.
529
+ spec = self._require_spec_version(spec_str)
530
+
531
+ # Check to see if the prospective version is greater than the spec
532
+ # version. If it's not we can short circuit and just return False now
533
+ # instead of doing extra unneeded work.
534
+ if not prospective > spec:
535
+ return False
536
+
537
+ # This special case is here so that, unless the specifier itself
538
+ # includes is a post-release version, that we do not accept
539
+ # post-release versions for the version mentioned in the specifier
540
+ # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
541
+ if (
542
+ not spec.is_postrelease
543
+ and prospective.is_postrelease
544
+ and _base_version(prospective) == _base_version(spec)
545
+ ):
546
+ return False
547
+
548
+ # Ensure that we do not allow a local version of the version mentioned
549
+ # in the specifier, which is technically greater than, to match.
550
+ if prospective.local is not None and _base_version(
551
+ prospective
552
+ ) == _base_version(spec):
553
+ return False
554
+
555
+ # If we've gotten to here, it means that prospective version is both
556
+ # greater than the spec version *and* it's not a pre-release of the
557
+ # same version in the spec.
558
+ return True
559
+
560
+ def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool:
561
+ return str(prospective).lower() == str(spec).lower()
562
+
563
+ def __contains__(self, item: str | Version) -> bool:
564
+ """Return whether or not the item is contained in this specifier.
565
+
566
+ :param item: The item to check for.
567
+
568
+ This is used for the ``in`` operator and behaves the same as
569
+ :meth:`contains` with no ``prereleases`` argument passed.
570
+
571
+ >>> "1.2.3" in Specifier(">=1.2.3")
572
+ True
573
+ >>> Version("1.2.3") in Specifier(">=1.2.3")
574
+ True
575
+ >>> "1.0.0" in Specifier(">=1.2.3")
576
+ False
577
+ >>> "1.3.0a1" in Specifier(">=1.2.3")
578
+ True
579
+ >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
580
+ True
581
+ """
582
+ return self.contains(item)
583
+
584
+ def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool:
585
+ """Return whether or not the item is contained in this specifier.
586
+
587
+ :param item:
588
+ The item to check for, which can be a version string or a
589
+ :class:`Version` instance.
590
+ :param prereleases:
591
+ Whether or not to match prereleases with this Specifier. If set to
592
+ ``None`` (the default), it will follow the recommendation from
593
+ :pep:`440` and match prereleases, as there are no other versions.
594
+
595
+ >>> Specifier(">=1.2.3").contains("1.2.3")
596
+ True
597
+ >>> Specifier(">=1.2.3").contains(Version("1.2.3"))
598
+ True
599
+ >>> Specifier(">=1.2.3").contains("1.0.0")
600
+ False
601
+ >>> Specifier(">=1.2.3").contains("1.3.0a1")
602
+ True
603
+ >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1")
604
+ False
605
+ >>> Specifier(">=1.2.3").contains("1.3.0a1")
606
+ True
607
+ """
608
+
609
+ return bool(list(self.filter([item], prereleases=prereleases)))
610
+
611
+ def filter(
612
+ self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
613
+ ) -> Iterator[UnparsedVersionVar]:
614
+ """Filter items in the given iterable, that match the specifier.
615
+
616
+ :param iterable:
617
+ An iterable that can contain version strings and :class:`Version` instances.
618
+ The items in the iterable will be filtered according to the specifier.
619
+ :param prereleases:
620
+ Whether or not to allow prereleases in the returned iterator. If set to
621
+ ``None`` (the default), it will follow the recommendation from :pep:`440`
622
+ and match prereleases if there are no other versions.
623
+
624
+ >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
625
+ ['1.3']
626
+ >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")]))
627
+ ['1.2.3', '1.3', <Version('1.4')>]
628
+ >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"]))
629
+ ['1.5a1']
630
+ >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
631
+ ['1.3', '1.5a1']
632
+ >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
633
+ ['1.3', '1.5a1']
634
+ """
635
+ prereleases_versions = []
636
+ found_non_prereleases = False
637
+
638
+ # Determine if to include prereleases by default
639
+ include_prereleases = (
640
+ prereleases if prereleases is not None else self.prereleases
641
+ )
642
+
643
+ # Get the matching operator
644
+ operator_callable = self._get_operator(self.operator)
645
+
646
+ # Filter versions
647
+ for version in iterable:
648
+ parsed_version = _coerce_version(version)
649
+ if parsed_version is None:
650
+ # === operator can match arbitrary (non-version) strings
651
+ if self.operator == "===" and self._compare_arbitrary(
652
+ version, self.version
653
+ ):
654
+ yield version
655
+ elif operator_callable(parsed_version, self.version):
656
+ # If it's not a prerelease or prereleases are allowed, yield it directly
657
+ if not parsed_version.is_prerelease or include_prereleases:
658
+ found_non_prereleases = True
659
+ yield version
660
+ # Otherwise collect prereleases for potential later use
661
+ elif prereleases is None and self._prereleases is not False:
662
+ prereleases_versions.append(version)
663
+
664
+ # If no non-prereleases were found and prereleases weren't
665
+ # explicitly forbidden, yield the collected prereleases
666
+ if (
667
+ not found_non_prereleases
668
+ and prereleases is None
669
+ and self._prereleases is not False
670
+ ):
671
+ yield from prereleases_versions
672
+
673
+
674
+ _prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)")
675
+
676
+
677
+ def _version_split(version: str) -> list[str]:
678
+ """Split version into components.
679
+
680
+ The split components are intended for version comparison. The logic does
681
+ not attempt to retain the original version string, so joining the
682
+ components back with :func:`_version_join` may not produce the original
683
+ version string.
684
+ """
685
+ result: list[str] = []
686
+
687
+ epoch, _, rest = version.rpartition("!")
688
+ result.append(epoch or "0")
689
+
690
+ for item in rest.split("."):
691
+ match = _prefix_regex.fullmatch(item)
692
+ if match:
693
+ result.extend(match.groups())
694
+ else:
695
+ result.append(item)
696
+ return result
697
+
698
+
699
+ def _version_join(components: list[str]) -> str:
700
+ """Join split version components into a version string.
701
+
702
+ This function assumes the input came from :func:`_version_split`, where the
703
+ first component must be the epoch (either empty or numeric), and all other
704
+ components numeric.
705
+ """
706
+ epoch, *rest = components
707
+ return f"{epoch}!{'.'.join(rest)}"
708
+
709
+
710
+ def _is_not_suffix(segment: str) -> bool:
711
+ return not any(
712
+ segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
713
+ )
714
+
715
+
716
+ def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]:
717
+ left_split, right_split = [], []
718
+
719
+ # Get the release segment of our versions
720
+ left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
721
+ right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
722
+
723
+ # Get the rest of our versions
724
+ left_split.append(left[len(left_split[0]) :])
725
+ right_split.append(right[len(right_split[0]) :])
726
+
727
+ # Insert our padding
728
+ left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
729
+ right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
730
+
731
+ return (
732
+ list(itertools.chain.from_iterable(left_split)),
733
+ list(itertools.chain.from_iterable(right_split)),
734
+ )
735
+
736
+
737
+ class SpecifierSet(BaseSpecifier):
738
+ """This class abstracts handling of a set of version specifiers.
739
+
740
+ It can be passed a single specifier (``>=3.0``), a comma-separated list of
741
+ specifiers (``>=3.0,!=3.1``), or no specifier at all.
742
+ """
743
+
744
+ __slots__ = ("_prereleases", "_specs")
745
+
746
+ def __init__(
747
+ self,
748
+ specifiers: str | Iterable[Specifier] = "",
749
+ prereleases: bool | None = None,
750
+ ) -> None:
751
+ """Initialize a SpecifierSet instance.
752
+
753
+ :param specifiers:
754
+ The string representation of a specifier or a comma-separated list of
755
+ specifiers which will be parsed and normalized before use.
756
+ May also be an iterable of ``Specifier`` instances, which will be used
757
+ as is.
758
+ :param prereleases:
759
+ This tells the SpecifierSet if it should accept prerelease versions if
760
+ applicable or not. The default of ``None`` will autodetect it from the
761
+ given specifiers.
762
+
763
+ :raises InvalidSpecifier:
764
+ If the given ``specifiers`` are not parseable than this exception will be
765
+ raised.
766
+ """
767
+
768
+ if isinstance(specifiers, str):
769
+ # Split on `,` to break each individual specifier into its own item, and
770
+ # strip each item to remove leading/trailing whitespace.
771
+ split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
772
+
773
+ # Make each individual specifier a Specifier and save in a frozen set
774
+ # for later.
775
+ self._specs = frozenset(map(Specifier, split_specifiers))
776
+ else:
777
+ # Save the supplied specifiers in a frozen set.
778
+ self._specs = frozenset(specifiers)
779
+
780
+ # Store our prereleases value so we can use it later to determine if
781
+ # we accept prereleases or not.
782
+ self._prereleases = prereleases
783
+
784
+ @property
785
+ def prereleases(self) -> bool | None:
786
+ # If we have been given an explicit prerelease modifier, then we'll
787
+ # pass that through here.
788
+ if self._prereleases is not None:
789
+ return self._prereleases
790
+
791
+ # If we don't have any specifiers, and we don't have a forced value,
792
+ # then we'll just return None since we don't know if this should have
793
+ # pre-releases or not.
794
+ if not self._specs:
795
+ return None
796
+
797
+ # Otherwise we'll see if any of the given specifiers accept
798
+ # prereleases, if any of them do we'll return True, otherwise False.
799
+ if any(s.prereleases for s in self._specs):
800
+ return True
801
+
802
+ return None
803
+
804
+ @prereleases.setter
805
+ def prereleases(self, value: bool | None) -> None:
806
+ self._prereleases = value
807
+
808
+ def __repr__(self) -> str:
809
+ """A representation of the specifier set that shows all internal state.
810
+
811
+ Note that the ordering of the individual specifiers within the set may not
812
+ match the input string.
813
+
814
+ >>> SpecifierSet('>=1.0.0,!=2.0.0')
815
+ <SpecifierSet('!=2.0.0,>=1.0.0')>
816
+ >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)
817
+ <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=False)>
818
+ >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)
819
+ <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=True)>
820
+ """
821
+ pre = (
822
+ f", prereleases={self.prereleases!r}"
823
+ if self._prereleases is not None
824
+ else ""
825
+ )
826
+
827
+ return f"<SpecifierSet({str(self)!r}{pre})>"
828
+
829
+ def __str__(self) -> str:
830
+ """A string representation of the specifier set that can be round-tripped.
831
+
832
+ Note that the ordering of the individual specifiers within the set may not
833
+ match the input string.
834
+
835
+ >>> str(SpecifierSet(">=1.0.0,!=1.0.1"))
836
+ '!=1.0.1,>=1.0.0'
837
+ >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False))
838
+ '!=1.0.1,>=1.0.0'
839
+ """
840
+ return ",".join(sorted(str(s) for s in self._specs))
841
+
842
+ def __hash__(self) -> int:
843
+ return hash(self._specs)
844
+
845
+ def __and__(self, other: SpecifierSet | str) -> SpecifierSet:
846
+ """Return a SpecifierSet which is a combination of the two sets.
847
+
848
+ :param other: The other object to combine with.
849
+
850
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1'
851
+ <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>
852
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1')
853
+ <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>
854
+ """
855
+ if isinstance(other, str):
856
+ other = SpecifierSet(other)
857
+ elif not isinstance(other, SpecifierSet):
858
+ return NotImplemented
859
+
860
+ specifier = SpecifierSet()
861
+ specifier._specs = frozenset(self._specs | other._specs)
862
+
863
+ if self._prereleases is None and other._prereleases is not None:
864
+ specifier._prereleases = other._prereleases
865
+ elif (
866
+ self._prereleases is not None and other._prereleases is None
867
+ ) or self._prereleases == other._prereleases:
868
+ specifier._prereleases = self._prereleases
869
+ else:
870
+ raise ValueError(
871
+ "Cannot combine SpecifierSets with True and False prerelease overrides."
872
+ )
873
+
874
+ return specifier
875
+
876
+ def __eq__(self, other: object) -> bool:
877
+ """Whether or not the two SpecifierSet-like objects are equal.
878
+
879
+ :param other: The other object to check against.
880
+
881
+ The value of :attr:`prereleases` is ignored.
882
+
883
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1")
884
+ True
885
+ >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) ==
886
+ ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True))
887
+ True
888
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1"
889
+ True
890
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0")
891
+ False
892
+ >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2")
893
+ False
894
+ """
895
+ if isinstance(other, (str, Specifier)):
896
+ other = SpecifierSet(str(other))
897
+ elif not isinstance(other, SpecifierSet):
898
+ return NotImplemented
899
+
900
+ return self._specs == other._specs
901
+
902
+ def __len__(self) -> int:
903
+ """Returns the number of specifiers in this specifier set."""
904
+ return len(self._specs)
905
+
906
+ def __iter__(self) -> Iterator[Specifier]:
907
+ """
908
+ Returns an iterator over all the underlying :class:`Specifier` instances
909
+ in this specifier set.
910
+
911
+ >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str)
912
+ [<Specifier('!=1.0.1')>, <Specifier('>=1.0.0')>]
913
+ """
914
+ return iter(self._specs)
915
+
916
+ def __contains__(self, item: UnparsedVersion) -> bool:
917
+ """Return whether or not the item is contained in this specifier.
918
+
919
+ :param item: The item to check for.
920
+
921
+ This is used for the ``in`` operator and behaves the same as
922
+ :meth:`contains` with no ``prereleases`` argument passed.
923
+
924
+ >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1")
925
+ True
926
+ >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1")
927
+ True
928
+ >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
929
+ False
930
+ >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
931
+ True
932
+ >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
933
+ True
934
+ """
935
+ return self.contains(item)
936
+
937
+ def contains(
938
+ self,
939
+ item: UnparsedVersion,
940
+ prereleases: bool | None = None,
941
+ installed: bool | None = None,
942
+ ) -> bool:
943
+ """Return whether or not the item is contained in this SpecifierSet.
944
+
945
+ :param item:
946
+ The item to check for, which can be a version string or a
947
+ :class:`Version` instance.
948
+ :param prereleases:
949
+ Whether or not to match prereleases with this SpecifierSet. If set to
950
+ ``None`` (the default), it will follow the recommendation from :pep:`440`
951
+ and match prereleases, as there are no other versions.
952
+ :param installed:
953
+ Whether or not the item is installed. If set to ``True``, it will
954
+ accept prerelease versions even if the specifier does not allow them.
955
+
956
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3")
957
+ True
958
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3"))
959
+ True
960
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
961
+ False
962
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
963
+ True
964
+ >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1")
965
+ False
966
+ >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True)
967
+ True
968
+ """
969
+ version = _coerce_version(item)
970
+
971
+ if version is not None and installed and version.is_prerelease:
972
+ prereleases = True
973
+
974
+ check_item = item if version is None else version
975
+ return bool(list(self.filter([check_item], prereleases=prereleases)))
976
+
977
+ def filter(
978
+ self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
979
+ ) -> Iterator[UnparsedVersionVar]:
980
+ """Filter items in the given iterable, that match the specifiers in this set.
981
+
982
+ :param iterable:
983
+ An iterable that can contain version strings and :class:`Version` instances.
984
+ The items in the iterable will be filtered according to the specifier.
985
+ :param prereleases:
986
+ Whether or not to allow prereleases in the returned iterator. If set to
987
+ ``None`` (the default), it will follow the recommendation from :pep:`440`
988
+ and match prereleases if there are no other versions.
989
+
990
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
991
+ ['1.3']
992
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
993
+ ['1.3', <Version('1.4')>]
994
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
995
+ ['1.5a1']
996
+ >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
997
+ ['1.3', '1.5a1']
998
+ >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
999
+ ['1.3', '1.5a1']
1000
+
1001
+ An "empty" SpecifierSet will filter items based on the presence of prerelease
1002
+ versions in the set.
1003
+
1004
+ >>> list(SpecifierSet("").filter(["1.3", "1.5a1"]))
1005
+ ['1.3']
1006
+ >>> list(SpecifierSet("").filter(["1.5a1"]))
1007
+ ['1.5a1']
1008
+ >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"]))
1009
+ ['1.3', '1.5a1']
1010
+ >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True))
1011
+ ['1.3', '1.5a1']
1012
+ """
1013
+ # Determine if we're forcing a prerelease or not, if we're not forcing
1014
+ # one for this particular filter call, then we'll use whatever the
1015
+ # SpecifierSet thinks for whether or not we should support prereleases.
1016
+ if prereleases is None and self.prereleases is not None:
1017
+ prereleases = self.prereleases
1018
+
1019
+ # If we have any specifiers, then we want to wrap our iterable in the
1020
+ # filter method for each one, this will act as a logical AND amongst
1021
+ # each specifier.
1022
+ if self._specs:
1023
+ # When prereleases is None, we need to let all versions through
1024
+ # the individual filters, then decide about prereleases at the end
1025
+ # based on whether any non-prereleases matched ALL specs.
1026
+ for spec in self._specs:
1027
+ iterable = spec.filter(
1028
+ iterable, prereleases=True if prereleases is None else prereleases
1029
+ )
1030
+
1031
+ if prereleases is not None:
1032
+ # If we have a forced prereleases value,
1033
+ # we can immediately return the iterator.
1034
+ return iter(iterable)
1035
+ else:
1036
+ # Handle empty SpecifierSet cases where prereleases is not None.
1037
+ if prereleases is True:
1038
+ return iter(iterable)
1039
+
1040
+ if prereleases is False:
1041
+ return (
1042
+ item
1043
+ for item in iterable
1044
+ if (version := _coerce_version(item)) is None
1045
+ or not version.is_prerelease
1046
+ )
1047
+
1048
+ # Finally if prereleases is None, apply PEP 440 logic:
1049
+ # exclude prereleases unless there are no final releases that matched.
1050
+ filtered_items: list[UnparsedVersionVar] = []
1051
+ found_prereleases: list[UnparsedVersionVar] = []
1052
+ found_final_release = False
1053
+
1054
+ for item in iterable:
1055
+ parsed_version = _coerce_version(item)
1056
+ # Arbitrary strings are always included as it is not
1057
+ # possible to determine if they are prereleases,
1058
+ # and they have already passed all specifiers.
1059
+ if parsed_version is None:
1060
+ filtered_items.append(item)
1061
+ found_prereleases.append(item)
1062
+ elif parsed_version.is_prerelease:
1063
+ found_prereleases.append(item)
1064
+ else:
1065
+ filtered_items.append(item)
1066
+ found_final_release = True
1067
+
1068
+ return iter(filtered_items if found_final_release else found_prereleases)
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/tags.py ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ import platform
9
+ import re
10
+ import struct
11
+ import subprocess
12
+ import sys
13
+ import sysconfig
14
+ from importlib.machinery import EXTENSION_SUFFIXES
15
+ from typing import (
16
+ Any,
17
+ Iterable,
18
+ Iterator,
19
+ Sequence,
20
+ Tuple,
21
+ cast,
22
+ )
23
+
24
+ from . import _manylinux, _musllinux
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ PythonVersion = Sequence[int]
29
+ AppleVersion = Tuple[int, int]
30
+
31
+ INTERPRETER_SHORT_NAMES: dict[str, str] = {
32
+ "python": "py", # Generic.
33
+ "cpython": "cp",
34
+ "pypy": "pp",
35
+ "ironpython": "ip",
36
+ "jython": "jy",
37
+ }
38
+
39
+
40
+ _32_BIT_INTERPRETER = struct.calcsize("P") == 4
41
+
42
+
43
+ class Tag:
44
+ """
45
+ A representation of the tag triple for a wheel.
46
+
47
+ Instances are considered immutable and thus are hashable. Equality checking
48
+ is also supported.
49
+ """
50
+
51
+ __slots__ = ["_abi", "_hash", "_interpreter", "_platform"]
52
+
53
+ def __init__(self, interpreter: str, abi: str, platform: str) -> None:
54
+ self._interpreter = interpreter.lower()
55
+ self._abi = abi.lower()
56
+ self._platform = platform.lower()
57
+ # The __hash__ of every single element in a Set[Tag] will be evaluated each time
58
+ # that a set calls its `.disjoint()` method, which may be called hundreds of
59
+ # times when scanning a page of links for packages with tags matching that
60
+ # Set[Tag]. Pre-computing the value here produces significant speedups for
61
+ # downstream consumers.
62
+ self._hash = hash((self._interpreter, self._abi, self._platform))
63
+
64
+ @property
65
+ def interpreter(self) -> str:
66
+ return self._interpreter
67
+
68
+ @property
69
+ def abi(self) -> str:
70
+ return self._abi
71
+
72
+ @property
73
+ def platform(self) -> str:
74
+ return self._platform
75
+
76
+ def __eq__(self, other: object) -> bool:
77
+ if not isinstance(other, Tag):
78
+ return NotImplemented
79
+
80
+ return (
81
+ (self._hash == other._hash) # Short-circuit ASAP for perf reasons.
82
+ and (self._platform == other._platform)
83
+ and (self._abi == other._abi)
84
+ and (self._interpreter == other._interpreter)
85
+ )
86
+
87
+ def __hash__(self) -> int:
88
+ return self._hash
89
+
90
+ def __str__(self) -> str:
91
+ return f"{self._interpreter}-{self._abi}-{self._platform}"
92
+
93
+ def __repr__(self) -> str:
94
+ return f"<{self} @ {id(self)}>"
95
+
96
+ def __setstate__(self, state: tuple[None, dict[str, Any]]) -> None:
97
+ # The cached _hash is wrong when unpickling.
98
+ _, slots = state
99
+ for k, v in slots.items():
100
+ setattr(self, k, v)
101
+ self._hash = hash((self._interpreter, self._abi, self._platform))
102
+
103
+
104
+ def parse_tag(tag: str) -> frozenset[Tag]:
105
+ """
106
+ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
107
+
108
+ Returning a set is required due to the possibility that the tag is a
109
+ compressed tag set.
110
+ """
111
+ tags = set()
112
+ interpreters, abis, platforms = tag.split("-")
113
+ for interpreter in interpreters.split("."):
114
+ for abi in abis.split("."):
115
+ for platform_ in platforms.split("."):
116
+ tags.add(Tag(interpreter, abi, platform_))
117
+ return frozenset(tags)
118
+
119
+
120
+ def _get_config_var(name: str, warn: bool = False) -> int | str | None:
121
+ value: int | str | None = sysconfig.get_config_var(name)
122
+ if value is None and warn:
123
+ logger.debug(
124
+ "Config variable '%s' is unset, Python ABI tag may be incorrect", name
125
+ )
126
+ return value
127
+
128
+
129
+ def _normalize_string(string: str) -> str:
130
+ return string.replace(".", "_").replace("-", "_").replace(" ", "_")
131
+
132
+
133
+ def _is_threaded_cpython(abis: list[str]) -> bool:
134
+ """
135
+ Determine if the ABI corresponds to a threaded (`--disable-gil`) build.
136
+
137
+ The threaded builds are indicated by a "t" in the abiflags.
138
+ """
139
+ if len(abis) == 0:
140
+ return False
141
+ # expect e.g., cp313
142
+ m = re.match(r"cp\d+(.*)", abis[0])
143
+ if not m:
144
+ return False
145
+ abiflags = m.group(1)
146
+ return "t" in abiflags
147
+
148
+
149
+ def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool:
150
+ """
151
+ Determine if the Python version supports abi3.
152
+
153
+ PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`)
154
+ builds do not support abi3.
155
+ """
156
+ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
157
+
158
+
159
+ def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]:
160
+ py_version = tuple(py_version) # To allow for version comparison.
161
+ abis = []
162
+ version = _version_nodot(py_version[:2])
163
+ threading = debug = pymalloc = ucs4 = ""
164
+ with_debug = _get_config_var("Py_DEBUG", warn)
165
+ has_refcount = hasattr(sys, "gettotalrefcount")
166
+ # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
167
+ # extension modules is the best option.
168
+ # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
169
+ has_ext = "_d.pyd" in EXTENSION_SUFFIXES
170
+ if with_debug or (with_debug is None and (has_refcount or has_ext)):
171
+ debug = "d"
172
+ if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn):
173
+ threading = "t"
174
+ if py_version < (3, 8):
175
+ with_pymalloc = _get_config_var("WITH_PYMALLOC", warn)
176
+ if with_pymalloc or with_pymalloc is None:
177
+ pymalloc = "m"
178
+ if py_version < (3, 3):
179
+ unicode_size = _get_config_var("Py_UNICODE_SIZE", warn)
180
+ if unicode_size == 4 or (
181
+ unicode_size is None and sys.maxunicode == 0x10FFFF
182
+ ):
183
+ ucs4 = "u"
184
+ elif debug:
185
+ # Debug builds can also load "normal" extension modules.
186
+ # We can also assume no UCS-4 or pymalloc requirement.
187
+ abis.append(f"cp{version}{threading}")
188
+ abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}")
189
+ return abis
190
+
191
+
192
+ def cpython_tags(
193
+ python_version: PythonVersion | None = None,
194
+ abis: Iterable[str] | None = None,
195
+ platforms: Iterable[str] | None = None,
196
+ *,
197
+ warn: bool = False,
198
+ ) -> Iterator[Tag]:
199
+ """
200
+ Yields the tags for a CPython interpreter.
201
+
202
+ The tags consist of:
203
+ - cp<python_version>-<abi>-<platform>
204
+ - cp<python_version>-abi3-<platform>
205
+ - cp<python_version>-none-<platform>
206
+ - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.
207
+
208
+ If python_version only specifies a major version then user-provided ABIs and
209
+ the 'none' ABItag will be used.
210
+
211
+ If 'abi3' or 'none' are specified in 'abis' then they will be yielded at
212
+ their normal position and not at the beginning.
213
+ """
214
+ if not python_version:
215
+ python_version = sys.version_info[:2]
216
+
217
+ interpreter = f"cp{_version_nodot(python_version[:2])}"
218
+
219
+ if abis is None:
220
+ abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else []
221
+ abis = list(abis)
222
+ # 'abi3' and 'none' are explicitly handled later.
223
+ for explicit_abi in ("abi3", "none"):
224
+ try:
225
+ abis.remove(explicit_abi)
226
+ except ValueError: # noqa: PERF203
227
+ pass
228
+
229
+ platforms = list(platforms or platform_tags())
230
+ for abi in abis:
231
+ for platform_ in platforms:
232
+ yield Tag(interpreter, abi, platform_)
233
+
234
+ threading = _is_threaded_cpython(abis)
235
+ use_abi3 = _abi3_applies(python_version, threading)
236
+ if use_abi3:
237
+ yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
238
+ yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
239
+
240
+ if use_abi3:
241
+ for minor_version in range(python_version[1] - 1, 1, -1):
242
+ for platform_ in platforms:
243
+ version = _version_nodot((python_version[0], minor_version))
244
+ interpreter = f"cp{version}"
245
+ yield Tag(interpreter, "abi3", platform_)
246
+
247
+
248
+ def _generic_abi() -> list[str]:
249
+ """
250
+ Return the ABI tag based on EXT_SUFFIX.
251
+ """
252
+ # The following are examples of `EXT_SUFFIX`.
253
+ # We want to keep the parts which are related to the ABI and remove the
254
+ # parts which are related to the platform:
255
+ # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310
256
+ # - mac: '.cpython-310-darwin.so' => cp310
257
+ # - win: '.cp310-win_amd64.pyd' => cp310
258
+ # - win: '.pyd' => cp37 (uses _cpython_abis())
259
+ # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
260
+ # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
261
+ # => graalpy_38_native
262
+
263
+ ext_suffix = _get_config_var("EXT_SUFFIX", warn=True)
264
+ if not isinstance(ext_suffix, str) or ext_suffix[0] != ".":
265
+ raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
266
+ parts = ext_suffix.split(".")
267
+ if len(parts) < 3:
268
+ # CPython3.7 and earlier uses ".pyd" on Windows.
269
+ return _cpython_abis(sys.version_info[:2])
270
+ soabi = parts[1]
271
+ if soabi.startswith("cpython"):
272
+ # non-windows
273
+ abi = "cp" + soabi.split("-")[1]
274
+ elif soabi.startswith("cp"):
275
+ # windows
276
+ abi = soabi.split("-")[0]
277
+ elif soabi.startswith("pypy"):
278
+ abi = "-".join(soabi.split("-")[:2])
279
+ elif soabi.startswith("graalpy"):
280
+ abi = "-".join(soabi.split("-")[:3])
281
+ elif soabi:
282
+ # pyston, ironpython, others?
283
+ abi = soabi
284
+ else:
285
+ return []
286
+ return [_normalize_string(abi)]
287
+
288
+
289
+ def generic_tags(
290
+ interpreter: str | None = None,
291
+ abis: Iterable[str] | None = None,
292
+ platforms: Iterable[str] | None = None,
293
+ *,
294
+ warn: bool = False,
295
+ ) -> Iterator[Tag]:
296
+ """
297
+ Yields the tags for a generic interpreter.
298
+
299
+ The tags consist of:
300
+ - <interpreter>-<abi>-<platform>
301
+
302
+ The "none" ABI will be added if it was not explicitly provided.
303
+ """
304
+ if not interpreter:
305
+ interp_name = interpreter_name()
306
+ interp_version = interpreter_version(warn=warn)
307
+ interpreter = f"{interp_name}{interp_version}"
308
+ abis = _generic_abi() if abis is None else list(abis)
309
+ platforms = list(platforms or platform_tags())
310
+ if "none" not in abis:
311
+ abis.append("none")
312
+ for abi in abis:
313
+ for platform_ in platforms:
314
+ yield Tag(interpreter, abi, platform_)
315
+
316
+
317
+ def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
318
+ """
319
+ Yields Python versions in descending order.
320
+
321
+ After the latest version, the major-only version will be yielded, and then
322
+ all previous versions of that major version.
323
+ """
324
+ if len(py_version) > 1:
325
+ yield f"py{_version_nodot(py_version[:2])}"
326
+ yield f"py{py_version[0]}"
327
+ if len(py_version) > 1:
328
+ for minor in range(py_version[1] - 1, -1, -1):
329
+ yield f"py{_version_nodot((py_version[0], minor))}"
330
+
331
+
332
+ def compatible_tags(
333
+ python_version: PythonVersion | None = None,
334
+ interpreter: str | None = None,
335
+ platforms: Iterable[str] | None = None,
336
+ ) -> Iterator[Tag]:
337
+ """
338
+ Yields the sequence of tags that are compatible with a specific version of Python.
339
+
340
+ The tags consist of:
341
+ - py*-none-<platform>
342
+ - <interpreter>-none-any # ... if `interpreter` is provided.
343
+ - py*-none-any
344
+ """
345
+ if not python_version:
346
+ python_version = sys.version_info[:2]
347
+ platforms = list(platforms or platform_tags())
348
+ for version in _py_interpreter_range(python_version):
349
+ for platform_ in platforms:
350
+ yield Tag(version, "none", platform_)
351
+ if interpreter:
352
+ yield Tag(interpreter, "none", "any")
353
+ for version in _py_interpreter_range(python_version):
354
+ yield Tag(version, "none", "any")
355
+
356
+
357
+ def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
358
+ if not is_32bit:
359
+ return arch
360
+
361
+ if arch.startswith("ppc"):
362
+ return "ppc"
363
+
364
+ return "i386"
365
+
366
+
367
+ def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]:
368
+ formats = [cpu_arch]
369
+ if cpu_arch == "x86_64":
370
+ if version < (10, 4):
371
+ return []
372
+ formats.extend(["intel", "fat64", "fat32"])
373
+
374
+ elif cpu_arch == "i386":
375
+ if version < (10, 4):
376
+ return []
377
+ formats.extend(["intel", "fat32", "fat"])
378
+
379
+ elif cpu_arch == "ppc64":
380
+ # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
381
+ if version > (10, 5) or version < (10, 4):
382
+ return []
383
+ formats.append("fat64")
384
+
385
+ elif cpu_arch == "ppc":
386
+ if version > (10, 6):
387
+ return []
388
+ formats.extend(["fat32", "fat"])
389
+
390
+ if cpu_arch in {"arm64", "x86_64"}:
391
+ formats.append("universal2")
392
+
393
+ if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}:
394
+ formats.append("universal")
395
+
396
+ return formats
397
+
398
+
399
+ def mac_platforms(
400
+ version: AppleVersion | None = None, arch: str | None = None
401
+ ) -> Iterator[str]:
402
+ """
403
+ Yields the platform tags for a macOS system.
404
+
405
+ The `version` parameter is a two-item tuple specifying the macOS version to
406
+ generate platform tags for. The `arch` parameter is the CPU architecture to
407
+ generate platform tags for. Both parameters default to the appropriate value
408
+ for the current system.
409
+ """
410
+ version_str, _, cpu_arch = platform.mac_ver()
411
+ if version is None:
412
+ version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
413
+ if version == (10, 16):
414
+ # When built against an older macOS SDK, Python will report macOS 10.16
415
+ # instead of the real version.
416
+ version_str = subprocess.run(
417
+ [
418
+ sys.executable,
419
+ "-sS",
420
+ "-c",
421
+ "import platform; print(platform.mac_ver()[0])",
422
+ ],
423
+ check=True,
424
+ env={"SYSTEM_VERSION_COMPAT": "0"},
425
+ stdout=subprocess.PIPE,
426
+ text=True,
427
+ ).stdout
428
+ version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
429
+
430
+ if arch is None:
431
+ arch = _mac_arch(cpu_arch)
432
+
433
+ if (10, 0) <= version < (11, 0):
434
+ # Prior to Mac OS 11, each yearly release of Mac OS bumped the
435
+ # "minor" version number. The major version was always 10.
436
+ major_version = 10
437
+ for minor_version in range(version[1], -1, -1):
438
+ compat_version = major_version, minor_version
439
+ binary_formats = _mac_binary_formats(compat_version, arch)
440
+ for binary_format in binary_formats:
441
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
442
+
443
+ if version >= (11, 0):
444
+ # Starting with Mac OS 11, each yearly release bumps the major version
445
+ # number. The minor versions are now the midyear updates.
446
+ minor_version = 0
447
+ for major_version in range(version[0], 10, -1):
448
+ compat_version = major_version, minor_version
449
+ binary_formats = _mac_binary_formats(compat_version, arch)
450
+ for binary_format in binary_formats:
451
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
452
+
453
+ if version >= (11, 0):
454
+ # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
455
+ # Arm64 support was introduced in 11.0, so no Arm binaries from previous
456
+ # releases exist.
457
+ #
458
+ # However, the "universal2" binary format can have a
459
+ # macOS version earlier than 11.0 when the x86_64 part of the binary supports
460
+ # that version of macOS.
461
+ major_version = 10
462
+ if arch == "x86_64":
463
+ for minor_version in range(16, 3, -1):
464
+ compat_version = major_version, minor_version
465
+ binary_formats = _mac_binary_formats(compat_version, arch)
466
+ for binary_format in binary_formats:
467
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
468
+ else:
469
+ for minor_version in range(16, 3, -1):
470
+ compat_version = major_version, minor_version
471
+ binary_format = "universal2"
472
+ yield f"macosx_{major_version}_{minor_version}_{binary_format}"
473
+
474
+
475
+ def ios_platforms(
476
+ version: AppleVersion | None = None, multiarch: str | None = None
477
+ ) -> Iterator[str]:
478
+ """
479
+ Yields the platform tags for an iOS system.
480
+
481
+ :param version: A two-item tuple specifying the iOS version to generate
482
+ platform tags for. Defaults to the current iOS version.
483
+ :param multiarch: The CPU architecture+ABI to generate platform tags for -
484
+ (the value used by `sys.implementation._multiarch` e.g.,
485
+ `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current
486
+ multiarch value.
487
+ """
488
+ if version is None:
489
+ # if iOS is the current platform, ios_ver *must* be defined. However,
490
+ # it won't exist for CPython versions before 3.13, which causes a mypy
491
+ # error.
492
+ _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore]
493
+ version = cast("AppleVersion", tuple(map(int, release.split(".")[:2])))
494
+
495
+ if multiarch is None:
496
+ multiarch = sys.implementation._multiarch
497
+ multiarch = multiarch.replace("-", "_")
498
+
499
+ ios_platform_template = "ios_{major}_{minor}_{multiarch}"
500
+
501
+ # Consider any iOS major.minor version from the version requested, down to
502
+ # 12.0. 12.0 is the first iOS version that is known to have enough features
503
+ # to support CPython. Consider every possible minor release up to X.9. There
504
+ # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra
505
+ # candidates that won't ever match doesn't really hurt, and it saves us from
506
+ # having to keep an explicit list of known iOS versions in the code. Return
507
+ # the results descending order of version number.
508
+
509
+ # If the requested major version is less than 12, there won't be any matches.
510
+ if version[0] < 12:
511
+ return
512
+
513
+ # Consider the actual X.Y version that was requested.
514
+ yield ios_platform_template.format(
515
+ major=version[0], minor=version[1], multiarch=multiarch
516
+ )
517
+
518
+ # Consider every minor version from X.0 to the minor version prior to the
519
+ # version requested by the platform.
520
+ for minor in range(version[1] - 1, -1, -1):
521
+ yield ios_platform_template.format(
522
+ major=version[0], minor=minor, multiarch=multiarch
523
+ )
524
+
525
+ for major in range(version[0] - 1, 11, -1):
526
+ for minor in range(9, -1, -1):
527
+ yield ios_platform_template.format(
528
+ major=major, minor=minor, multiarch=multiarch
529
+ )
530
+
531
+
532
+ def android_platforms(
533
+ api_level: int | None = None, abi: str | None = None
534
+ ) -> Iterator[str]:
535
+ """
536
+ Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on
537
+ non-Android platforms, the ``api_level`` and ``abi`` arguments are required.
538
+
539
+ :param int api_level: The maximum `API level
540
+ <https://developer.android.com/tools/releases/platforms>`__ to return. Defaults
541
+ to the current system's version, as returned by ``platform.android_ver``.
542
+ :param str abi: The `Android ABI <https://developer.android.com/ndk/guides/abis>`__,
543
+ e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by
544
+ ``sysconfig.get_platform``. Hyphens and periods will be replaced with
545
+ underscores.
546
+ """
547
+ if platform.system() != "Android" and (api_level is None or abi is None):
548
+ raise TypeError(
549
+ "on non-Android platforms, the api_level and abi arguments are required"
550
+ )
551
+
552
+ if api_level is None:
553
+ # Python 3.13 was the first version to return platform.system() == "Android",
554
+ # and also the first version to define platform.android_ver().
555
+ api_level = platform.android_ver().api_level # type: ignore[attr-defined]
556
+
557
+ if abi is None:
558
+ abi = sysconfig.get_platform().split("-")[-1]
559
+ abi = _normalize_string(abi)
560
+
561
+ # 16 is the minimum API level known to have enough features to support CPython
562
+ # without major patching. Yield every API level from the maximum down to the
563
+ # minimum, inclusive.
564
+ min_api_level = 16
565
+ for ver in range(api_level, min_api_level - 1, -1):
566
+ yield f"android_{ver}_{abi}"
567
+
568
+
569
+ def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
570
+ linux = _normalize_string(sysconfig.get_platform())
571
+ if not linux.startswith("linux_"):
572
+ # we should never be here, just yield the sysconfig one and return
573
+ yield linux
574
+ return
575
+ if is_32bit:
576
+ if linux == "linux_x86_64":
577
+ linux = "linux_i686"
578
+ elif linux == "linux_aarch64":
579
+ linux = "linux_armv8l"
580
+ _, arch = linux.split("_", 1)
581
+ archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch])
582
+ yield from _manylinux.platform_tags(archs)
583
+ yield from _musllinux.platform_tags(archs)
584
+ for arch in archs:
585
+ yield f"linux_{arch}"
586
+
587
+
588
+ def _generic_platforms() -> Iterator[str]:
589
+ yield _normalize_string(sysconfig.get_platform())
590
+
591
+
592
+ def platform_tags() -> Iterator[str]:
593
+ """
594
+ Provides the platform tags for this installation.
595
+ """
596
+ if platform.system() == "Darwin":
597
+ return mac_platforms()
598
+ elif platform.system() == "iOS":
599
+ return ios_platforms()
600
+ elif platform.system() == "Android":
601
+ return android_platforms()
602
+ elif platform.system() == "Linux":
603
+ return _linux_platforms()
604
+ else:
605
+ return _generic_platforms()
606
+
607
+
608
+ def interpreter_name() -> str:
609
+ """
610
+ Returns the name of the running interpreter.
611
+
612
+ Some implementations have a reserved, two-letter abbreviation which will
613
+ be returned when appropriate.
614
+ """
615
+ name = sys.implementation.name
616
+ return INTERPRETER_SHORT_NAMES.get(name) or name
617
+
618
+
619
+ def interpreter_version(*, warn: bool = False) -> str:
620
+ """
621
+ Returns the version of the running interpreter.
622
+ """
623
+ version = _get_config_var("py_version_nodot", warn=warn)
624
+ return str(version) if version else _version_nodot(sys.version_info[:2])
625
+
626
+
627
+ def _version_nodot(version: PythonVersion) -> str:
628
+ return "".join(map(str, version))
629
+
630
+
631
+ def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
632
+ """
633
+ Returns the sequence of tag triples for the running interpreter.
634
+
635
+ The order of the sequence corresponds to priority order for the
636
+ interpreter, from most to least important.
637
+ """
638
+
639
+ interp_name = interpreter_name()
640
+ if interp_name == "cp":
641
+ yield from cpython_tags(warn=warn)
642
+ else:
643
+ yield from generic_tags()
644
+
645
+ if interp_name == "pp":
646
+ interp = "pp3"
647
+ elif interp_name == "cp":
648
+ interp = "cp" + interpreter_version(warn=warn)
649
+ else:
650
+ interp = None
651
+ yield from compatible_tags(interpreter=interp)
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/utils.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from typing import NewType, Tuple, Union, cast
9
+
10
+ from .tags import Tag, parse_tag
11
+ from .version import InvalidVersion, Version, _TrimmedRelease
12
+
13
+ BuildTag = Union[Tuple[()], Tuple[int, str]]
14
+ NormalizedName = NewType("NormalizedName", str)
15
+
16
+
17
+ class InvalidName(ValueError):
18
+ """
19
+ An invalid distribution name; users should refer to the packaging user guide.
20
+ """
21
+
22
+
23
+ class InvalidWheelFilename(ValueError):
24
+ """
25
+ An invalid wheel filename was found, users should refer to PEP 427.
26
+ """
27
+
28
+
29
+ class InvalidSdistFilename(ValueError):
30
+ """
31
+ An invalid sdist filename was found, users should refer to the packaging user guide.
32
+ """
33
+
34
+
35
+ # Core metadata spec for `Name`
36
+ _validate_regex = re.compile(r"[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9]", re.IGNORECASE)
37
+ _normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]")
38
+ # PEP 427: The build number must start with a digit.
39
+ _build_tag_regex = re.compile(r"(\d+)(.*)")
40
+
41
+
42
+ def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName:
43
+ if validate and not _validate_regex.fullmatch(name):
44
+ raise InvalidName(f"name is invalid: {name!r}")
45
+ # Ensure all ``.`` and ``_`` are ``-``
46
+ # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503
47
+ # Much faster than re, and even faster than str.translate
48
+ value = name.lower().replace("_", "-").replace(".", "-")
49
+ # Condense repeats (faster than regex)
50
+ while "--" in value:
51
+ value = value.replace("--", "-")
52
+ return cast("NormalizedName", value)
53
+
54
+
55
+ def is_normalized_name(name: str) -> bool:
56
+ return _normalized_regex.fullmatch(name) is not None
57
+
58
+
59
+ def canonicalize_version(
60
+ version: Version | str, *, strip_trailing_zero: bool = True
61
+ ) -> str:
62
+ """
63
+ Return a canonical form of a version as a string.
64
+
65
+ >>> canonicalize_version('1.0.1')
66
+ '1.0.1'
67
+
68
+ Per PEP 625, versions may have multiple canonical forms, differing
69
+ only by trailing zeros.
70
+
71
+ >>> canonicalize_version('1.0.0')
72
+ '1'
73
+ >>> canonicalize_version('1.0.0', strip_trailing_zero=False)
74
+ '1.0.0'
75
+
76
+ Invalid versions are returned unaltered.
77
+
78
+ >>> canonicalize_version('foo bar baz')
79
+ 'foo bar baz'
80
+ """
81
+ if isinstance(version, str):
82
+ try:
83
+ version = Version(version)
84
+ except InvalidVersion:
85
+ return str(version)
86
+ return str(_TrimmedRelease(version) if strip_trailing_zero else version)
87
+
88
+
89
+ def parse_wheel_filename(
90
+ filename: str,
91
+ ) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]:
92
+ if not filename.endswith(".whl"):
93
+ raise InvalidWheelFilename(
94
+ f"Invalid wheel filename (extension must be '.whl'): {filename!r}"
95
+ )
96
+
97
+ filename = filename[:-4]
98
+ dashes = filename.count("-")
99
+ if dashes not in (4, 5):
100
+ raise InvalidWheelFilename(
101
+ f"Invalid wheel filename (wrong number of parts): {filename!r}"
102
+ )
103
+
104
+ parts = filename.split("-", dashes - 2)
105
+ name_part = parts[0]
106
+ # See PEP 427 for the rules on escaping the project name.
107
+ if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
108
+ raise InvalidWheelFilename(f"Invalid project name: {filename!r}")
109
+ name = canonicalize_name(name_part)
110
+
111
+ try:
112
+ version = Version(parts[1])
113
+ except InvalidVersion as e:
114
+ raise InvalidWheelFilename(
115
+ f"Invalid wheel filename (invalid version): {filename!r}"
116
+ ) from e
117
+
118
+ if dashes == 5:
119
+ build_part = parts[2]
120
+ build_match = _build_tag_regex.match(build_part)
121
+ if build_match is None:
122
+ raise InvalidWheelFilename(
123
+ f"Invalid build number: {build_part} in {filename!r}"
124
+ )
125
+ build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2)))
126
+ else:
127
+ build = ()
128
+ tags = parse_tag(parts[-1])
129
+ return (name, version, build, tags)
130
+
131
+
132
+ def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]:
133
+ if filename.endswith(".tar.gz"):
134
+ file_stem = filename[: -len(".tar.gz")]
135
+ elif filename.endswith(".zip"):
136
+ file_stem = filename[: -len(".zip")]
137
+ else:
138
+ raise InvalidSdistFilename(
139
+ f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
140
+ f" {filename!r}"
141
+ )
142
+
143
+ # We are requiring a PEP 440 version, which cannot contain dashes,
144
+ # so we split on the last dash.
145
+ name_part, sep, version_part = file_stem.rpartition("-")
146
+ if not sep:
147
+ raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}")
148
+
149
+ name = canonicalize_name(name_part)
150
+
151
+ try:
152
+ version = Version(version_part)
153
+ except InvalidVersion as e:
154
+ raise InvalidSdistFilename(
155
+ f"Invalid sdist filename (invalid version): {filename!r}"
156
+ ) from e
157
+
158
+ return (name, version)
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/version.py ADDED
@@ -0,0 +1,792 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+ """
5
+ .. testsetup::
6
+
7
+ from packaging.version import parse, Version
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import sys
14
+ import typing
15
+ from typing import (
16
+ Any,
17
+ Callable,
18
+ Literal,
19
+ NamedTuple,
20
+ SupportsInt,
21
+ Tuple,
22
+ TypedDict,
23
+ Union,
24
+ )
25
+
26
+ from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
27
+
28
+ if typing.TYPE_CHECKING:
29
+ from typing_extensions import Self, Unpack
30
+
31
+ if sys.version_info >= (3, 13): # pragma: no cover
32
+ from warnings import deprecated as _deprecated
33
+ elif typing.TYPE_CHECKING:
34
+ from typing_extensions import deprecated as _deprecated
35
+ else: # pragma: no cover
36
+ import functools
37
+ import warnings
38
+
39
+ def _deprecated(message: str) -> object:
40
+ def decorator(func: object) -> object:
41
+ @functools.wraps(func)
42
+ def wrapper(*args: object, **kwargs: object) -> object:
43
+ warnings.warn(
44
+ message,
45
+ category=DeprecationWarning,
46
+ stacklevel=2,
47
+ )
48
+ return func(*args, **kwargs)
49
+
50
+ return wrapper
51
+
52
+ return decorator
53
+
54
+
55
+ _LETTER_NORMALIZATION = {
56
+ "alpha": "a",
57
+ "beta": "b",
58
+ "c": "rc",
59
+ "pre": "rc",
60
+ "preview": "rc",
61
+ "rev": "post",
62
+ "r": "post",
63
+ }
64
+
65
+ __all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"]
66
+
67
+ LocalType = Tuple[Union[int, str], ...]
68
+
69
+ CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]
70
+ CmpLocalType = Union[
71
+ NegativeInfinityType,
72
+ Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],
73
+ ]
74
+ CmpKey = Tuple[
75
+ int,
76
+ Tuple[int, ...],
77
+ CmpPrePostDevType,
78
+ CmpPrePostDevType,
79
+ CmpPrePostDevType,
80
+ CmpLocalType,
81
+ ]
82
+ VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
83
+
84
+
85
+ class _VersionReplace(TypedDict, total=False):
86
+ epoch: int | None
87
+ release: tuple[int, ...] | None
88
+ pre: tuple[Literal["a", "b", "rc"], int] | None
89
+ post: int | None
90
+ dev: int | None
91
+ local: str | None
92
+
93
+
94
+ def parse(version: str) -> Version:
95
+ """Parse the given version string.
96
+
97
+ >>> parse('1.0.dev1')
98
+ <Version('1.0.dev1')>
99
+
100
+ :param version: The version string to parse.
101
+ :raises InvalidVersion: When the version string is not a valid version.
102
+ """
103
+ return Version(version)
104
+
105
+
106
+ class InvalidVersion(ValueError):
107
+ """Raised when a version string is not a valid version.
108
+
109
+ >>> Version("invalid")
110
+ Traceback (most recent call last):
111
+ ...
112
+ packaging.version.InvalidVersion: Invalid version: 'invalid'
113
+ """
114
+
115
+
116
+ class _BaseVersion:
117
+ __slots__ = ()
118
+
119
+ # This can also be a normal member (see the packaging_legacy package);
120
+ # we are just requiring it to be readable. Actually defining a property
121
+ # has runtime effect on subclasses, so it's typing only.
122
+ if typing.TYPE_CHECKING:
123
+
124
+ @property
125
+ def _key(self) -> tuple[Any, ...]: ...
126
+
127
+ def __hash__(self) -> int:
128
+ return hash(self._key)
129
+
130
+ # Please keep the duplicated `isinstance` check
131
+ # in the six comparisons hereunder
132
+ # unless you find a way to avoid adding overhead function calls.
133
+ def __lt__(self, other: _BaseVersion) -> bool:
134
+ if not isinstance(other, _BaseVersion):
135
+ return NotImplemented
136
+
137
+ return self._key < other._key
138
+
139
+ def __le__(self, other: _BaseVersion) -> bool:
140
+ if not isinstance(other, _BaseVersion):
141
+ return NotImplemented
142
+
143
+ return self._key <= other._key
144
+
145
+ def __eq__(self, other: object) -> bool:
146
+ if not isinstance(other, _BaseVersion):
147
+ return NotImplemented
148
+
149
+ return self._key == other._key
150
+
151
+ def __ge__(self, other: _BaseVersion) -> bool:
152
+ if not isinstance(other, _BaseVersion):
153
+ return NotImplemented
154
+
155
+ return self._key >= other._key
156
+
157
+ def __gt__(self, other: _BaseVersion) -> bool:
158
+ if not isinstance(other, _BaseVersion):
159
+ return NotImplemented
160
+
161
+ return self._key > other._key
162
+
163
+ def __ne__(self, other: object) -> bool:
164
+ if not isinstance(other, _BaseVersion):
165
+ return NotImplemented
166
+
167
+ return self._key != other._key
168
+
169
+
170
+ # Deliberately not anchored to the start and end of the string, to make it
171
+ # easier for 3rd party code to reuse
172
+
173
+ # Note that ++ doesn't behave identically on CPython and PyPy, so not using it here
174
+ _VERSION_PATTERN = r"""
175
+ v?+ # optional leading v
176
+ (?:
177
+ (?:(?P<epoch>[0-9]+)!)?+ # epoch
178
+ (?P<release>[0-9]+(?:\.[0-9]+)*+) # release segment
179
+ (?P<pre> # pre-release
180
+ [._-]?+
181
+ (?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)
182
+ [._-]?+
183
+ (?P<pre_n>[0-9]+)?
184
+ )?+
185
+ (?P<post> # post release
186
+ (?:-(?P<post_n1>[0-9]+))
187
+ |
188
+ (?:
189
+ [._-]?
190
+ (?P<post_l>post|rev|r)
191
+ [._-]?
192
+ (?P<post_n2>[0-9]+)?
193
+ )
194
+ )?+
195
+ (?P<dev> # dev release
196
+ [._-]?+
197
+ (?P<dev_l>dev)
198
+ [._-]?+
199
+ (?P<dev_n>[0-9]+)?
200
+ )?+
201
+ )
202
+ (?:\+
203
+ (?P<local> # local version
204
+ [a-z0-9]+
205
+ (?:[._-][a-z0-9]+)*+
206
+ )
207
+ )?+
208
+ """
209
+
210
+ _VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
211
+
212
+ # Possessive qualifiers were added in Python 3.11.
213
+ # CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795
214
+ # Older PyPy also had a bug.
215
+ VERSION_PATTERN = (
216
+ _VERSION_PATTERN_OLD
217
+ if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5))
218
+ or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13))
219
+ or sys.version_info < (3, 11)
220
+ else _VERSION_PATTERN
221
+ )
222
+ """
223
+ A string containing the regular expression used to match a valid version.
224
+
225
+ The pattern is not anchored at either end, and is intended for embedding in larger
226
+ expressions (for example, matching a version number as part of a file name). The
227
+ regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
228
+ flags set.
229
+
230
+ :meta hide-value:
231
+ """
232
+
233
+
234
+ # Validation pattern for local version in replace()
235
+ _LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE)
236
+
237
+
238
+ def _validate_epoch(value: object, /) -> int:
239
+ epoch = value or 0
240
+ if isinstance(epoch, int) and epoch >= 0:
241
+ return epoch
242
+ msg = f"epoch must be non-negative integer, got {epoch}"
243
+ raise InvalidVersion(msg)
244
+
245
+
246
+ def _validate_release(value: object, /) -> tuple[int, ...]:
247
+ release = (0,) if value is None else value
248
+ if (
249
+ isinstance(release, tuple)
250
+ and len(release) > 0
251
+ and all(isinstance(i, int) and i >= 0 for i in release)
252
+ ):
253
+ return release
254
+ msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
255
+ raise InvalidVersion(msg)
256
+
257
+
258
+ def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
259
+ if value is None:
260
+ return value
261
+ if (
262
+ isinstance(value, tuple)
263
+ and len(value) == 2
264
+ and value[0] in ("a", "b", "rc")
265
+ and isinstance(value[1], int)
266
+ and value[1] >= 0
267
+ ):
268
+ return value
269
+ msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
270
+ raise InvalidVersion(msg)
271
+
272
+
273
+ def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
274
+ if value is None:
275
+ return value
276
+ if isinstance(value, int) and value >= 0:
277
+ return ("post", value)
278
+ msg = f"post must be non-negative integer, got {value}"
279
+ raise InvalidVersion(msg)
280
+
281
+
282
+ def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
283
+ if value is None:
284
+ return value
285
+ if isinstance(value, int) and value >= 0:
286
+ return ("dev", value)
287
+ msg = f"dev must be non-negative integer, got {value}"
288
+ raise InvalidVersion(msg)
289
+
290
+
291
+ def _validate_local(value: object, /) -> LocalType | None:
292
+ if value is None:
293
+ return value
294
+ if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
295
+ return _parse_local_version(value)
296
+ msg = f"local must be a valid version string, got {value!r}"
297
+ raise InvalidVersion(msg)
298
+
299
+
300
+ # Backward compatibility for internals before 26.0. Do not use.
301
+ class _Version(NamedTuple):
302
+ epoch: int
303
+ release: tuple[int, ...]
304
+ dev: tuple[str, int] | None
305
+ pre: tuple[str, int] | None
306
+ post: tuple[str, int] | None
307
+ local: LocalType | None
308
+
309
+
310
+ class Version(_BaseVersion):
311
+ """This class abstracts handling of a project's versions.
312
+
313
+ A :class:`Version` instance is comparison aware and can be compared and
314
+ sorted using the standard Python interfaces.
315
+
316
+ >>> v1 = Version("1.0a5")
317
+ >>> v2 = Version("1.0")
318
+ >>> v1
319
+ <Version('1.0a5')>
320
+ >>> v2
321
+ <Version('1.0')>
322
+ >>> v1 < v2
323
+ True
324
+ >>> v1 == v2
325
+ False
326
+ >>> v1 > v2
327
+ False
328
+ >>> v1 >= v2
329
+ False
330
+ >>> v1 <= v2
331
+ True
332
+ """
333
+
334
+ __slots__ = ("_dev", "_epoch", "_key_cache", "_local", "_post", "_pre", "_release")
335
+ __match_args__ = ("_str",)
336
+
337
+ _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
338
+
339
+ _epoch: int
340
+ _release: tuple[int, ...]
341
+ _dev: tuple[str, int] | None
342
+ _pre: tuple[str, int] | None
343
+ _post: tuple[str, int] | None
344
+ _local: LocalType | None
345
+
346
+ _key_cache: CmpKey | None
347
+
348
+ def __init__(self, version: str) -> None:
349
+ """Initialize a Version object.
350
+
351
+ :param version:
352
+ The string representation of a version which will be parsed and normalized
353
+ before use.
354
+ :raises InvalidVersion:
355
+ If the ``version`` does not conform to PEP 440 in any way then this
356
+ exception will be raised.
357
+ """
358
+ # Validate the version and parse it into pieces
359
+ match = self._regex.fullmatch(version)
360
+ if not match:
361
+ raise InvalidVersion(f"Invalid version: {version!r}")
362
+ self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
363
+ self._release = tuple(map(int, match.group("release").split(".")))
364
+ self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))
365
+ self._post = _parse_letter_version(
366
+ match.group("post_l"), match.group("post_n1") or match.group("post_n2")
367
+ )
368
+ self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))
369
+ self._local = _parse_local_version(match.group("local"))
370
+
371
+ # Key which will be used for sorting
372
+ self._key_cache = None
373
+
374
+ def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
375
+ epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
376
+ release = (
377
+ _validate_release(kwargs["release"])
378
+ if "release" in kwargs
379
+ else self._release
380
+ )
381
+ pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
382
+ post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
383
+ dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
384
+ local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
385
+
386
+ if (
387
+ epoch == self._epoch
388
+ and release == self._release
389
+ and pre == self._pre
390
+ and post == self._post
391
+ and dev == self._dev
392
+ and local == self._local
393
+ ):
394
+ return self
395
+
396
+ new_version = self.__class__.__new__(self.__class__)
397
+ new_version._key_cache = None
398
+ new_version._epoch = epoch
399
+ new_version._release = release
400
+ new_version._pre = pre
401
+ new_version._post = post
402
+ new_version._dev = dev
403
+ new_version._local = local
404
+
405
+ return new_version
406
+
407
+ @property
408
+ def _key(self) -> CmpKey:
409
+ if self._key_cache is None:
410
+ self._key_cache = _cmpkey(
411
+ self._epoch,
412
+ self._release,
413
+ self._pre,
414
+ self._post,
415
+ self._dev,
416
+ self._local,
417
+ )
418
+ return self._key_cache
419
+
420
+ @property
421
+ @_deprecated("Version._version is private and will be removed soon")
422
+ def _version(self) -> _Version:
423
+ return _Version(
424
+ self._epoch, self._release, self._dev, self._pre, self._post, self._local
425
+ )
426
+
427
+ @_version.setter
428
+ @_deprecated("Version._version is private and will be removed soon")
429
+ def _version(self, value: _Version) -> None:
430
+ self._epoch = value.epoch
431
+ self._release = value.release
432
+ self._dev = value.dev
433
+ self._pre = value.pre
434
+ self._post = value.post
435
+ self._local = value.local
436
+ self._key_cache = None
437
+
438
+ def __repr__(self) -> str:
439
+ """A representation of the Version that shows all internal state.
440
+
441
+ >>> Version('1.0.0')
442
+ <Version('1.0.0')>
443
+ """
444
+ return f"<Version('{self}')>"
445
+
446
+ def __str__(self) -> str:
447
+ """A string representation of the version that can be round-tripped.
448
+
449
+ >>> str(Version("1.0a5"))
450
+ '1.0a5'
451
+ """
452
+ # This is a hot function, so not calling self.base_version
453
+ version = ".".join(map(str, self.release))
454
+
455
+ # Epoch
456
+ if self.epoch:
457
+ version = f"{self.epoch}!{version}"
458
+
459
+ # Pre-release
460
+ if self.pre is not None:
461
+ version += "".join(map(str, self.pre))
462
+
463
+ # Post-release
464
+ if self.post is not None:
465
+ version += f".post{self.post}"
466
+
467
+ # Development release
468
+ if self.dev is not None:
469
+ version += f".dev{self.dev}"
470
+
471
+ # Local version segment
472
+ if self.local is not None:
473
+ version += f"+{self.local}"
474
+
475
+ return version
476
+
477
+ @property
478
+ def _str(self) -> str:
479
+ """Internal property for match_args"""
480
+ return str(self)
481
+
482
+ @property
483
+ def epoch(self) -> int:
484
+ """The epoch of the version.
485
+
486
+ >>> Version("2.0.0").epoch
487
+ 0
488
+ >>> Version("1!2.0.0").epoch
489
+ 1
490
+ """
491
+ return self._epoch
492
+
493
+ @property
494
+ def release(self) -> tuple[int, ...]:
495
+ """The components of the "release" segment of the version.
496
+
497
+ >>> Version("1.2.3").release
498
+ (1, 2, 3)
499
+ >>> Version("2.0.0").release
500
+ (2, 0, 0)
501
+ >>> Version("1!2.0.0.post0").release
502
+ (2, 0, 0)
503
+
504
+ Includes trailing zeroes but not the epoch or any pre-release / development /
505
+ post-release suffixes.
506
+ """
507
+ return self._release
508
+
509
+ @property
510
+ def pre(self) -> tuple[str, int] | None:
511
+ """The pre-release segment of the version.
512
+
513
+ >>> print(Version("1.2.3").pre)
514
+ None
515
+ >>> Version("1.2.3a1").pre
516
+ ('a', 1)
517
+ >>> Version("1.2.3b1").pre
518
+ ('b', 1)
519
+ >>> Version("1.2.3rc1").pre
520
+ ('rc', 1)
521
+ """
522
+ return self._pre
523
+
524
+ @property
525
+ def post(self) -> int | None:
526
+ """The post-release number of the version.
527
+
528
+ >>> print(Version("1.2.3").post)
529
+ None
530
+ >>> Version("1.2.3.post1").post
531
+ 1
532
+ """
533
+ return self._post[1] if self._post else None
534
+
535
+ @property
536
+ def dev(self) -> int | None:
537
+ """The development number of the version.
538
+
539
+ >>> print(Version("1.2.3").dev)
540
+ None
541
+ >>> Version("1.2.3.dev1").dev
542
+ 1
543
+ """
544
+ return self._dev[1] if self._dev else None
545
+
546
+ @property
547
+ def local(self) -> str | None:
548
+ """The local version segment of the version.
549
+
550
+ >>> print(Version("1.2.3").local)
551
+ None
552
+ >>> Version("1.2.3+abc").local
553
+ 'abc'
554
+ """
555
+ if self._local:
556
+ return ".".join(str(x) for x in self._local)
557
+ else:
558
+ return None
559
+
560
+ @property
561
+ def public(self) -> str:
562
+ """The public portion of the version.
563
+
564
+ >>> Version("1.2.3").public
565
+ '1.2.3'
566
+ >>> Version("1.2.3+abc").public
567
+ '1.2.3'
568
+ >>> Version("1!1.2.3dev1+abc").public
569
+ '1!1.2.3.dev1'
570
+ """
571
+ return str(self).split("+", 1)[0]
572
+
573
+ @property
574
+ def base_version(self) -> str:
575
+ """The "base version" of the version.
576
+
577
+ >>> Version("1.2.3").base_version
578
+ '1.2.3'
579
+ >>> Version("1.2.3+abc").base_version
580
+ '1.2.3'
581
+ >>> Version("1!1.2.3dev1+abc").base_version
582
+ '1!1.2.3'
583
+
584
+ The "base version" is the public version of the project without any pre or post
585
+ release markers.
586
+ """
587
+ release_segment = ".".join(map(str, self.release))
588
+ return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
589
+
590
+ @property
591
+ def is_prerelease(self) -> bool:
592
+ """Whether this version is a pre-release.
593
+
594
+ >>> Version("1.2.3").is_prerelease
595
+ False
596
+ >>> Version("1.2.3a1").is_prerelease
597
+ True
598
+ >>> Version("1.2.3b1").is_prerelease
599
+ True
600
+ >>> Version("1.2.3rc1").is_prerelease
601
+ True
602
+ >>> Version("1.2.3dev1").is_prerelease
603
+ True
604
+ """
605
+ return self.dev is not None or self.pre is not None
606
+
607
+ @property
608
+ def is_postrelease(self) -> bool:
609
+ """Whether this version is a post-release.
610
+
611
+ >>> Version("1.2.3").is_postrelease
612
+ False
613
+ >>> Version("1.2.3.post1").is_postrelease
614
+ True
615
+ """
616
+ return self.post is not None
617
+
618
+ @property
619
+ def is_devrelease(self) -> bool:
620
+ """Whether this version is a development release.
621
+
622
+ >>> Version("1.2.3").is_devrelease
623
+ False
624
+ >>> Version("1.2.3.dev1").is_devrelease
625
+ True
626
+ """
627
+ return self.dev is not None
628
+
629
+ @property
630
+ def major(self) -> int:
631
+ """The first item of :attr:`release` or ``0`` if unavailable.
632
+
633
+ >>> Version("1.2.3").major
634
+ 1
635
+ """
636
+ return self.release[0] if len(self.release) >= 1 else 0
637
+
638
+ @property
639
+ def minor(self) -> int:
640
+ """The second item of :attr:`release` or ``0`` if unavailable.
641
+
642
+ >>> Version("1.2.3").minor
643
+ 2
644
+ >>> Version("1").minor
645
+ 0
646
+ """
647
+ return self.release[1] if len(self.release) >= 2 else 0
648
+
649
+ @property
650
+ def micro(self) -> int:
651
+ """The third item of :attr:`release` or ``0`` if unavailable.
652
+
653
+ >>> Version("1.2.3").micro
654
+ 3
655
+ >>> Version("1").micro
656
+ 0
657
+ """
658
+ return self.release[2] if len(self.release) >= 3 else 0
659
+
660
+
661
+ class _TrimmedRelease(Version):
662
+ __slots__ = ()
663
+
664
+ def __init__(self, version: str | Version) -> None:
665
+ if isinstance(version, Version):
666
+ self._epoch = version._epoch
667
+ self._release = version._release
668
+ self._dev = version._dev
669
+ self._pre = version._pre
670
+ self._post = version._post
671
+ self._local = version._local
672
+ self._key_cache = version._key_cache
673
+ return
674
+ super().__init__(version) # pragma: no cover
675
+
676
+ @property
677
+ def release(self) -> tuple[int, ...]:
678
+ """
679
+ Release segment without any trailing zeros.
680
+
681
+ >>> _TrimmedRelease('1.0.0').release
682
+ (1,)
683
+ >>> _TrimmedRelease('0.0').release
684
+ (0,)
685
+ """
686
+ # This leaves one 0.
687
+ rel = super().release
688
+ len_release = len(rel)
689
+ i = len_release
690
+ while i > 1 and rel[i - 1] == 0:
691
+ i -= 1
692
+ return rel if i == len_release else rel[:i]
693
+
694
+
695
+ def _parse_letter_version(
696
+ letter: str | None, number: str | bytes | SupportsInt | None
697
+ ) -> tuple[str, int] | None:
698
+ if letter:
699
+ # We normalize any letters to their lower case form
700
+ letter = letter.lower()
701
+
702
+ # We consider some words to be alternate spellings of other words and
703
+ # in those cases we want to normalize the spellings to our preferred
704
+ # spelling.
705
+ letter = _LETTER_NORMALIZATION.get(letter, letter)
706
+
707
+ # We consider there to be an implicit 0 in a pre-release if there is
708
+ # not a numeral associated with it.
709
+ return letter, int(number or 0)
710
+
711
+ if number:
712
+ # We assume if we are given a number, but we are not given a letter
713
+ # then this is using the implicit post release syntax (e.g. 1.0-1)
714
+ return "post", int(number)
715
+
716
+ return None
717
+
718
+
719
+ _local_version_separators = re.compile(r"[\._-]")
720
+
721
+
722
+ def _parse_local_version(local: str | None) -> LocalType | None:
723
+ """
724
+ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
725
+ """
726
+ if local is not None:
727
+ return tuple(
728
+ part.lower() if not part.isdigit() else int(part)
729
+ for part in _local_version_separators.split(local)
730
+ )
731
+ return None
732
+
733
+
734
+ def _cmpkey(
735
+ epoch: int,
736
+ release: tuple[int, ...],
737
+ pre: tuple[str, int] | None,
738
+ post: tuple[str, int] | None,
739
+ dev: tuple[str, int] | None,
740
+ local: LocalType | None,
741
+ ) -> CmpKey:
742
+ # When we compare a release version, we want to compare it with all of the
743
+ # trailing zeros removed. We will use this for our sorting key.
744
+ len_release = len(release)
745
+ i = len_release
746
+ while i and release[i - 1] == 0:
747
+ i -= 1
748
+ _release = release if i == len_release else release[:i]
749
+
750
+ # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
751
+ # We'll do this by abusing the pre segment, but we _only_ want to do this
752
+ # if there is not a pre or a post segment. If we have one of those then
753
+ # the normal sorting rules will handle this case correctly.
754
+ if pre is None and post is None and dev is not None:
755
+ _pre: CmpPrePostDevType = NegativeInfinity
756
+ # Versions without a pre-release (except as noted above) should sort after
757
+ # those with one.
758
+ elif pre is None:
759
+ _pre = Infinity
760
+ else:
761
+ _pre = pre
762
+
763
+ # Versions without a post segment should sort before those with one.
764
+ if post is None:
765
+ _post: CmpPrePostDevType = NegativeInfinity
766
+
767
+ else:
768
+ _post = post
769
+
770
+ # Versions without a development segment should sort after those with one.
771
+ if dev is None:
772
+ _dev: CmpPrePostDevType = Infinity
773
+
774
+ else:
775
+ _dev = dev
776
+
777
+ if local is None:
778
+ # Versions without a local segment should sort before those with one.
779
+ _local: CmpLocalType = NegativeInfinity
780
+ else:
781
+ # Versions with a local segment need that segment parsed to implement
782
+ # the sorting rules in PEP440.
783
+ # - Alpha numeric segments sort before numeric segments
784
+ # - Alpha numeric segments sort lexicographically
785
+ # - Numeric segments sort numerically
786
+ # - Shorter versions sort before longer versions when the prefixes
787
+ # match exactly
788
+ _local = tuple(
789
+ (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
790
+ )
791
+
792
+ return epoch, _release, _pre, _post, _dev, _local
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/METADATA ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: typer
3
+ Version: 0.24.1
4
+ Summary: Typer, build great CLIs. Easy to code. Based on Python type hints.
5
+ Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Intended Audience :: Information Technology
9
+ Classifier: Intended Audience :: System Administrators
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Classifier: Topic :: Software Development
17
+ Classifier: Typing :: Typed
18
+ Classifier: Development Status :: 4 - Beta
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Project-URL: Homepage, https://github.com/fastapi/typer
27
+ Project-URL: Documentation, https://typer.tiangolo.com
28
+ Project-URL: Repository, https://github.com/fastapi/typer
29
+ Project-URL: Issues, https://github.com/fastapi/typer/issues
30
+ Project-URL: Changelog, https://typer.tiangolo.com/release-notes/
31
+ Requires-Python: >=3.10
32
+ Requires-Dist: click>=8.2.1
33
+ Requires-Dist: shellingham>=1.3.0
34
+ Requires-Dist: rich>=12.3.0
35
+ Requires-Dist: annotated-doc>=0.0.2
36
+ Description-Content-Type: text/markdown
37
+
38
+ <p align="center">
39
+ <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>
40
+
41
+ </p>
42
+ <p align="center">
43
+ <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>
44
+ </p>
45
+ <p align="center">
46
+ <a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank">
47
+ <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">
48
+ </a>
49
+ <a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish" target="_blank">
50
+ <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish">
51
+ </a>
52
+ <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer" target="_blank">
53
+ <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage">
54
+ <a href="https://pypi.org/project/typer" target="_blank">
55
+ <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">
56
+ </a>
57
+ </p>
58
+
59
+ ---
60
+
61
+ **Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com</a>
62
+
63
+ **Source Code**: <a href="https://github.com/fastapi/typer" target="_blank">https://github.com/fastapi/typer</a>
64
+
65
+ ---
66
+
67
+ Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.
68
+
69
+ It's also a command line tool to run scripts, automatically converting them to CLI applications.
70
+
71
+ The key features are:
72
+
73
+ * **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.
74
+ * **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.
75
+ * **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
76
+ * **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.
77
+ * **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.
78
+ * **Run scripts**: Typer includes a `typer` command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.
79
+
80
+ ## 2026 February - Typer developer survey
81
+
82
+ Help us define Typer's future by filling the <a href="https://forms.gle/nYvutPrVkmBQZLas7" class="external-link" target="_blank">Typer developer survey</a>. ✨
83
+
84
+ ## FastAPI of CLIs
85
+
86
+ **Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.
87
+
88
+ ## Installation
89
+
90
+ Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:
91
+
92
+ <div class="termy">
93
+
94
+ ```console
95
+ $ pip install typer
96
+ ---> 100%
97
+ Successfully installed typer rich shellingham
98
+ ```
99
+
100
+ </div>
101
+
102
+ ## Example
103
+
104
+ ### The absolute minimum
105
+
106
+ * Create a file `main.py` with:
107
+
108
+ ```Python
109
+ def main(name: str):
110
+ print(f"Hello {name}")
111
+ ```
112
+
113
+ This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.
114
+
115
+ ### Run it
116
+
117
+ Run your application with the `typer` command:
118
+
119
+ <div class="termy">
120
+
121
+ ```console
122
+ // Run your application
123
+ $ typer main.py run
124
+
125
+ // You get a nice error, you are missing NAME
126
+ Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
127
+ Try 'typer [PATH_OR_MODULE] run --help' for help.
128
+ ╭─ Error ───────────────────────────────────────────╮
129
+ │ Missing argument 'NAME'. │
130
+ ╰───────────────────────────────────────────────────╯
131
+
132
+
133
+ // You get a --help for free
134
+ $ typer main.py run --help
135
+
136
+ Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
137
+
138
+ Run the provided Typer app.
139
+
140
+ ╭─ Arguments ───────────────────────────────────────╮
141
+ │ * name TEXT [default: None] [required] |
142
+ ╰───────────────────────────────────────────────────╯
143
+ ╭─ Options ─────────────────────────────────────────╮
144
+ │ --help Show this message and exit. │
145
+ ╰───────────────────────────────────────────────────╯
146
+
147
+ // Now pass the NAME argument
148
+ $ typer main.py run Camila
149
+
150
+ Hello Camila
151
+
152
+ // It works! 🎉
153
+ ```
154
+
155
+ </div>
156
+
157
+ This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.
158
+
159
+ **Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.
160
+
161
+ ## Use Typer in your code
162
+
163
+ Now let's start using Typer in your own code, update `main.py` with:
164
+
165
+ ```Python
166
+ import typer
167
+
168
+
169
+ def main(name: str):
170
+ print(f"Hello {name}")
171
+
172
+
173
+ if __name__ == "__main__":
174
+ typer.run(main)
175
+ ```
176
+
177
+ Now you could run it with Python directly:
178
+
179
+ <div class="termy">
180
+
181
+ ```console
182
+ // Run your application
183
+ $ python main.py
184
+
185
+ // You get a nice error, you are missing NAME
186
+ Usage: main.py [OPTIONS] NAME
187
+ Try 'main.py --help' for help.
188
+ ╭─ Error ───────────────────────────────────────────╮
189
+ │ Missing argument 'NAME'. │
190
+ ╰───────────────────────────────────────────────────╯
191
+
192
+
193
+ // You get a --help for free
194
+ $ python main.py --help
195
+
196
+ Usage: main.py [OPTIONS] NAME
197
+
198
+ ╭─ Arguments ───────────────────────────────────────╮
199
+ │ * name TEXT [default: None] [required] |
200
+ ╰───────────────────────────────────────────────────╯
201
+ ╭─ Options ─────────────────────────────────────────╮
202
+ │ --help Show this message and exit. │
203
+ ╰───────────────────────────────────────────────────╯
204
+
205
+ // Now pass the NAME argument
206
+ $ python main.py Camila
207
+
208
+ Hello Camila
209
+
210
+ // It works! 🎉
211
+ ```
212
+
213
+ </div>
214
+
215
+ **Note**: you can also call this same script with the `typer` command, but you don't need to.
216
+
217
+ ## Example upgrade
218
+
219
+ This was the simplest example possible.
220
+
221
+ Now let's see one a bit more complex.
222
+
223
+ ### An example with two subcommands
224
+
225
+ Modify the file `main.py`.
226
+
227
+ Create a `typer.Typer()` app, and create two subcommands with their parameters.
228
+
229
+ ```Python hl_lines="3 6 11 20"
230
+ import typer
231
+
232
+ app = typer.Typer()
233
+
234
+
235
+ @app.command()
236
+ def hello(name: str):
237
+ print(f"Hello {name}")
238
+
239
+
240
+ @app.command()
241
+ def goodbye(name: str, formal: bool = False):
242
+ if formal:
243
+ print(f"Goodbye Ms. {name}. Have a good day.")
244
+ else:
245
+ print(f"Bye {name}!")
246
+
247
+
248
+ if __name__ == "__main__":
249
+ app()
250
+ ```
251
+
252
+ And that will:
253
+
254
+ * Explicitly create a `typer.Typer` app.
255
+ * The previous `typer.run` actually creates one implicitly for you.
256
+ * Add two subcommands with `@app.command()`.
257
+ * Execute the `app()` itself, as if it was a function (instead of `typer.run`).
258
+
259
+ ### Run the upgraded example
260
+
261
+ Check the new help:
262
+
263
+ <div class="termy">
264
+
265
+ ```console
266
+ $ python main.py --help
267
+
268
+ Usage: main.py [OPTIONS] COMMAND [ARGS]...
269
+
270
+ ╭─ Options ───────────────────────────────��─────────╮
271
+ │ --install-completion Install completion │
272
+ │ for the current │
273
+ │ shell. │
274
+ │ --show-completion Show completion for │
275
+ │ the current shell, │
276
+ │ to copy it or │
277
+ │ customize the │
278
+ │ installation. │
279
+ │ --help Show this message │
280
+ │ and exit. │
281
+ ╰───────────────────────────────────────────────────╯
282
+ ╭─ Commands ────────────────────────────────────────╮
283
+ │ goodbye │
284
+ │ hello │
285
+ ╰───────────────────────────────────────────────────╯
286
+
287
+ // When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion
288
+
289
+ // You have 2 subcommands (the 2 functions): goodbye and hello
290
+ ```
291
+
292
+ </div>
293
+
294
+ Now check the help for the `hello` command:
295
+
296
+ <div class="termy">
297
+
298
+ ```console
299
+ $ python main.py hello --help
300
+
301
+ Usage: main.py hello [OPTIONS] NAME
302
+
303
+ ╭─ Arguments ───────────────────────────────────────╮
304
+ │ * name TEXT [default: None] [required] │
305
+ ╰───────────────────────────────────────────────────╯
306
+ ╭─ Options ─────────────────────────────────────────╮
307
+ │ --help Show this message and exit. │
308
+ ╰───────────────────────────────────────────────────╯
309
+ ```
310
+
311
+ </div>
312
+
313
+ And now check the help for the `goodbye` command:
314
+
315
+ <div class="termy">
316
+
317
+ ```console
318
+ $ python main.py goodbye --help
319
+
320
+ Usage: main.py goodbye [OPTIONS] NAME
321
+
322
+ ╭─ Arguments ───────────────────────────────────────╮
323
+ │ * name TEXT [default: None] [required] │
324
+ ╰───────────────────────────────────────────────────╯
325
+ ╭─ Options ─────────────────────────────────────────╮
326
+ │ --formal --no-formal [default: no-formal] │
327
+ │ --help Show this message │
328
+ │ and exit. │
329
+ ╰───────────────────────────────────────────────────╯
330
+
331
+ // Automatic --formal and --no-formal for the bool option 🎉
332
+ ```
333
+
334
+ </div>
335
+
336
+ Now you can try out the new command line application:
337
+
338
+ <div class="termy">
339
+
340
+ ```console
341
+ // Use it with the hello command
342
+
343
+ $ python main.py hello Camila
344
+
345
+ Hello Camila
346
+
347
+ // And with the goodbye command
348
+
349
+ $ python main.py goodbye Camila
350
+
351
+ Bye Camila!
352
+
353
+ // And with --formal
354
+
355
+ $ python main.py goodbye --formal Camila
356
+
357
+ Goodbye Ms. Camila. Have a good day.
358
+ ```
359
+
360
+ </div>
361
+
362
+ **Note**: If your app only has one command, by default the command name is **omitted** in usage: `python main.py Camila`. However, when there are multiple commands, you must **explicitly include the command name**: `python main.py hello Camila`. See [One or Multiple Commands](https://typer.tiangolo.com/tutorial/commands/one-or-multiple/) for more details.
363
+
364
+ ### Recap
365
+
366
+ In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.
367
+
368
+ You do that with standard modern Python types.
369
+
370
+ You don't have to learn a new syntax, the methods or classes of a specific library, etc.
371
+
372
+ Just standard **Python**.
373
+
374
+ For example, for an `int`:
375
+
376
+ ```Python
377
+ total: int
378
+ ```
379
+
380
+ or for a `bool` flag:
381
+
382
+ ```Python
383
+ force: bool
384
+ ```
385
+
386
+ And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.
387
+
388
+ **You get**: great editor support, including **completion** and **type checks** everywhere.
389
+
390
+ **Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the `typer` command.
391
+
392
+ For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
393
+
394
+ ## Dependencies
395
+
396
+ **Typer** stands on the shoulders of giants. It has three required dependencies:
397
+
398
+ * <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>: a popular tool for building CLIs in Python. Typer is based on it.
399
+ * <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.
400
+ * <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: to automatically detect the current shell when installing completion.
401
+
402
+ ### `typer-slim`
403
+
404
+ There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.
405
+
406
+ However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.
407
+
408
+ If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.
409
+
410
+ ## License
411
+
412
+ This project is licensed under the terms of the MIT license.
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/RECORD ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ typer-0.24.1.dist-info/METADATA,sha256=V4OWoWjBhPNcoIaOxhr1cszo69nePKOHMRXERkMscKs,16057
2
+ typer-0.24.1.dist-info/WHEEL,sha256=Wb0ASbVj8JvWHpOiIpPi7ucfIgJeCi__PzivviEAQFc,90
3
+ typer-0.24.1.dist-info/entry_points.txt,sha256=YO13ByiqWeuas9V0JADLUARZFUe_cwU_7wmTNvxBYQ8,57
4
+ typer-0.24.1.dist-info/licenses/LICENSE,sha256=WJks68-N-25AxOIRLtEhJsJDZm3KORKj14t-ysSFnUk,1086
5
+ typer/__init__.py,sha256=WOelHJu4PW0hk9nfjEX0Qxssb58NCh1km_Xq5LY_33s,1596
6
+ typer/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
7
+ typer/_completion_classes.py,sha256=R9v4D8pJ_-n8fLOuyxrRSu7sP5lpXIy5fsLUW8zwsDU,7039
8
+ typer/_completion_shared.py,sha256=-uhCUIMc2S1ywdB-fBSSccH70mIBEsVTxHomcmy-klE,9129
9
+ typer/_types.py,sha256=0lcBDLcsxqr1sxTsqObj_u0Dfa37lWJYUY4PNkX4QlA,974
10
+ typer/_typing.py,sha256=QOw5o-B2L--C3ly2DQH6aUwag6x5brV5FhVaBZ5gzMg,1727
11
+ typer/cli.py,sha256=icRbazvdRdbYeaidPZOmJDOzrP3RAa7vj2INVV9Zb8Q,10183
12
+ typer/colors.py,sha256=e42j8uB520hLpX5C_0fiR3OOoIFMbhO3ADZvv6hlAV8,430
13
+ typer/completion.py,sha256=FRTR9hP_IPdJp-4GXPOq0btXo5SvgAtLVfS3ZkAMpgQ,4793
14
+ typer/core.py,sha256=O5NywSwHPyYbLhZkPYSfwIj7Za2hPnoPP4xPXRa97a0,27947
15
+ typer/main.py,sha256=xyNex-QfGUi-enu9j9rl-_wofApxs5VwdpCthAUAAkk,69005
16
+ typer/models.py,sha256=OwPG3MAXiUD5ih3p8eNVciXUsL07UIJfNWy3JiNpDfg,19843
17
+ typer/params.py,sha256=AovViRtl-VvUIXnmKKpnxoWK9_gHUbyQgXxxv3h_7lI,59713
18
+ typer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ typer/rich_utils.py,sha256=RTyeoxwz16ZZXYbwoEixB_LSEnqpoStG_TGCRTz6zFQ,25424
20
+ typer/testing.py,sha256=-ovLNjUNNEFCJoau-41iTJIobsjPbqyTrRq7-8ac4z4,871
21
+ typer/utils.py,sha256=wnJ1DWXBFMnxLHaMN_HDYntxLRby0K-rux63aokHInI,7599
22
+ typer-0.24.1.dist-info/RECORD,,
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.7)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [console_scripts]
2
+ typer = typer.cli:main
3
+
4
+ [gui_scripts]
5
+
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Sebastián Ramírez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typer, build great CLIs. Easy to code. Based on Python type hints."""
2
+
3
+ __version__ = "0.24.1"
4
+
5
+ from shutil import get_terminal_size as get_terminal_size
6
+
7
+ from click.exceptions import Abort as Abort
8
+ from click.exceptions import BadParameter as BadParameter
9
+ from click.exceptions import Exit as Exit
10
+ from click.termui import clear as clear
11
+ from click.termui import confirm as confirm
12
+ from click.termui import echo_via_pager as echo_via_pager
13
+ from click.termui import edit as edit
14
+ from click.termui import getchar as getchar
15
+ from click.termui import pause as pause
16
+ from click.termui import progressbar as progressbar
17
+ from click.termui import prompt as prompt
18
+ from click.termui import secho as secho
19
+ from click.termui import style as style
20
+ from click.termui import unstyle as unstyle
21
+ from click.utils import echo as echo
22
+ from click.utils import format_filename as format_filename
23
+ from click.utils import get_app_dir as get_app_dir
24
+ from click.utils import get_binary_stream as get_binary_stream
25
+ from click.utils import get_text_stream as get_text_stream
26
+ from click.utils import open_file as open_file
27
+
28
+ from . import colors as colors
29
+ from .main import Typer as Typer
30
+ from .main import launch as launch
31
+ from .main import run as run
32
+ from .models import CallbackParam as CallbackParam
33
+ from .models import Context as Context
34
+ from .models import FileBinaryRead as FileBinaryRead
35
+ from .models import FileBinaryWrite as FileBinaryWrite
36
+ from .models import FileText as FileText
37
+ from .models import FileTextWrite as FileTextWrite
38
+ from .params import Argument as Argument
39
+ from .params import Option as Option
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__main__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .cli import main
2
+
3
+ main()