Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/__init__.pyAdded+39
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection.pyAdded+222
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection_pool.pyAdded+420
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http11.pyAdded+379
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http2.pyAdded+592
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http_proxy.pyAdded+367
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/interfaces.pyAdded+137
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/socks_proxy.pyAdded+341
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/__init__.pyAdded
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/anyio.pyAdded+146
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/auto.pyAdded+52
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/base.pyAdded+101
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/mock.pyAdded+143
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/sync.pyAdded+241
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/trio.pyAdded+159
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/__init__.pyAdded+39
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection.pyAdded+222
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection_pool.pyAdded+420
- .cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/http11.pyAdded+379
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/METADATAAdded+107
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/RECORDAdded+24
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSEAdded+3
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.APACHEAdded+177
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.BSDAdded+23
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/__init__.pyAdded+15
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_elffile.pyAdded+108
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_manylinux.pyAdded+262
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_musllinux.pyAdded+85
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_parser.pyAdded+365
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_structures.pyAdded+69
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_tokenizer.pyAdded+193
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/__init__.pyAdded+147
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/_spdx.pyAdded+799
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/markers.pyAdded+388
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/metadata.pyAdded+978
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/py.typedAdded
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/pylock.pyAdded+635
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/requirements.pyAdded+86
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/specifiers.pyAdded+1068
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/tags.pyAdded+651
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/utils.pyAdded+158
- .cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/version.pyAdded+792
- .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/METADATAAdded+412
- .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/RECORDAdded+22
- .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/entry_points.txtAdded+5
- .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/licenses/LICENSEAdded+21
- .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__init__.pyAdded+39
- .cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__main__.pyAdded+3
123456789101112131415161718192021222324252627282930313233343536373839from .connection import AsyncHTTPConnectionfrom .connection_pool import AsyncConnectionPoolfrom .http11 import AsyncHTTP11Connectionfrom .http_proxy import AsyncHTTPProxyfrom .interfaces import AsyncConnectionInterface
try: from .http2 import AsyncHTTP2Connectionexcept ImportError: # pragma: nocover
class AsyncHTTP2Connection: # type: ignore def __init__(self, *args, **kwargs) -> None: # type: ignore raise RuntimeError( "Attempted to use http2 support, but the `h2` package is not " "installed. Use 'pip install httpcore[http2]'." )
try: from .socks_proxy import AsyncSOCKSProxyexcept ImportError: # pragma: nocover
class AsyncSOCKSProxy: # type: ignore def __init__(self, *args, **kwargs) -> None: # type: ignore raise RuntimeError( "Attempted to use SOCKS support, but the `socksio` package is not " "installed. Use 'pip install httpcore[socks]'." )
__all__ = [ "AsyncHTTPConnection", "AsyncConnectionPool", "AsyncHTTPProxy", "AsyncHTTP11Connection", "AsyncHTTP2Connection", "AsyncConnectionInterface", "AsyncSOCKSProxy",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222from __future__ import annotations
import itertoolsimport loggingimport sslimport typesimport typing
from .._backends.auto import AutoBackendfrom .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStreamfrom .._exceptions import ConnectError, ConnectTimeoutfrom .._models import Origin, Request, Responsefrom .._ssl import default_ssl_contextfrom .._synchronization import AsyncLockfrom .._trace import Tracefrom .http11 import AsyncHTTP11Connectionfrom .interfaces import AsyncConnectionInterface
RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc.
logger = logging.getLogger("httpcore.connection")
def exponential_backoff(factor: float) -> typing.Iterator[float]: """ Generate a geometric sequence that has a ratio of 2 and starts with 0.
For example: - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...` - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...` """ yield 0 for n in itertools.count(): yield factor * 2**n
class AsyncHTTPConnection(AsyncConnectionInterface): def __init__( self, origin: Origin, ssl_context: ssl.SSLContext | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._origin = origin self._ssl_context = ssl_context self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._retries = retries self._local_address = local_address self._uds = uds
self._network_backend: AsyncNetworkBackend = ( AutoBackend() if network_backend is None else network_backend ) self._connection: AsyncConnectionInterface | None = None self._connect_failed: bool = False self._request_lock = AsyncLock() self._socket_options = socket_options
async def handle_async_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection to {self._origin}" )
try: async with self._request_lock: if self._connection is None: stream = await self._connect(request)
ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" ) if http2_negotiated or (self._http2 and not self._http1): from .http2 import AsyncHTTP2Connection
self._connection = AsyncHTTP2Connection( origin=self._origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = AsyncHTTP11Connection( origin=self._origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) except BaseException as exc: self._connect_failed = True raise exc
return await self._connection.handle_async_request(request)
async def _connect(self, request: Request) -> AsyncNetworkStream: timeouts = request.extensions.get("timeout", {}) sni_hostname = request.extensions.get("sni_hostname", None) timeout = timeouts.get("connect", None)
retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
while True: try: if self._uds is None: kwargs = { "host": self._origin.host.decode("ascii"), "port": self._origin.port, "local_address": self._local_address, "timeout": timeout, "socket_options": self._socket_options, } async with Trace("connect_tcp", logger, request, kwargs) as trace: stream = await self._network_backend.connect_tcp(**kwargs) trace.return_value = stream else: kwargs = { "path": self._uds, "timeout": timeout, "socket_options": self._socket_options, } async with Trace( "connect_unix_socket", logger, request, kwargs ) as trace: stream = await self._network_backend.connect_unix_socket( **kwargs ) trace.return_value = stream
if self._origin.scheme in (b"https", b"wss"): ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": sni_hostname or self._origin.host.decode("ascii"), "timeout": timeout, } async with Trace("start_tls", logger, request, kwargs) as trace: stream = await stream.start_tls(**kwargs) trace.return_value = stream return stream except (ConnectError, ConnectTimeout): if retries_left <= 0: raise retries_left -= 1 delay = next(delays) async with Trace("retry", logger, request, kwargs) as trace: await self._network_backend.sleep(delay)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
async def aclose(self) -> None: if self._connection is not None: async with Trace("close", logger, None, {}): await self._connection.aclose()
def is_available(self) -> bool: if self._connection is None: # If HTTP/2 support is enabled, and the resulting connection could # end up as HTTP/2 then we should indicate the connection as being # available to service multiple requests. return ( self._http2 and (self._origin.scheme == b"https" or not self._http1) and not self._connect_failed ) return self._connection.is_available()
def has_expired(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.has_expired()
def is_idle(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.is_idle()
def is_closed(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.is_closed()
def info(self) -> str: if self._connection is None: return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" return self._connection.info()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
async def __aenter__(self) -> AsyncHTTPConnection: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420from __future__ import annotations
import sslimport sysimport typesimport typing
from .._backends.auto import AutoBackendfrom .._backends.base import SOCKET_OPTION, AsyncNetworkBackendfrom .._exceptions import ConnectionNotAvailable, UnsupportedProtocolfrom .._models import Origin, Proxy, Request, Responsefrom .._synchronization import AsyncEvent, AsyncShieldCancellation, AsyncThreadLockfrom .connection import AsyncHTTPConnectionfrom .interfaces import AsyncConnectionInterface, AsyncRequestInterface
class AsyncPoolRequest: def __init__(self, request: Request) -> None: self.request = request self.connection: AsyncConnectionInterface | None = None self._connection_acquired = AsyncEvent()
def assign_to_connection(self, connection: AsyncConnectionInterface | None) -> None: self.connection = connection self._connection_acquired.set()
def clear_connection(self) -> None: self.connection = None self._connection_acquired = AsyncEvent()
async def wait_for_connection( self, timeout: float | None = None ) -> AsyncConnectionInterface: if self.connection is None: await self._connection_acquired.wait(timeout=timeout) assert self.connection is not None return self.connection
def is_queued(self) -> bool: return self.connection is None
class AsyncConnectionPool(AsyncRequestInterface): """ A connection pool for making HTTP requests. """
def __init__( self, ssl_context: ssl.SSLContext | None = None, proxy: Proxy | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. socket_options: Socket options that have to be included in the TCP socket when the connection was established. """ self._ssl_context = ssl_context self._proxy = proxy self._max_connections = ( sys.maxsize if max_connections is None else max_connections ) self._max_keepalive_connections = ( sys.maxsize if max_keepalive_connections is None else max_keepalive_connections ) self._max_keepalive_connections = min( self._max_connections, self._max_keepalive_connections )
self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._retries = retries self._local_address = local_address self._uds = uds
self._network_backend = ( AutoBackend() if network_backend is None else network_backend ) self._socket_options = socket_options
# The mutable state on a connection pool is the queue of incoming requests, # and the set of connections that are servicing those requests. self._connections: list[AsyncConnectionInterface] = [] self._requests: list[AsyncPoolRequest] = []
# We only mutate the state of the connection pool within an 'optional_thread_lock' # context. This holds a threading lock unless we're running in async mode, # in which case it is a no-op. self._optional_thread_lock = AsyncThreadLock()
def create_connection(self, origin: Origin) -> AsyncConnectionInterface: if self._proxy is not None: if self._proxy.url.scheme in (b"socks5", b"socks5h"): from .socks_proxy import AsyncSocks5Connection
return AsyncSocks5Connection( proxy_origin=self._proxy.url.origin, proxy_auth=self._proxy.auth, remote_origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, ) elif origin.scheme == b"http": from .http_proxy import AsyncForwardHTTPConnection
return AsyncForwardHTTPConnection( proxy_origin=self._proxy.url.origin, proxy_headers=self._proxy.headers, proxy_ssl_context=self._proxy.ssl_context, remote_origin=origin, keepalive_expiry=self._keepalive_expiry, network_backend=self._network_backend, ) from .http_proxy import AsyncTunnelHTTPConnection
return AsyncTunnelHTTPConnection( proxy_origin=self._proxy.url.origin, proxy_headers=self._proxy.headers, proxy_ssl_context=self._proxy.ssl_context, remote_origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
return AsyncHTTPConnection( origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, retries=self._retries, local_address=self._local_address, uds=self._uds, network_backend=self._network_backend, socket_options=self._socket_options, )
@property def connections(self) -> list[AsyncConnectionInterface]: """ Return a list of the connections currently in the pool.
For example:
```python >>> pool.connections [ <AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 6]>, <AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 9]> , <AsyncHTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>, ] ``` """ return list(self._connections)
async def handle_async_request(self, request: Request) -> Response: """ Send an HTTP request, and return an HTTP response.
This is the core implementation that is called into by `.request()` or `.stream()`. """ scheme = request.url.scheme.decode() if scheme == "": raise UnsupportedProtocol( "Request URL is missing an 'http://' or 'https://' protocol." ) if scheme not in ("http", "https", "ws", "wss"): raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{scheme}://'." )
timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("pool", None)
with self._optional_thread_lock: # Add the incoming request to our request queue. pool_request = AsyncPoolRequest(request) self._requests.append(pool_request)
try: while True: with self._optional_thread_lock: # Assign incoming requests to available connections, # closing or creating new connections as required. closing = self._assign_requests_to_connections() await self._close_connections(closing)
# Wait until this request has an assigned connection. connection = await pool_request.wait_for_connection(timeout=timeout)
try: # Send the request on the assigned connection. response = await connection.handle_async_request( pool_request.request ) except ConnectionNotAvailable: # In some cases a connection may initially be available to # handle a request, but then become unavailable. # # In this case we clear the connection and try again. pool_request.clear_connection() else: break # pragma: nocover
except BaseException as exc: with self._optional_thread_lock: # For any exception or cancellation we remove the request from # the queue, and then re-assign requests to connections. self._requests.remove(pool_request) closing = self._assign_requests_to_connections()
await self._close_connections(closing) raise exc from None
# Return the response. Note that in this case we still have to manage # the point at which the response is closed. assert isinstance(response.stream, typing.AsyncIterable) return Response( status=response.status, headers=response.headers, content=PoolByteStream( stream=response.stream, pool_request=pool_request, pool=self ), extensions=response.extensions, )
def _assign_requests_to_connections(self) -> list[AsyncConnectionInterface]: """ Manage the state of the connection pool, assigning incoming requests to connections as available.
Called whenever a new request is added or removed from the pool.
Any closing connections are returned, allowing the I/O for closing those connections to be handled seperately. """ closing_connections = []
# First we handle cleaning up any connections that are closed, # have expired their keep-alive, or surplus idle connections. for connection in list(self._connections): if connection.is_closed(): # log: "removing closed connection" self._connections.remove(connection) elif connection.has_expired(): # log: "closing expired connection" self._connections.remove(connection) closing_connections.append(connection) elif ( connection.is_idle() and len([connection.is_idle() for connection in self._connections]) > self._max_keepalive_connections ): # log: "closing idle connection" self._connections.remove(connection) closing_connections.append(connection)
# Assign queued requests to connections. queued_requests = [request for request in self._requests if request.is_queued()] for pool_request in queued_requests: origin = pool_request.request.url.origin available_connections = [ connection for connection in self._connections if connection.can_handle_request(origin) and connection.is_available() ] idle_connections = [ connection for connection in self._connections if connection.is_idle() ]
# There are three cases for how we may be able to handle the request: # # 1. There is an existing connection that can handle the request. # 2. We can create a new connection to handle the request. # 3. We can close an idle connection and then create a new connection # to handle the request. if available_connections: # log: "reusing existing connection" connection = available_connections[0] pool_request.assign_to_connection(connection) elif len(self._connections) < self._max_connections: # log: "creating new connection" connection = self.create_connection(origin) self._connections.append(connection) pool_request.assign_to_connection(connection) elif idle_connections: # log: "closing idle connection" connection = idle_connections[0] self._connections.remove(connection) closing_connections.append(connection) # log: "creating new connection" connection = self.create_connection(origin) self._connections.append(connection) pool_request.assign_to_connection(connection)
return closing_connections
async def _close_connections(self, closing: list[AsyncConnectionInterface]) -> None: # Close connections which have been removed from the pool. with AsyncShieldCancellation(): for connection in closing: await connection.aclose()
async def aclose(self) -> None: # Explicitly close the connection pool. # Clears all existing requests and connections. with self._optional_thread_lock: closing_connections = list(self._connections) self._connections = [] await self._close_connections(closing_connections)
async def __aenter__(self) -> AsyncConnectionPool: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()
def __repr__(self) -> str: class_name = self.__class__.__name__ with self._optional_thread_lock: request_is_queued = [request.is_queued() for request in self._requests] connection_is_idle = [ connection.is_idle() for connection in self._connections ]
num_active_requests = request_is_queued.count(False) num_queued_requests = request_is_queued.count(True) num_active_connections = connection_is_idle.count(False) num_idle_connections = connection_is_idle.count(True)
requests_info = ( f"Requests: {num_active_requests} active, {num_queued_requests} queued" ) connection_info = ( f"Connections: {num_active_connections} active, {num_idle_connections} idle" )
return f"<{class_name} [{requests_info} | {connection_info}]>"
class PoolByteStream: def __init__( self, stream: typing.AsyncIterable[bytes], pool_request: AsyncPoolRequest, pool: AsyncConnectionPool, ) -> None: self._stream = stream self._pool_request = pool_request self._pool = pool self._closed = False
async def __aiter__(self) -> typing.AsyncIterator[bytes]: try: async for part in self._stream: yield part except BaseException as exc: await self.aclose() raise exc from None
async def aclose(self) -> None: if not self._closed: self._closed = True with AsyncShieldCancellation(): if hasattr(self._stream, "aclose"): await self._stream.aclose()
with self._pool._optional_thread_lock: self._pool._requests.remove(self._pool_request) closing = self._pool._assign_requests_to_connections()
await self._pool._close_connections(closing)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379from __future__ import annotations
import enumimport loggingimport sslimport timeimport typesimport typing
import h11
from .._backends.base import AsyncNetworkStreamfrom .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError, WriteError, map_exceptions,)from .._models import Origin, Request, Responsefrom .._synchronization import AsyncLock, AsyncShieldCancellationfrom .._trace import Tracefrom .interfaces import AsyncConnectionInterface
logger = logging.getLogger("httpcore.http11")
# A subset of `h11.Event` types supported by `_send_event`H11SendEvent = typing.Union[ h11.Request, h11.Data, h11.EndOfMessage,]
class HTTPConnectionState(enum.IntEnum): NEW = 0 ACTIVE = 1 IDLE = 2 CLOSED = 3
class AsyncHTTP11Connection(AsyncConnectionInterface): READ_NUM_BYTES = 64 * 1024 MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024
def __init__( self, origin: Origin, stream: AsyncNetworkStream, keepalive_expiry: float | None = None, ) -> None: self._origin = origin self._network_stream = stream self._keepalive_expiry: float | None = keepalive_expiry self._expire_at: float | None = None self._state = HTTPConnectionState.NEW self._state_lock = AsyncLock() self._request_count = 0 self._h11_state = h11.Connection( our_role=h11.CLIENT, max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE, )
async def handle_async_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection " f"to {self._origin}" )
async with self._state_lock: if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE): self._request_count += 1 self._state = HTTPConnectionState.ACTIVE self._expire_at = None else: raise ConnectionNotAvailable()
try: kwargs = {"request": request} try: async with Trace( "send_request_headers", logger, request, kwargs ) as trace: await self._send_request_headers(**kwargs) async with Trace("send_request_body", logger, request, kwargs) as trace: await self._send_request_body(**kwargs) except WriteError: # If we get a write error while we're writing the request, # then we supress this error and move on to attempting to # read the response. Servers can sometimes close the request # pre-emptively and then respond with a well formed HTTP # error response. pass
async with Trace( "receive_response_headers", logger, request, kwargs ) as trace: ( http_version, status, reason_phrase, headers, trailing_data, ) = await self._receive_response_headers(**kwargs) trace.return_value = ( http_version, status, reason_phrase, headers, )
network_stream = self._network_stream
# CONNECT or Upgrade request if (status == 101) or ( (request.method == b"CONNECT") and (200 <= status < 300) ): network_stream = AsyncHTTP11UpgradeStream(network_stream, trailing_data)
return Response( status=status, headers=headers, content=HTTP11ConnectionByteStream(self, request), extensions={ "http_version": http_version, "reason_phrase": reason_phrase, "network_stream": network_stream, }, ) except BaseException as exc: with AsyncShieldCancellation(): async with Trace("response_closed", logger, request) as trace: await self._response_closed() raise exc
# Sending the request...
async def _send_request_headers(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
with map_exceptions({h11.LocalProtocolError: LocalProtocolError}): event = h11.Request( method=request.method, target=request.url.target, headers=request.headers, ) await self._send_event(event, timeout=timeout)
async def _send_request_body(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
assert isinstance(request.stream, typing.AsyncIterable) async for chunk in request.stream: event = h11.Data(data=chunk) await self._send_event(event, timeout=timeout)
await self._send_event(h11.EndOfMessage(), timeout=timeout)
async def _send_event(self, event: h11.Event, timeout: float | None = None) -> None: bytes_to_send = self._h11_state.send(event) if bytes_to_send is not None: await self._network_stream.write(bytes_to_send, timeout=timeout)
# Receiving the response...
async def _receive_response_headers( self, request: Request ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
while True: event = await self._receive_event(timeout=timeout) if isinstance(event, h11.Response): break if ( isinstance(event, h11.InformationalResponse) and event.status_code == 101 ): break
http_version = b"HTTP/" + event.http_version
# h11 version 0.11+ supports a `raw_items` interface to get the # raw header casing, rather than the enforced lowercase headers. headers = event.headers.raw_items()
trailing_data, _ = self._h11_state.trailing_data
return http_version, event.status_code, event.reason, headers, trailing_data
async def _receive_response_body( self, request: Request ) -> typing.AsyncIterator[bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
while True: event = await self._receive_event(timeout=timeout) if isinstance(event, h11.Data): yield bytes(event.data) elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)): break
async def _receive_event( self, timeout: float | None = None ) -> h11.Event | type[h11.PAUSED]: while True: with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}): event = self._h11_state.next_event()
if event is h11.NEED_DATA: data = await self._network_stream.read( self.READ_NUM_BYTES, timeout=timeout )
# If we feed this case through h11 we'll raise an exception like: # # httpcore.RemoteProtocolError: can't handle event type # ConnectionClosed when role=SERVER and state=SEND_RESPONSE # # Which is accurate, but not very informative from an end-user # perspective. Instead we handle this case distinctly and treat # it as a ConnectError. if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE: msg = "Server disconnected without sending a response." raise RemoteProtocolError(msg)
self._h11_state.receive_data(data) else: # mypy fails to narrow the type in the above if statement above return event # type: ignore[return-value]
async def _response_closed(self) -> None: async with self._state_lock: if ( self._h11_state.our_state is h11.DONE and self._h11_state.their_state is h11.DONE ): self._state = HTTPConnectionState.IDLE self._h11_state.start_next_cycle() if self._keepalive_expiry is not None: now = time.monotonic() self._expire_at = now + self._keepalive_expiry else: await self.aclose()
# Once the connection is no longer required...
async def aclose(self) -> None: # Note that this method unilaterally closes the connection, and does # not have any kind of locking in place around it. self._state = HTTPConnectionState.CLOSED await self._network_stream.aclose()
# The AsyncConnectionInterface methods provide information about the state of # the connection, allowing for a connection pooling implementation to # determine when to reuse and when to close the connection...
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
def is_available(self) -> bool: # Note that HTTP/1.1 connections in the "NEW" state are not treated as # being "available". The control flow which created the connection will # be able to send an outgoing request, but the connection will not be # acquired from the connection pool for any other request. return self._state == HTTPConnectionState.IDLE
def has_expired(self) -> bool: now = time.monotonic() keepalive_expired = self._expire_at is not None and now > self._expire_at
# If the HTTP connection is idle but the socket is readable, then the # only valid state is that the socket is about to return b"", indicating # a server-initiated disconnect. server_disconnected = ( self._state == HTTPConnectionState.IDLE and self._network_stream.get_extra_info("is_readable") )
return keepalive_expired or server_disconnected
def is_idle(self) -> bool: return self._state == HTTPConnectionState.IDLE
def is_closed(self) -> bool: return self._state == HTTPConnectionState.CLOSED
def info(self) -> str: origin = str(self._origin) return ( f"{origin!r}, HTTP/1.1, {self._state.name}, " f"Request Count: {self._request_count}" )
def __repr__(self) -> str: class_name = self.__class__.__name__ origin = str(self._origin) return ( f"<{class_name} [{origin!r}, {self._state.name}, " f"Request Count: {self._request_count}]>" )
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
async def __aenter__(self) -> AsyncHTTP11Connection: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()
class HTTP11ConnectionByteStream: def __init__(self, connection: AsyncHTTP11Connection, request: Request) -> None: self._connection = connection self._request = request self._closed = False
async def __aiter__(self) -> typing.AsyncIterator[bytes]: kwargs = {"request": self._request} try: async with Trace("receive_response_body", logger, self._request, kwargs): async for chunk in self._connection._receive_response_body(**kwargs): yield chunk except BaseException as exc: # If we get an exception while streaming the response, # we want to close the response (and possibly the connection) # before raising that exception. with AsyncShieldCancellation(): await self.aclose() raise exc
async def aclose(self) -> None: if not self._closed: self._closed = True async with Trace("response_closed", logger, self._request): await self._connection._response_closed()
class AsyncHTTP11UpgradeStream(AsyncNetworkStream): def __init__(self, stream: AsyncNetworkStream, leading_data: bytes) -> None: self._stream = stream self._leading_data = leading_data
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: if self._leading_data: buffer = self._leading_data[:max_bytes] self._leading_data = self._leading_data[max_bytes:] return buffer else: return await self._stream.read(max_bytes, timeout)
async def write(self, buffer: bytes, timeout: float | None = None) -> None: await self._stream.write(buffer, timeout)
async def aclose(self) -> None: await self._stream.aclose()
async def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> AsyncNetworkStream: return await self._stream.start_tls(ssl_context, server_hostname, timeout)
def get_extra_info(self, info: str) -> typing.Any: return self._stream.get_extra_info(info)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592from __future__ import annotations
import enumimport loggingimport timeimport typesimport typing
import h2.configimport h2.connectionimport h2.eventsimport h2.exceptionsimport h2.settings
from .._backends.base import AsyncNetworkStreamfrom .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError,)from .._models import Origin, Request, Responsefrom .._synchronization import AsyncLock, AsyncSemaphore, AsyncShieldCancellationfrom .._trace import Tracefrom .interfaces import AsyncConnectionInterface
logger = logging.getLogger("httpcore.http2")
def has_body_headers(request: Request) -> bool: return any( k.lower() == b"content-length" or k.lower() == b"transfer-encoding" for k, v in request.headers )
class HTTPConnectionState(enum.IntEnum): ACTIVE = 1 IDLE = 2 CLOSED = 3
class AsyncHTTP2Connection(AsyncConnectionInterface): READ_NUM_BYTES = 64 * 1024 CONFIG = h2.config.H2Configuration(validate_inbound_headers=False)
def __init__( self, origin: Origin, stream: AsyncNetworkStream, keepalive_expiry: float | None = None, ): self._origin = origin self._network_stream = stream self._keepalive_expiry: float | None = keepalive_expiry self._h2_state = h2.connection.H2Connection(config=self.CONFIG) self._state = HTTPConnectionState.IDLE self._expire_at: float | None = None self._request_count = 0 self._init_lock = AsyncLock() self._state_lock = AsyncLock() self._read_lock = AsyncLock() self._write_lock = AsyncLock() self._sent_connection_init = False self._used_all_stream_ids = False self._connection_error = False
# Mapping from stream ID to response stream events. self._events: dict[ int, list[ h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded | h2.events.StreamReset, ], ] = {}
# Connection terminated events are stored as state since # we need to handle them for all streams. self._connection_terminated: h2.events.ConnectionTerminated | None = None
self._read_exception: Exception | None = None self._write_exception: Exception | None = None
async def handle_async_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): # This cannot occur in normal operation, since the connection pool # will only send requests on connections that handle them. # It's in place simply for resilience as a guard against incorrect # usage, for anyone working directly with httpcore connections. raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection " f"to {self._origin}" )
async with self._state_lock: if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE): self._request_count += 1 self._expire_at = None self._state = HTTPConnectionState.ACTIVE else: raise ConnectionNotAvailable()
async with self._init_lock: if not self._sent_connection_init: try: sci_kwargs = {"request": request} async with Trace( "send_connection_init", logger, request, sci_kwargs ): await self._send_connection_init(**sci_kwargs) except BaseException as exc: with AsyncShieldCancellation(): await self.aclose() raise exc
self._sent_connection_init = True
# Initially start with just 1 until the remote server provides # its max_concurrent_streams value self._max_streams = 1
local_settings_max_streams = ( self._h2_state.local_settings.max_concurrent_streams ) self._max_streams_semaphore = AsyncSemaphore(local_settings_max_streams)
for _ in range(local_settings_max_streams - self._max_streams): await self._max_streams_semaphore.acquire()
await self._max_streams_semaphore.acquire()
try: stream_id = self._h2_state.get_next_available_stream_id() self._events[stream_id] = [] except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover self._used_all_stream_ids = True self._request_count -= 1 raise ConnectionNotAvailable()
try: kwargs = {"request": request, "stream_id": stream_id} async with Trace("send_request_headers", logger, request, kwargs): await self._send_request_headers(request=request, stream_id=stream_id) async with Trace("send_request_body", logger, request, kwargs): await self._send_request_body(request=request, stream_id=stream_id) async with Trace( "receive_response_headers", logger, request, kwargs ) as trace: status, headers = await self._receive_response( request=request, stream_id=stream_id ) trace.return_value = (status, headers)
return Response( status=status, headers=headers, content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id), extensions={ "http_version": b"HTTP/2", "network_stream": self._network_stream, "stream_id": stream_id, }, ) except BaseException as exc: # noqa: PIE786 with AsyncShieldCancellation(): kwargs = {"stream_id": stream_id} async with Trace("response_closed", logger, request, kwargs): await self._response_closed(stream_id=stream_id)
if isinstance(exc, h2.exceptions.ProtocolError): # One case where h2 can raise a protocol error is when a # closed frame has been seen by the state machine. # # This happens when one stream is reading, and encounters # a GOAWAY event. Other flows of control may then raise # a protocol error at any point they interact with the 'h2_state'. # # In this case we'll have stored the event, and should raise # it as a RemoteProtocolError. if self._connection_terminated: # pragma: nocover raise RemoteProtocolError(self._connection_terminated) # If h2 raises a protocol error in some other state then we # must somehow have made a protocol violation. raise LocalProtocolError(exc) # pragma: nocover
raise exc
async def _send_connection_init(self, request: Request) -> None: """ The HTTP/2 connection requires some initial setup before we can start using individual request/response streams on it. """ # Need to set these manually here instead of manipulating via # __setitem__() otherwise the H2Connection will emit SettingsUpdate # frames in addition to sending the undesired defaults. self._h2_state.local_settings = h2.settings.Settings( client=True, initial_values={ # Disable PUSH_PROMISE frames from the server since we don't do anything # with them for now. Maybe when we support caching? h2.settings.SettingCodes.ENABLE_PUSH: 0, # These two are taken from h2 for safe defaults h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100, h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536, }, )
# Some websites (*cough* Yahoo *cough*) balk at this setting being # present in the initial handshake since it's not defined in the original # RFC despite the RFC mandating ignoring settings you don't know about. del self._h2_state.local_settings[ h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL ]
self._h2_state.initiate_connection() self._h2_state.increment_flow_control_window(2**24) await self._write_outgoing_data(request)
# Sending the request...
async def _send_request_headers(self, request: Request, stream_id: int) -> None: """ Send the request headers to a given stream ID. """ end_stream = not has_body_headers(request)
# In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'. # In order to gracefully handle HTTP/1.1 and HTTP/2 we always require # HTTP/1.1 style headers, and map them appropriately if we end up on # an HTTP/2 connection. authority = [v for k, v in request.headers if k.lower() == b"host"][0]
headers = [ (b":method", request.method), (b":authority", authority), (b":scheme", request.url.scheme), (b":path", request.url.target), ] + [ (k.lower(), v) for k, v in request.headers if k.lower() not in ( b"host", b"transfer-encoding", ) ]
self._h2_state.send_headers(stream_id, headers, end_stream=end_stream) self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id) await self._write_outgoing_data(request)
async def _send_request_body(self, request: Request, stream_id: int) -> None: """ Iterate over the request body sending it to a given stream ID. """ if not has_body_headers(request): return
assert isinstance(request.stream, typing.AsyncIterable) async for data in request.stream: await self._send_stream_data(request, stream_id, data) await self._send_end_stream(request, stream_id)
async def _send_stream_data( self, request: Request, stream_id: int, data: bytes ) -> None: """ Send a single chunk of data in one or more data frames. """ while data: max_flow = await self._wait_for_outgoing_flow(request, stream_id) chunk_size = min(len(data), max_flow) chunk, data = data[:chunk_size], data[chunk_size:] self._h2_state.send_data(stream_id, chunk) await self._write_outgoing_data(request)
async def _send_end_stream(self, request: Request, stream_id: int) -> None: """ Send an empty data frame on on a given stream ID with the END_STREAM flag set. """ self._h2_state.end_stream(stream_id) await self._write_outgoing_data(request)
# Receiving the response...
async def _receive_response( self, request: Request, stream_id: int ) -> tuple[int, list[tuple[bytes, bytes]]]: """ Return the response status code and headers for a given stream ID. """ while True: event = await self._receive_stream_event(request, stream_id) if isinstance(event, h2.events.ResponseReceived): break
status_code = 200 headers = [] assert event.headers is not None for k, v in event.headers: if k == b":status": status_code = int(v.decode("ascii", errors="ignore")) elif not k.startswith(b":"): headers.append((k, v))
return (status_code, headers)
async def _receive_response_body( self, request: Request, stream_id: int ) -> typing.AsyncIterator[bytes]: """ Iterator that returns the bytes of the response body for a given stream ID. """ while True: event = await self._receive_stream_event(request, stream_id) if isinstance(event, h2.events.DataReceived): assert event.flow_controlled_length is not None assert event.data is not None amount = event.flow_controlled_length self._h2_state.acknowledge_received_data(amount, stream_id) await self._write_outgoing_data(request) yield event.data elif isinstance(event, h2.events.StreamEnded): break
async def _receive_stream_event( self, request: Request, stream_id: int ) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded: """ Return the next available event for a given stream ID.
Will read more data from the network if required. """ while not self._events.get(stream_id): await self._receive_events(request, stream_id) event = self._events[stream_id].pop(0) if isinstance(event, h2.events.StreamReset): raise RemoteProtocolError(event) return event
async def _receive_events( self, request: Request, stream_id: int | None = None ) -> None: """ Read some data from the network until we see one or more events for a given stream ID. """ async with self._read_lock: if self._connection_terminated is not None: last_stream_id = self._connection_terminated.last_stream_id if stream_id and last_stream_id and stream_id > last_stream_id: self._request_count -= 1 raise ConnectionNotAvailable() raise RemoteProtocolError(self._connection_terminated)
# This conditional is a bit icky. We don't want to block reading if we've # actually got an event to return for a given stream. We need to do that # check *within* the atomic read lock. Though it also need to be optional, # because when we call it from `_wait_for_outgoing_flow` we *do* want to # block until we've available flow control, event when we have events # pending for the stream ID we're attempting to send on. if stream_id is None or not self._events.get(stream_id): events = await self._read_incoming_data(request) for event in events: if isinstance(event, h2.events.RemoteSettingsChanged): async with Trace( "receive_remote_settings", logger, request ) as trace: await self._receive_remote_settings_change(event) trace.return_value = event
elif isinstance( event, ( h2.events.ResponseReceived, h2.events.DataReceived, h2.events.StreamEnded, h2.events.StreamReset, ), ): if event.stream_id in self._events: self._events[event.stream_id].append(event)
elif isinstance(event, h2.events.ConnectionTerminated): self._connection_terminated = event
await self._write_outgoing_data(request)
async def _receive_remote_settings_change( self, event: h2.events.RemoteSettingsChanged ) -> None: max_concurrent_streams = event.changed_settings.get( h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS ) if max_concurrent_streams: new_max_streams = min( max_concurrent_streams.new_value, self._h2_state.local_settings.max_concurrent_streams, ) if new_max_streams and new_max_streams != self._max_streams: while new_max_streams > self._max_streams: await self._max_streams_semaphore.release() self._max_streams += 1 while new_max_streams < self._max_streams: await self._max_streams_semaphore.acquire() self._max_streams -= 1
async def _response_closed(self, stream_id: int) -> None: await self._max_streams_semaphore.release() del self._events[stream_id] async with self._state_lock: if self._connection_terminated and not self._events: await self.aclose()
elif self._state == HTTPConnectionState.ACTIVE and not self._events: self._state = HTTPConnectionState.IDLE if self._keepalive_expiry is not None: now = time.monotonic() self._expire_at = now + self._keepalive_expiry if self._used_all_stream_ids: # pragma: nocover await self.aclose()
async def aclose(self) -> None: # Note that this method unilaterally closes the connection, and does # not have any kind of locking in place around it. self._h2_state.close_connection() self._state = HTTPConnectionState.CLOSED await self._network_stream.aclose()
# Wrappers around network read/write operations...
async def _read_incoming_data(self, request: Request) -> list[h2.events.Event]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
if self._read_exception is not None: raise self._read_exception # pragma: nocover
try: data = await self._network_stream.read(self.READ_NUM_BYTES, timeout) if data == b"": raise RemoteProtocolError("Server disconnected") except Exception as exc: # If we get a network error we should: # # 1. Save the exception and just raise it immediately on any future reads. # (For example, this means that a single read timeout or disconnect will # immediately close all pending streams. Without requiring multiple # sequential timeouts.) # 2. Mark the connection as errored, so that we don't accept any other # incoming requests. self._read_exception = exc self._connection_error = True raise exc
events: list[h2.events.Event] = self._h2_state.receive_data(data)
return events
async def _write_outgoing_data(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
async with self._write_lock: data_to_send = self._h2_state.data_to_send()
if self._write_exception is not None: raise self._write_exception # pragma: nocover
try: await self._network_stream.write(data_to_send, timeout) except Exception as exc: # pragma: nocover # If we get a network error we should: # # 1. Save the exception and just raise it immediately on any future write. # (For example, this means that a single write timeout or disconnect will # immediately close all pending streams. Without requiring multiple # sequential timeouts.) # 2. Mark the connection as errored, so that we don't accept any other # incoming requests. self._write_exception = exc self._connection_error = True raise exc
# Flow control...
async def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int: """ Returns the maximum allowable outgoing flow for a given stream.
If the allowable flow is zero, then waits on the network until WindowUpdated frames have increased the flow rate. https://tools.ietf.org/html/rfc7540#section-6.9 """ local_flow: int = self._h2_state.local_flow_control_window(stream_id) max_frame_size: int = self._h2_state.max_outbound_frame_size flow = min(local_flow, max_frame_size) while flow == 0: await self._receive_events(request) local_flow = self._h2_state.local_flow_control_window(stream_id) max_frame_size = self._h2_state.max_outbound_frame_size flow = min(local_flow, max_frame_size) return flow
# Interface for connection pooling...
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
def is_available(self) -> bool: return ( self._state != HTTPConnectionState.CLOSED and not self._connection_error and not self._used_all_stream_ids and not ( self._h2_state.state_machine.state == h2.connection.ConnectionState.CLOSED ) )
def has_expired(self) -> bool: now = time.monotonic() return self._expire_at is not None and now > self._expire_at
def is_idle(self) -> bool: return self._state == HTTPConnectionState.IDLE
def is_closed(self) -> bool: return self._state == HTTPConnectionState.CLOSED
def info(self) -> str: origin = str(self._origin) return ( f"{origin!r}, HTTP/2, {self._state.name}, " f"Request Count: {self._request_count}" )
def __repr__(self) -> str: class_name = self.__class__.__name__ origin = str(self._origin) return ( f"<{class_name} [{origin!r}, {self._state.name}, " f"Request Count: {self._request_count}]>" )
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
async def __aenter__(self) -> AsyncHTTP2Connection: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()
class HTTP2ConnectionByteStream: def __init__( self, connection: AsyncHTTP2Connection, request: Request, stream_id: int ) -> None: self._connection = connection self._request = request self._stream_id = stream_id self._closed = False
async def __aiter__(self) -> typing.AsyncIterator[bytes]: kwargs = {"request": self._request, "stream_id": self._stream_id} try: async with Trace("receive_response_body", logger, self._request, kwargs): async for chunk in self._connection._receive_response_body( request=self._request, stream_id=self._stream_id ): yield chunk except BaseException as exc: # If we get an exception while streaming the response, # we want to close the response (and possibly the connection) # before raising that exception. with AsyncShieldCancellation(): await self.aclose() raise exc
async def aclose(self) -> None: if not self._closed: self._closed = True kwargs = {"stream_id": self._stream_id} async with Trace("response_closed", logger, self._request, kwargs): await self._connection._response_closed(stream_id=self._stream_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367from __future__ import annotations
import base64import loggingimport sslimport typing
from .._backends.base import SOCKET_OPTION, AsyncNetworkBackendfrom .._exceptions import ProxyErrorfrom .._models import ( URL, Origin, Request, Response, enforce_bytes, enforce_headers, enforce_url,)from .._ssl import default_ssl_contextfrom .._synchronization import AsyncLockfrom .._trace import Tracefrom .connection import AsyncHTTPConnectionfrom .connection_pool import AsyncConnectionPoolfrom .http11 import AsyncHTTP11Connectionfrom .interfaces import AsyncConnectionInterface
ByteOrStr = typing.Union[bytes, str]HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]]HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr]
logger = logging.getLogger("httpcore.proxy")
def merge_headers( default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,) -> list[tuple[bytes, bytes]]: """ Append default_headers and override_headers, de-duplicating if a key exists in both cases. """ default_headers = [] if default_headers is None else list(default_headers) override_headers = [] if override_headers is None else list(override_headers) has_override = set(key.lower() for key, value in override_headers) default_headers = [ (key, value) for key, value in default_headers if key.lower() not in has_override ] return default_headers + override_headers
class AsyncHTTPProxy(AsyncConnectionPool): # pragma: nocover """ A connection pool that sends requests via an HTTP proxy. """
def __init__( self, proxy_url: URL | bytes | str, proxy_auth: tuple[bytes | str, bytes | str] | None = None, proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: proxy_url: The URL to use when connecting to the proxy server. For example `"http://127.0.0.1:8080/"`. proxy_auth: Any proxy authentication as a two-tuple of (username, password). May be either bytes or ascii-only str. proxy_headers: Any HTTP headers to use for the proxy requests. For example `{"Proxy-Authorization": "Basic <username>:<password>"}`. ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. """ super().__init__( ssl_context=ssl_context, max_connections=max_connections, max_keepalive_connections=max_keepalive_connections, keepalive_expiry=keepalive_expiry, http1=http1, http2=http2, network_backend=network_backend, retries=retries, local_address=local_address, uds=uds, socket_options=socket_options, )
self._proxy_url = enforce_url(proxy_url, name="proxy_url") if ( self._proxy_url.scheme == b"http" and proxy_ssl_context is not None ): # pragma: no cover raise RuntimeError( "The `proxy_ssl_context` argument is not allowed for the http scheme" )
self._ssl_context = ssl_context self._proxy_ssl_context = proxy_ssl_context self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") if proxy_auth is not None: username = enforce_bytes(proxy_auth[0], name="proxy_auth") password = enforce_bytes(proxy_auth[1], name="proxy_auth") userpass = username + b":" + password authorization = b"Basic " + base64.b64encode(userpass) self._proxy_headers = [ (b"Proxy-Authorization", authorization) ] + self._proxy_headers
def create_connection(self, origin: Origin) -> AsyncConnectionInterface: if origin.scheme == b"http": return AsyncForwardHTTPConnection( proxy_origin=self._proxy_url.origin, proxy_headers=self._proxy_headers, remote_origin=origin, keepalive_expiry=self._keepalive_expiry, network_backend=self._network_backend, proxy_ssl_context=self._proxy_ssl_context, ) return AsyncTunnelHTTPConnection( proxy_origin=self._proxy_url.origin, proxy_headers=self._proxy_headers, remote_origin=origin, ssl_context=self._ssl_context, proxy_ssl_context=self._proxy_ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
class AsyncForwardHTTPConnection(AsyncConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, keepalive_expiry: float | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, proxy_ssl_context: ssl.SSLContext | None = None, ) -> None: self._connection = AsyncHTTPConnection( origin=proxy_origin, keepalive_expiry=keepalive_expiry, network_backend=network_backend, socket_options=socket_options, ssl_context=proxy_ssl_context, ) self._proxy_origin = proxy_origin self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") self._remote_origin = remote_origin
async def handle_async_request(self, request: Request) -> Response: headers = merge_headers(self._proxy_headers, request.headers) url = URL( scheme=self._proxy_origin.scheme, host=self._proxy_origin.host, port=self._proxy_origin.port, target=bytes(request.url), ) proxy_request = Request( method=request.method, url=url, headers=headers, content=request.stream, extensions=request.extensions, ) return await self._connection.handle_async_request(proxy_request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
async def aclose(self) -> None: await self._connection.aclose()
def info(self) -> str: return self._connection.info()
def is_available(self) -> bool: return self._connection.is_available()
def has_expired(self) -> bool: return self._connection.has_expired()
def is_idle(self) -> bool: return self._connection.is_idle()
def is_closed(self) -> bool: return self._connection.is_closed()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"
class AsyncTunnelHTTPConnection(AsyncConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._connection: AsyncConnectionInterface = AsyncHTTPConnection( origin=proxy_origin, keepalive_expiry=keepalive_expiry, network_backend=network_backend, socket_options=socket_options, ssl_context=proxy_ssl_context, ) self._proxy_origin = proxy_origin self._remote_origin = remote_origin self._ssl_context = ssl_context self._proxy_ssl_context = proxy_ssl_context self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._connect_lock = AsyncLock() self._connected = False
async def handle_async_request(self, request: Request) -> Response: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("connect", None)
async with self._connect_lock: if not self._connected: target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port)
connect_url = URL( scheme=self._proxy_origin.scheme, host=self._proxy_origin.host, port=self._proxy_origin.port, target=target, ) connect_headers = merge_headers( [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers ) connect_request = Request( method=b"CONNECT", url=connect_url, headers=connect_headers, extensions=request.extensions, ) connect_response = await self._connection.handle_async_request( connect_request )
if connect_response.status < 200 or connect_response.status > 299: reason_bytes = connect_response.extensions.get("reason_phrase", b"") reason_str = reason_bytes.decode("ascii", errors="ignore") msg = "%d %s" % (connect_response.status, reason_str) await self._connection.aclose() raise ProxyError(msg)
stream = connect_response.extensions["network_stream"]
# Upgrade the stream to SSL ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": self._remote_origin.host.decode("ascii"), "timeout": timeout, } async with Trace("start_tls", logger, request, kwargs) as trace: stream = await stream.start_tls(**kwargs) trace.return_value = stream
# Determine if we should be using HTTP/1.1 or HTTP/2 ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" )
# Create the HTTP/1.1 or HTTP/2 connection if http2_negotiated or (self._http2 and not self._http1): from .http2 import AsyncHTTP2Connection
self._connection = AsyncHTTP2Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = AsyncHTTP11Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, )
self._connected = True return await self._connection.handle_async_request(request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
async def aclose(self) -> None: await self._connection.aclose()
def info(self) -> str: return self._connection.info()
def is_available(self) -> bool: return self._connection.is_available()
def has_expired(self) -> bool: return self._connection.has_expired()
def is_idle(self) -> bool: return self._connection.is_idle()
def is_closed(self) -> bool: return self._connection.is_closed()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137from __future__ import annotations
import contextlibimport typing
from .._models import ( URL, Extensions, HeaderTypes, Origin, Request, Response, enforce_bytes, enforce_headers, enforce_url, include_request_headers,)
class AsyncRequestInterface: async def request( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.AsyncIterator[bytes] | None = None, extensions: Extensions | None = None, ) -> Response: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") headers = enforce_headers(headers, name="headers")
# Include Host header, and optionally Content-Length or Transfer-Encoding. headers = include_request_headers(headers, url=url, content=content)
request = Request( method=method, url=url, headers=headers, content=content, extensions=extensions, ) response = await self.handle_async_request(request) try: await response.aread() finally: await response.aclose() return response
@contextlib.asynccontextmanager async def stream( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.AsyncIterator[bytes] | None = None, extensions: Extensions | None = None, ) -> typing.AsyncIterator[Response]: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") headers = enforce_headers(headers, name="headers")
# Include Host header, and optionally Content-Length or Transfer-Encoding. headers = include_request_headers(headers, url=url, content=content)
request = Request( method=method, url=url, headers=headers, content=content, extensions=extensions, ) response = await self.handle_async_request(request) try: yield response finally: await response.aclose()
async def handle_async_request(self, request: Request) -> Response: raise NotImplementedError() # pragma: nocover
class AsyncConnectionInterface(AsyncRequestInterface): async def aclose(self) -> None: raise NotImplementedError() # pragma: nocover
def info(self) -> str: raise NotImplementedError() # pragma: nocover
def can_handle_request(self, origin: Origin) -> bool: raise NotImplementedError() # pragma: nocover
def is_available(self) -> bool: """ Return `True` if the connection is currently able to accept an outgoing request.
An HTTP/1.1 connection will only be available if it is currently idle.
An HTTP/2 connection will be available so long as the stream ID space is not yet exhausted, and the connection is not in an error state.
While the connection is being established we may not yet know if it is going to result in an HTTP/1.1 or HTTP/2 connection. The connection should be treated as being available, but might ultimately raise `NewConnectionRequired` required exceptions if multiple requests are attempted over a connection that ends up being established as HTTP/1.1. """ raise NotImplementedError() # pragma: nocover
def has_expired(self) -> bool: """ Return `True` if the connection is in a state where it should be closed.
This either means that the connection is idle and it has passed the expiry time on its keep-alive, or that server has sent an EOF. """ raise NotImplementedError() # pragma: nocover
def is_idle(self) -> bool: """ Return `True` if the connection is currently idle. """ raise NotImplementedError() # pragma: nocover
def is_closed(self) -> bool: """ Return `True` if the connection has been closed.
Used when a response is closed to determine if the connection may be returned to the connection pool or not. """ raise NotImplementedError() # pragma: nocover123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341from __future__ import annotations
import loggingimport ssl
import socksio
from .._backends.auto import AutoBackendfrom .._backends.base import AsyncNetworkBackend, AsyncNetworkStreamfrom .._exceptions import ConnectionNotAvailable, ProxyErrorfrom .._models import URL, Origin, Request, Response, enforce_bytes, enforce_urlfrom .._ssl import default_ssl_contextfrom .._synchronization import AsyncLockfrom .._trace import Tracefrom .connection_pool import AsyncConnectionPoolfrom .http11 import AsyncHTTP11Connectionfrom .interfaces import AsyncConnectionInterface
logger = logging.getLogger("httpcore.socks")
AUTH_METHODS = { b"\x00": "NO AUTHENTICATION REQUIRED", b"\x01": "GSSAPI", b"\x02": "USERNAME/PASSWORD", b"\xff": "NO ACCEPTABLE METHODS",}
REPLY_CODES = { b"\x00": "Succeeded", b"\x01": "General SOCKS server failure", b"\x02": "Connection not allowed by ruleset", b"\x03": "Network unreachable", b"\x04": "Host unreachable", b"\x05": "Connection refused", b"\x06": "TTL expired", b"\x07": "Command not supported", b"\x08": "Address type not supported",}
async def _init_socks5_connection( stream: AsyncNetworkStream, *, host: bytes, port: int, auth: tuple[bytes, bytes] | None = None,) -> None: conn = socksio.socks5.SOCKS5Connection()
# Auth method request auth_method = ( socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED if auth is None else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD ) conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes)
# Auth method response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5AuthReply) if response.method != auth_method: requested = AUTH_METHODS.get(auth_method, "UNKNOWN") responded = AUTH_METHODS.get(response.method, "UNKNOWN") raise ProxyError( f"Requested {requested} from proxy server, but got {responded}." )
if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: # Username/password request assert auth is not None username, password = auth conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes)
# Username/password response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) if not response.success: raise ProxyError("Invalid username/password")
# Connect request conn.send( socksio.socks5.SOCKS5CommandRequest.from_address( socksio.socks5.SOCKS5Command.CONNECT, (host, port) ) ) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes)
# Connect response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5Reply) if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") raise ProxyError(f"Proxy Server could not connect: {reply_code}.")
class AsyncSOCKSProxy(AsyncConnectionPool): # pragma: nocover """ A connection pool that sends requests via an HTTP proxy. """
def __init__( self, proxy_url: URL | bytes | str, proxy_auth: tuple[bytes | str, bytes | str] | None = None, ssl_context: ssl.SSLContext | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, network_backend: AsyncNetworkBackend | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: proxy_url: The URL to use when connecting to the proxy server. For example `"http://127.0.0.1:8080/"`. ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. """ super().__init__( ssl_context=ssl_context, max_connections=max_connections, max_keepalive_connections=max_keepalive_connections, keepalive_expiry=keepalive_expiry, http1=http1, http2=http2, network_backend=network_backend, retries=retries, ) self._ssl_context = ssl_context self._proxy_url = enforce_url(proxy_url, name="proxy_url") if proxy_auth is not None: username, password = proxy_auth username_bytes = enforce_bytes(username, name="proxy_auth") password_bytes = enforce_bytes(password, name="proxy_auth") self._proxy_auth: tuple[bytes, bytes] | None = ( username_bytes, password_bytes, ) else: self._proxy_auth = None
def create_connection(self, origin: Origin) -> AsyncConnectionInterface: return AsyncSocks5Connection( proxy_origin=self._proxy_url.origin, remote_origin=origin, proxy_auth=self._proxy_auth, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
class AsyncSocks5Connection(AsyncConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, proxy_auth: tuple[bytes, bytes] | None = None, ssl_context: ssl.SSLContext | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: AsyncNetworkBackend | None = None, ) -> None: self._proxy_origin = proxy_origin self._remote_origin = remote_origin self._proxy_auth = proxy_auth self._ssl_context = ssl_context self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2
self._network_backend: AsyncNetworkBackend = ( AutoBackend() if network_backend is None else network_backend ) self._connect_lock = AsyncLock() self._connection: AsyncConnectionInterface | None = None self._connect_failed = False
async def handle_async_request(self, request: Request) -> Response: timeouts = request.extensions.get("timeout", {}) sni_hostname = request.extensions.get("sni_hostname", None) timeout = timeouts.get("connect", None)
async with self._connect_lock: if self._connection is None: try: # Connect to the proxy kwargs = { "host": self._proxy_origin.host.decode("ascii"), "port": self._proxy_origin.port, "timeout": timeout, } async with Trace("connect_tcp", logger, request, kwargs) as trace: stream = await self._network_backend.connect_tcp(**kwargs) trace.return_value = stream
# Connect to the remote host using socks5 kwargs = { "stream": stream, "host": self._remote_origin.host.decode("ascii"), "port": self._remote_origin.port, "auth": self._proxy_auth, } async with Trace( "setup_socks5_connection", logger, request, kwargs ) as trace: await _init_socks5_connection(**kwargs) trace.return_value = stream
# Upgrade the stream to SSL if self._remote_origin.scheme == b"https": ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ( ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ) ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": sni_hostname or self._remote_origin.host.decode("ascii"), "timeout": timeout, } async with Trace("start_tls", logger, request, kwargs) as trace: stream = await stream.start_tls(**kwargs) trace.return_value = stream
# Determine if we should be using HTTP/1.1 or HTTP/2 ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" )
# Create the HTTP/1.1 or HTTP/2 connection if http2_negotiated or ( self._http2 and not self._http1 ): # pragma: nocover from .http2 import AsyncHTTP2Connection
self._connection = AsyncHTTP2Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = AsyncHTTP11Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) except Exception as exc: self._connect_failed = True raise exc elif not self._connection.is_available(): # pragma: nocover raise ConnectionNotAvailable()
return await self._connection.handle_async_request(request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
async def aclose(self) -> None: if self._connection is not None: await self._connection.aclose()
def is_available(self) -> bool: if self._connection is None: # pragma: nocover # If HTTP/2 support is enabled, and the resulting connection could # end up as HTTP/2 then we should indicate the connection as being # available to service multiple requests. return ( self._http2 and (self._remote_origin.scheme == b"https" or not self._http1) and not self._connect_failed ) return self._connection.is_available()
def has_expired(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.has_expired()
def is_idle(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.is_idle()
def is_closed(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.is_closed()
def info(self) -> str: if self._connection is None: # pragma: nocover return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" return self._connection.info()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146from __future__ import annotations
import sslimport typing
import anyio
from .._exceptions import ( ConnectError, ConnectTimeout, ReadError, ReadTimeout, WriteError, WriteTimeout, map_exceptions,)from .._utils import is_socket_readablefrom .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
class AnyIOStream(AsyncNetworkStream): def __init__(self, stream: anyio.abc.ByteStream) -> None: self._stream = stream
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: exc_map = { TimeoutError: ReadTimeout, anyio.BrokenResourceError: ReadError, anyio.ClosedResourceError: ReadError, anyio.EndOfStream: ReadError, } with map_exceptions(exc_map): with anyio.fail_after(timeout): try: return await self._stream.receive(max_bytes=max_bytes) except anyio.EndOfStream: # pragma: nocover return b""
async def write(self, buffer: bytes, timeout: float | None = None) -> None: if not buffer: return
exc_map = { TimeoutError: WriteTimeout, anyio.BrokenResourceError: WriteError, anyio.ClosedResourceError: WriteError, } with map_exceptions(exc_map): with anyio.fail_after(timeout): await self._stream.send(item=buffer)
async def aclose(self) -> None: await self._stream.aclose()
async def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> AsyncNetworkStream: exc_map = { TimeoutError: ConnectTimeout, anyio.BrokenResourceError: ConnectError, anyio.EndOfStream: ConnectError, ssl.SSLError: ConnectError, } with map_exceptions(exc_map): try: with anyio.fail_after(timeout): ssl_stream = await anyio.streams.tls.TLSStream.wrap( self._stream, ssl_context=ssl_context, hostname=server_hostname, standard_compatible=False, server_side=False, ) except Exception as exc: # pragma: nocover await self.aclose() raise exc return AnyIOStream(ssl_stream)
def get_extra_info(self, info: str) -> typing.Any: if info == "ssl_object": return self._stream.extra(anyio.streams.tls.TLSAttribute.ssl_object, None) if info == "client_addr": return self._stream.extra(anyio.abc.SocketAttribute.local_address, None) if info == "server_addr": return self._stream.extra(anyio.abc.SocketAttribute.remote_address, None) if info == "socket": return self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None) if info == "is_readable": sock = self._stream.extra(anyio.abc.SocketAttribute.raw_socket, None) return is_socket_readable(sock) return None
class AnyIOBackend(AsyncNetworkBackend): async def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover if socket_options is None: socket_options = [] exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, anyio.BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(timeout): stream: anyio.abc.ByteStream = await anyio.connect_tcp( remote_host=host, remote_port=port, local_host=local_address, ) # By default TCP sockets opened in `asyncio` include TCP_NODELAY. for option in socket_options: stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover return AnyIOStream(stream)
async def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover if socket_options is None: socket_options = [] exc_map = { TimeoutError: ConnectTimeout, OSError: ConnectError, anyio.BrokenResourceError: ConnectError, } with map_exceptions(exc_map): with anyio.fail_after(timeout): stream: anyio.abc.ByteStream = await anyio.connect_unix(path) for option in socket_options: stream._raw_socket.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover return AnyIOStream(stream)
async def sleep(self, seconds: float) -> None: await anyio.sleep(seconds) # pragma: nocover12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152from __future__ import annotations
import typing
from .._synchronization import current_async_libraryfrom .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
class AutoBackend(AsyncNetworkBackend): async def _init_backend(self) -> None: if not (hasattr(self, "_backend")): backend = current_async_library() if backend == "trio": from .trio import TrioBackend
self._backend: AsyncNetworkBackend = TrioBackend() else: from .anyio import AnyIOBackend
self._backend = AnyIOBackend()
async def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: await self._init_backend() return await self._backend.connect_tcp( host, port, timeout=timeout, local_address=local_address, socket_options=socket_options, )
async def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover await self._init_backend() return await self._backend.connect_unix_socket( path, timeout=timeout, socket_options=socket_options )
async def sleep(self, seconds: float) -> None: # pragma: nocover await self._init_backend() return await self._backend.sleep(seconds)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101from __future__ import annotations
import sslimport timeimport typing
SOCKET_OPTION = typing.Union[ typing.Tuple[int, int, int], typing.Tuple[int, int, typing.Union[bytes, bytearray]], typing.Tuple[int, int, None, int],]
class NetworkStream: def read(self, max_bytes: int, timeout: float | None = None) -> bytes: raise NotImplementedError() # pragma: nocover
def write(self, buffer: bytes, timeout: float | None = None) -> None: raise NotImplementedError() # pragma: nocover
def close(self) -> None: raise NotImplementedError() # pragma: nocover
def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> NetworkStream: raise NotImplementedError() # pragma: nocover
def get_extra_info(self, info: str) -> typing.Any: return None # pragma: nocover
class NetworkBackend: def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: raise NotImplementedError() # pragma: nocover
def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: raise NotImplementedError() # pragma: nocover
def sleep(self, seconds: float) -> None: time.sleep(seconds) # pragma: nocover
class AsyncNetworkStream: async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: raise NotImplementedError() # pragma: nocover
async def write(self, buffer: bytes, timeout: float | None = None) -> None: raise NotImplementedError() # pragma: nocover
async def aclose(self) -> None: raise NotImplementedError() # pragma: nocover
async def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> AsyncNetworkStream: raise NotImplementedError() # pragma: nocover
def get_extra_info(self, info: str) -> typing.Any: return None # pragma: nocover
class AsyncNetworkBackend: async def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: raise NotImplementedError() # pragma: nocover
async def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: raise NotImplementedError() # pragma: nocover
async def sleep(self, seconds: float) -> None: raise NotImplementedError() # pragma: nocover123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143from __future__ import annotations
import sslimport typing
from .._exceptions import ReadErrorfrom .base import ( SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream, NetworkBackend, NetworkStream,)
class MockSSLObject: def __init__(self, http2: bool): self._http2 = http2
def selected_alpn_protocol(self) -> str: return "h2" if self._http2 else "http/1.1"
class MockStream(NetworkStream): def __init__(self, buffer: list[bytes], http2: bool = False) -> None: self._buffer = buffer self._http2 = http2 self._closed = False
def read(self, max_bytes: int, timeout: float | None = None) -> bytes: if self._closed: raise ReadError("Connection closed") if not self._buffer: return b"" return self._buffer.pop(0)
def write(self, buffer: bytes, timeout: float | None = None) -> None: pass
def close(self) -> None: self._closed = True
def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> NetworkStream: return self
def get_extra_info(self, info: str) -> typing.Any: return MockSSLObject(http2=self._http2) if info == "ssl_object" else None
def __repr__(self) -> str: return "<httpcore.MockStream>"
class MockBackend(NetworkBackend): def __init__(self, buffer: list[bytes], http2: bool = False) -> None: self._buffer = buffer self._http2 = http2
def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: return MockStream(list(self._buffer), http2=self._http2)
def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: return MockStream(list(self._buffer), http2=self._http2)
def sleep(self, seconds: float) -> None: pass
class AsyncMockStream(AsyncNetworkStream): def __init__(self, buffer: list[bytes], http2: bool = False) -> None: self._buffer = buffer self._http2 = http2 self._closed = False
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: if self._closed: raise ReadError("Connection closed") if not self._buffer: return b"" return self._buffer.pop(0)
async def write(self, buffer: bytes, timeout: float | None = None) -> None: pass
async def aclose(self) -> None: self._closed = True
async def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> AsyncNetworkStream: return self
def get_extra_info(self, info: str) -> typing.Any: return MockSSLObject(http2=self._http2) if info == "ssl_object" else None
def __repr__(self) -> str: return "<httpcore.AsyncMockStream>"
class AsyncMockBackend(AsyncNetworkBackend): def __init__(self, buffer: list[bytes], http2: bool = False) -> None: self._buffer = buffer self._http2 = http2
async def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: return AsyncMockStream(list(self._buffer), http2=self._http2)
async def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: return AsyncMockStream(list(self._buffer), http2=self._http2)
async def sleep(self, seconds: float) -> None: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241from __future__ import annotations
import functoolsimport socketimport sslimport sysimport typing
from .._exceptions import ( ConnectError, ConnectTimeout, ExceptionMapping, ReadError, ReadTimeout, WriteError, WriteTimeout, map_exceptions,)from .._utils import is_socket_readablefrom .base import SOCKET_OPTION, NetworkBackend, NetworkStream
class TLSinTLSStream(NetworkStream): # pragma: no cover """ Because the standard `SSLContext.wrap_socket` method does not work for `SSLSocket` objects, we need this class to implement TLS stream using an underlying `SSLObject` instance in order to support TLS on top of TLS. """
# Defined in RFC 8449 TLS_RECORD_SIZE = 16384
def __init__( self, sock: socket.socket, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ): self._sock = sock self._incoming = ssl.MemoryBIO() self._outgoing = ssl.MemoryBIO()
self.ssl_obj = ssl_context.wrap_bio( incoming=self._incoming, outgoing=self._outgoing, server_hostname=server_hostname, )
self._sock.settimeout(timeout) self._perform_io(self.ssl_obj.do_handshake)
def _perform_io( self, func: typing.Callable[..., typing.Any], ) -> typing.Any: ret = None
while True: errno = None try: ret = func() except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e: errno = e.errno
self._sock.sendall(self._outgoing.read())
if errno == ssl.SSL_ERROR_WANT_READ: buf = self._sock.recv(self.TLS_RECORD_SIZE)
if buf: self._incoming.write(buf) else: self._incoming.write_eof() if errno is None: return ret
def read(self, max_bytes: int, timeout: float | None = None) -> bytes: exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} with map_exceptions(exc_map): self._sock.settimeout(timeout) return typing.cast( bytes, self._perform_io(functools.partial(self.ssl_obj.read, max_bytes)) )
def write(self, buffer: bytes, timeout: float | None = None) -> None: exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} with map_exceptions(exc_map): self._sock.settimeout(timeout) while buffer: nsent = self._perform_io(functools.partial(self.ssl_obj.write, buffer)) buffer = buffer[nsent:]
def close(self) -> None: self._sock.close()
def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> NetworkStream: raise NotImplementedError()
def get_extra_info(self, info: str) -> typing.Any: if info == "ssl_object": return self.ssl_obj if info == "client_addr": return self._sock.getsockname() if info == "server_addr": return self._sock.getpeername() if info == "socket": return self._sock if info == "is_readable": return is_socket_readable(self._sock) return None
class SyncStream(NetworkStream): def __init__(self, sock: socket.socket) -> None: self._sock = sock
def read(self, max_bytes: int, timeout: float | None = None) -> bytes: exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} with map_exceptions(exc_map): self._sock.settimeout(timeout) return self._sock.recv(max_bytes)
def write(self, buffer: bytes, timeout: float | None = None) -> None: if not buffer: return
exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} with map_exceptions(exc_map): while buffer: self._sock.settimeout(timeout) n = self._sock.send(buffer) buffer = buffer[n:]
def close(self) -> None: self._sock.close()
def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> NetworkStream: exc_map: ExceptionMapping = { socket.timeout: ConnectTimeout, OSError: ConnectError, } with map_exceptions(exc_map): try: if isinstance(self._sock, ssl.SSLSocket): # pragma: no cover # If the underlying socket has already been upgraded # to the TLS layer (i.e. is an instance of SSLSocket), # we need some additional smarts to support TLS-in-TLS. return TLSinTLSStream( self._sock, ssl_context, server_hostname, timeout ) else: self._sock.settimeout(timeout) sock = ssl_context.wrap_socket( self._sock, server_hostname=server_hostname ) except Exception as exc: # pragma: nocover self.close() raise exc return SyncStream(sock)
def get_extra_info(self, info: str) -> typing.Any: if info == "ssl_object" and isinstance(self._sock, ssl.SSLSocket): return self._sock._sslobj # type: ignore if info == "client_addr": return self._sock.getsockname() if info == "server_addr": return self._sock.getpeername() if info == "socket": return self._sock if info == "is_readable": return is_socket_readable(self._sock) return None
class SyncBackend(NetworkBackend): def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: # Note that we automatically include `TCP_NODELAY` # in addition to any other custom socket options. if socket_options is None: socket_options = [] # pragma: no cover address = (host, port) source_address = None if local_address is None else (local_address, 0) exc_map: ExceptionMapping = { socket.timeout: ConnectTimeout, OSError: ConnectError, }
with map_exceptions(exc_map): sock = socket.create_connection( address, timeout, source_address=source_address, ) for option in socket_options: sock.setsockopt(*option) # pragma: no cover sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) return SyncStream(sock)
def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: # pragma: nocover if sys.platform == "win32": raise RuntimeError( "Attempted to connect to a UNIX socket on a Windows system." ) if socket_options is None: socket_options = []
exc_map: ExceptionMapping = { socket.timeout: ConnectTimeout, OSError: ConnectError, } with map_exceptions(exc_map): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for option in socket_options: sock.setsockopt(*option) sock.settimeout(timeout) sock.connect(path) return SyncStream(sock)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159from __future__ import annotations
import sslimport typing
import trio
from .._exceptions import ( ConnectError, ConnectTimeout, ExceptionMapping, ReadError, ReadTimeout, WriteError, WriteTimeout, map_exceptions,)from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
class TrioStream(AsyncNetworkStream): def __init__(self, stream: trio.abc.Stream) -> None: self._stream = stream
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: timeout_or_inf = float("inf") if timeout is None else timeout exc_map: ExceptionMapping = { trio.TooSlowError: ReadTimeout, trio.BrokenResourceError: ReadError, trio.ClosedResourceError: ReadError, } with map_exceptions(exc_map): with trio.fail_after(timeout_or_inf): data: bytes = await self._stream.receive_some(max_bytes=max_bytes) return data
async def write(self, buffer: bytes, timeout: float | None = None) -> None: if not buffer: return
timeout_or_inf = float("inf") if timeout is None else timeout exc_map: ExceptionMapping = { trio.TooSlowError: WriteTimeout, trio.BrokenResourceError: WriteError, trio.ClosedResourceError: WriteError, } with map_exceptions(exc_map): with trio.fail_after(timeout_or_inf): await self._stream.send_all(data=buffer)
async def aclose(self) -> None: await self._stream.aclose()
async def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> AsyncNetworkStream: timeout_or_inf = float("inf") if timeout is None else timeout exc_map: ExceptionMapping = { trio.TooSlowError: ConnectTimeout, trio.BrokenResourceError: ConnectError, } ssl_stream = trio.SSLStream( self._stream, ssl_context=ssl_context, server_hostname=server_hostname, https_compatible=True, server_side=False, ) with map_exceptions(exc_map): try: with trio.fail_after(timeout_or_inf): await ssl_stream.do_handshake() except Exception as exc: # pragma: nocover await self.aclose() raise exc return TrioStream(ssl_stream)
def get_extra_info(self, info: str) -> typing.Any: if info == "ssl_object" and isinstance(self._stream, trio.SSLStream): # Type checkers cannot see `_ssl_object` attribute because trio._ssl.SSLStream uses __getattr__/__setattr__. # Tracked at https://github.com/python-trio/trio/issues/542 return self._stream._ssl_object # type: ignore[attr-defined] if info == "client_addr": return self._get_socket_stream().socket.getsockname() if info == "server_addr": return self._get_socket_stream().socket.getpeername() if info == "socket": stream = self._stream while isinstance(stream, trio.SSLStream): stream = stream.transport_stream assert isinstance(stream, trio.SocketStream) return stream.socket if info == "is_readable": socket = self.get_extra_info("socket") return socket.is_readable() return None
def _get_socket_stream(self) -> trio.SocketStream: stream = self._stream while isinstance(stream, trio.SSLStream): stream = stream.transport_stream assert isinstance(stream, trio.SocketStream) return stream
class TrioBackend(AsyncNetworkBackend): async def connect_tcp( self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # By default for TCP sockets, trio enables TCP_NODELAY. # https://trio.readthedocs.io/en/stable/reference-io.html#trio.SocketStream if socket_options is None: socket_options = [] # pragma: no cover timeout_or_inf = float("inf") if timeout is None else timeout exc_map: ExceptionMapping = { trio.TooSlowError: ConnectTimeout, trio.BrokenResourceError: ConnectError, OSError: ConnectError, } with map_exceptions(exc_map): with trio.fail_after(timeout_or_inf): stream: trio.abc.Stream = await trio.open_tcp_stream( host=host, port=port, local_address=local_address ) for option in socket_options: stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover return TrioStream(stream)
async def connect_unix_socket( self, path: str, timeout: float | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover if socket_options is None: socket_options = [] timeout_or_inf = float("inf") if timeout is None else timeout exc_map: ExceptionMapping = { trio.TooSlowError: ConnectTimeout, trio.BrokenResourceError: ConnectError, OSError: ConnectError, } with map_exceptions(exc_map): with trio.fail_after(timeout_or_inf): stream: trio.abc.Stream = await trio.open_unix_socket(path) for option in socket_options: stream.setsockopt(*option) # type: ignore[attr-defined] # pragma: no cover return TrioStream(stream)
async def sleep(self, seconds: float) -> None: await trio.sleep(seconds) # pragma: nocover123456789101112131415161718192021222324252627282930313233343536373839from .connection import HTTPConnectionfrom .connection_pool import ConnectionPoolfrom .http11 import HTTP11Connectionfrom .http_proxy import HTTPProxyfrom .interfaces import ConnectionInterface
try: from .http2 import HTTP2Connectionexcept ImportError: # pragma: nocover
class HTTP2Connection: # type: ignore def __init__(self, *args, **kwargs) -> None: # type: ignore raise RuntimeError( "Attempted to use http2 support, but the `h2` package is not " "installed. Use 'pip install httpcore[http2]'." )
try: from .socks_proxy import SOCKSProxyexcept ImportError: # pragma: nocover
class SOCKSProxy: # type: ignore def __init__(self, *args, **kwargs) -> None: # type: ignore raise RuntimeError( "Attempted to use SOCKS support, but the `socksio` package is not " "installed. Use 'pip install httpcore[socks]'." )
__all__ = [ "HTTPConnection", "ConnectionPool", "HTTPProxy", "HTTP11Connection", "HTTP2Connection", "ConnectionInterface", "SOCKSProxy",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222from __future__ import annotations
import itertoolsimport loggingimport sslimport typesimport typing
from .._backends.sync import SyncBackendfrom .._backends.base import SOCKET_OPTION, NetworkBackend, NetworkStreamfrom .._exceptions import ConnectError, ConnectTimeoutfrom .._models import Origin, Request, Responsefrom .._ssl import default_ssl_contextfrom .._synchronization import Lockfrom .._trace import Tracefrom .http11 import HTTP11Connectionfrom .interfaces import ConnectionInterface
RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc.
logger = logging.getLogger("httpcore.connection")
def exponential_backoff(factor: float) -> typing.Iterator[float]: """ Generate a geometric sequence that has a ratio of 2 and starts with 0.
For example: - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...` - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...` """ yield 0 for n in itertools.count(): yield factor * 2**n
class HTTPConnection(ConnectionInterface): def __init__( self, origin: Origin, ssl_context: ssl.SSLContext | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: NetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._origin = origin self._ssl_context = ssl_context self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._retries = retries self._local_address = local_address self._uds = uds
self._network_backend: NetworkBackend = ( SyncBackend() if network_backend is None else network_backend ) self._connection: ConnectionInterface | None = None self._connect_failed: bool = False self._request_lock = Lock() self._socket_options = socket_options
def handle_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection to {self._origin}" )
try: with self._request_lock: if self._connection is None: stream = self._connect(request)
ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" ) if http2_negotiated or (self._http2 and not self._http1): from .http2 import HTTP2Connection
self._connection = HTTP2Connection( origin=self._origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = HTTP11Connection( origin=self._origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) except BaseException as exc: self._connect_failed = True raise exc
return self._connection.handle_request(request)
def _connect(self, request: Request) -> NetworkStream: timeouts = request.extensions.get("timeout", {}) sni_hostname = request.extensions.get("sni_hostname", None) timeout = timeouts.get("connect", None)
retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
while True: try: if self._uds is None: kwargs = { "host": self._origin.host.decode("ascii"), "port": self._origin.port, "local_address": self._local_address, "timeout": timeout, "socket_options": self._socket_options, } with Trace("connect_tcp", logger, request, kwargs) as trace: stream = self._network_backend.connect_tcp(**kwargs) trace.return_value = stream else: kwargs = { "path": self._uds, "timeout": timeout, "socket_options": self._socket_options, } with Trace( "connect_unix_socket", logger, request, kwargs ) as trace: stream = self._network_backend.connect_unix_socket( **kwargs ) trace.return_value = stream
if self._origin.scheme in (b"https", b"wss"): ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": sni_hostname or self._origin.host.decode("ascii"), "timeout": timeout, } with Trace("start_tls", logger, request, kwargs) as trace: stream = stream.start_tls(**kwargs) trace.return_value = stream return stream except (ConnectError, ConnectTimeout): if retries_left <= 0: raise retries_left -= 1 delay = next(delays) with Trace("retry", logger, request, kwargs) as trace: self._network_backend.sleep(delay)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
def close(self) -> None: if self._connection is not None: with Trace("close", logger, None, {}): self._connection.close()
def is_available(self) -> bool: if self._connection is None: # If HTTP/2 support is enabled, and the resulting connection could # end up as HTTP/2 then we should indicate the connection as being # available to service multiple requests. return ( self._http2 and (self._origin.scheme == b"https" or not self._http1) and not self._connect_failed ) return self._connection.is_available()
def has_expired(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.has_expired()
def is_idle(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.is_idle()
def is_closed(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.is_closed()
def info(self) -> str: if self._connection is None: return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" return self._connection.info()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
def __enter__(self) -> HTTPConnection: return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: self.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420from __future__ import annotations
import sslimport sysimport typesimport typing
from .._backends.sync import SyncBackendfrom .._backends.base import SOCKET_OPTION, NetworkBackendfrom .._exceptions import ConnectionNotAvailable, UnsupportedProtocolfrom .._models import Origin, Proxy, Request, Responsefrom .._synchronization import Event, ShieldCancellation, ThreadLockfrom .connection import HTTPConnectionfrom .interfaces import ConnectionInterface, RequestInterface
class PoolRequest: def __init__(self, request: Request) -> None: self.request = request self.connection: ConnectionInterface | None = None self._connection_acquired = Event()
def assign_to_connection(self, connection: ConnectionInterface | None) -> None: self.connection = connection self._connection_acquired.set()
def clear_connection(self) -> None: self.connection = None self._connection_acquired = Event()
def wait_for_connection( self, timeout: float | None = None ) -> ConnectionInterface: if self.connection is None: self._connection_acquired.wait(timeout=timeout) assert self.connection is not None return self.connection
def is_queued(self) -> bool: return self.connection is None
class ConnectionPool(RequestInterface): """ A connection pool for making HTTP requests. """
def __init__( self, ssl_context: ssl.SSLContext | None = None, proxy: Proxy | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: NetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. socket_options: Socket options that have to be included in the TCP socket when the connection was established. """ self._ssl_context = ssl_context self._proxy = proxy self._max_connections = ( sys.maxsize if max_connections is None else max_connections ) self._max_keepalive_connections = ( sys.maxsize if max_keepalive_connections is None else max_keepalive_connections ) self._max_keepalive_connections = min( self._max_connections, self._max_keepalive_connections )
self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._retries = retries self._local_address = local_address self._uds = uds
self._network_backend = ( SyncBackend() if network_backend is None else network_backend ) self._socket_options = socket_options
# The mutable state on a connection pool is the queue of incoming requests, # and the set of connections that are servicing those requests. self._connections: list[ConnectionInterface] = [] self._requests: list[PoolRequest] = []
# We only mutate the state of the connection pool within an 'optional_thread_lock' # context. This holds a threading lock unless we're running in async mode, # in which case it is a no-op. self._optional_thread_lock = ThreadLock()
def create_connection(self, origin: Origin) -> ConnectionInterface: if self._proxy is not None: if self._proxy.url.scheme in (b"socks5", b"socks5h"): from .socks_proxy import Socks5Connection
return Socks5Connection( proxy_origin=self._proxy.url.origin, proxy_auth=self._proxy.auth, remote_origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, ) elif origin.scheme == b"http": from .http_proxy import ForwardHTTPConnection
return ForwardHTTPConnection( proxy_origin=self._proxy.url.origin, proxy_headers=self._proxy.headers, proxy_ssl_context=self._proxy.ssl_context, remote_origin=origin, keepalive_expiry=self._keepalive_expiry, network_backend=self._network_backend, ) from .http_proxy import TunnelHTTPConnection
return TunnelHTTPConnection( proxy_origin=self._proxy.url.origin, proxy_headers=self._proxy.headers, proxy_ssl_context=self._proxy.ssl_context, remote_origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
return HTTPConnection( origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, retries=self._retries, local_address=self._local_address, uds=self._uds, network_backend=self._network_backend, socket_options=self._socket_options, )
@property def connections(self) -> list[ConnectionInterface]: """ Return a list of the connections currently in the pool.
For example:
```python >>> pool.connections [ <HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 6]>, <HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 9]> , <HTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>, ] ``` """ return list(self._connections)
def handle_request(self, request: Request) -> Response: """ Send an HTTP request, and return an HTTP response.
This is the core implementation that is called into by `.request()` or `.stream()`. """ scheme = request.url.scheme.decode() if scheme == "": raise UnsupportedProtocol( "Request URL is missing an 'http://' or 'https://' protocol." ) if scheme not in ("http", "https", "ws", "wss"): raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{scheme}://'." )
timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("pool", None)
with self._optional_thread_lock: # Add the incoming request to our request queue. pool_request = PoolRequest(request) self._requests.append(pool_request)
try: while True: with self._optional_thread_lock: # Assign incoming requests to available connections, # closing or creating new connections as required. closing = self._assign_requests_to_connections() self._close_connections(closing)
# Wait until this request has an assigned connection. connection = pool_request.wait_for_connection(timeout=timeout)
try: # Send the request on the assigned connection. response = connection.handle_request( pool_request.request ) except ConnectionNotAvailable: # In some cases a connection may initially be available to # handle a request, but then become unavailable. # # In this case we clear the connection and try again. pool_request.clear_connection() else: break # pragma: nocover
except BaseException as exc: with self._optional_thread_lock: # For any exception or cancellation we remove the request from # the queue, and then re-assign requests to connections. self._requests.remove(pool_request) closing = self._assign_requests_to_connections()
self._close_connections(closing) raise exc from None
# Return the response. Note that in this case we still have to manage # the point at which the response is closed. assert isinstance(response.stream, typing.Iterable) return Response( status=response.status, headers=response.headers, content=PoolByteStream( stream=response.stream, pool_request=pool_request, pool=self ), extensions=response.extensions, )
def _assign_requests_to_connections(self) -> list[ConnectionInterface]: """ Manage the state of the connection pool, assigning incoming requests to connections as available.
Called whenever a new request is added or removed from the pool.
Any closing connections are returned, allowing the I/O for closing those connections to be handled seperately. """ closing_connections = []
# First we handle cleaning up any connections that are closed, # have expired their keep-alive, or surplus idle connections. for connection in list(self._connections): if connection.is_closed(): # log: "removing closed connection" self._connections.remove(connection) elif connection.has_expired(): # log: "closing expired connection" self._connections.remove(connection) closing_connections.append(connection) elif ( connection.is_idle() and len([connection.is_idle() for connection in self._connections]) > self._max_keepalive_connections ): # log: "closing idle connection" self._connections.remove(connection) closing_connections.append(connection)
# Assign queued requests to connections. queued_requests = [request for request in self._requests if request.is_queued()] for pool_request in queued_requests: origin = pool_request.request.url.origin available_connections = [ connection for connection in self._connections if connection.can_handle_request(origin) and connection.is_available() ] idle_connections = [ connection for connection in self._connections if connection.is_idle() ]
# There are three cases for how we may be able to handle the request: # # 1. There is an existing connection that can handle the request. # 2. We can create a new connection to handle the request. # 3. We can close an idle connection and then create a new connection # to handle the request. if available_connections: # log: "reusing existing connection" connection = available_connections[0] pool_request.assign_to_connection(connection) elif len(self._connections) < self._max_connections: # log: "creating new connection" connection = self.create_connection(origin) self._connections.append(connection) pool_request.assign_to_connection(connection) elif idle_connections: # log: "closing idle connection" connection = idle_connections[0] self._connections.remove(connection) closing_connections.append(connection) # log: "creating new connection" connection = self.create_connection(origin) self._connections.append(connection) pool_request.assign_to_connection(connection)
return closing_connections
def _close_connections(self, closing: list[ConnectionInterface]) -> None: # Close connections which have been removed from the pool. with ShieldCancellation(): for connection in closing: connection.close()
def close(self) -> None: # Explicitly close the connection pool. # Clears all existing requests and connections. with self._optional_thread_lock: closing_connections = list(self._connections) self._connections = [] self._close_connections(closing_connections)
def __enter__(self) -> ConnectionPool: return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: self.close()
def __repr__(self) -> str: class_name = self.__class__.__name__ with self._optional_thread_lock: request_is_queued = [request.is_queued() for request in self._requests] connection_is_idle = [ connection.is_idle() for connection in self._connections ]
num_active_requests = request_is_queued.count(False) num_queued_requests = request_is_queued.count(True) num_active_connections = connection_is_idle.count(False) num_idle_connections = connection_is_idle.count(True)
requests_info = ( f"Requests: {num_active_requests} active, {num_queued_requests} queued" ) connection_info = ( f"Connections: {num_active_connections} active, {num_idle_connections} idle" )
return f"<{class_name} [{requests_info} | {connection_info}]>"
class PoolByteStream: def __init__( self, stream: typing.Iterable[bytes], pool_request: PoolRequest, pool: ConnectionPool, ) -> None: self._stream = stream self._pool_request = pool_request self._pool = pool self._closed = False
def __iter__(self) -> typing.Iterator[bytes]: try: for part in self._stream: yield part except BaseException as exc: self.close() raise exc from None
def close(self) -> None: if not self._closed: self._closed = True with ShieldCancellation(): if hasattr(self._stream, "close"): self._stream.close()
with self._pool._optional_thread_lock: self._pool._requests.remove(self._pool_request) closing = self._pool._assign_requests_to_connections()
self._pool._close_connections(closing)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379from __future__ import annotations
import enumimport loggingimport sslimport timeimport typesimport typing
import h11
from .._backends.base import NetworkStreamfrom .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError, WriteError, map_exceptions,)from .._models import Origin, Request, Responsefrom .._synchronization import Lock, ShieldCancellationfrom .._trace import Tracefrom .interfaces import ConnectionInterface
logger = logging.getLogger("httpcore.http11")
# A subset of `h11.Event` types supported by `_send_event`H11SendEvent = typing.Union[ h11.Request, h11.Data, h11.EndOfMessage,]
class HTTPConnectionState(enum.IntEnum): NEW = 0 ACTIVE = 1 IDLE = 2 CLOSED = 3
class HTTP11Connection(ConnectionInterface): READ_NUM_BYTES = 64 * 1024 MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024
def __init__( self, origin: Origin, stream: NetworkStream, keepalive_expiry: float | None = None, ) -> None: self._origin = origin self._network_stream = stream self._keepalive_expiry: float | None = keepalive_expiry self._expire_at: float | None = None self._state = HTTPConnectionState.NEW self._state_lock = Lock() self._request_count = 0 self._h11_state = h11.Connection( our_role=h11.CLIENT, max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE, )
def handle_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection " f"to {self._origin}" )
with self._state_lock: if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE): self._request_count += 1 self._state = HTTPConnectionState.ACTIVE self._expire_at = None else: raise ConnectionNotAvailable()
try: kwargs = {"request": request} try: with Trace( "send_request_headers", logger, request, kwargs ) as trace: self._send_request_headers(**kwargs) with Trace("send_request_body", logger, request, kwargs) as trace: self._send_request_body(**kwargs) except WriteError: # If we get a write error while we're writing the request, # then we supress this error and move on to attempting to # read the response. Servers can sometimes close the request # pre-emptively and then respond with a well formed HTTP # error response. pass
with Trace( "receive_response_headers", logger, request, kwargs ) as trace: ( http_version, status, reason_phrase, headers, trailing_data, ) = self._receive_response_headers(**kwargs) trace.return_value = ( http_version, status, reason_phrase, headers, )
network_stream = self._network_stream
# CONNECT or Upgrade request if (status == 101) or ( (request.method == b"CONNECT") and (200 <= status < 300) ): network_stream = HTTP11UpgradeStream(network_stream, trailing_data)
return Response( status=status, headers=headers, content=HTTP11ConnectionByteStream(self, request), extensions={ "http_version": http_version, "reason_phrase": reason_phrase, "network_stream": network_stream, }, ) except BaseException as exc: with ShieldCancellation(): with Trace("response_closed", logger, request) as trace: self._response_closed() raise exc
# Sending the request...
def _send_request_headers(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
with map_exceptions({h11.LocalProtocolError: LocalProtocolError}): event = h11.Request( method=request.method, target=request.url.target, headers=request.headers, ) self._send_event(event, timeout=timeout)
def _send_request_body(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
assert isinstance(request.stream, typing.Iterable) for chunk in request.stream: event = h11.Data(data=chunk) self._send_event(event, timeout=timeout)
self._send_event(h11.EndOfMessage(), timeout=timeout)
def _send_event(self, event: h11.Event, timeout: float | None = None) -> None: bytes_to_send = self._h11_state.send(event) if bytes_to_send is not None: self._network_stream.write(bytes_to_send, timeout=timeout)
# Receiving the response...
def _receive_response_headers( self, request: Request ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
while True: event = self._receive_event(timeout=timeout) if isinstance(event, h11.Response): break if ( isinstance(event, h11.InformationalResponse) and event.status_code == 101 ): break
http_version = b"HTTP/" + event.http_version
# h11 version 0.11+ supports a `raw_items` interface to get the # raw header casing, rather than the enforced lowercase headers. headers = event.headers.raw_items()
trailing_data, _ = self._h11_state.trailing_data
return http_version, event.status_code, event.reason, headers, trailing_data
def _receive_response_body( self, request: Request ) -> typing.Iterator[bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
while True: event = self._receive_event(timeout=timeout) if isinstance(event, h11.Data): yield bytes(event.data) elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)): break
def _receive_event( self, timeout: float | None = None ) -> h11.Event | type[h11.PAUSED]: while True: with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}): event = self._h11_state.next_event()
if event is h11.NEED_DATA: data = self._network_stream.read( self.READ_NUM_BYTES, timeout=timeout )
# If we feed this case through h11 we'll raise an exception like: # # httpcore.RemoteProtocolError: can't handle event type # ConnectionClosed when role=SERVER and state=SEND_RESPONSE # # Which is accurate, but not very informative from an end-user # perspective. Instead we handle this case distinctly and treat # it as a ConnectError. if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE: msg = "Server disconnected without sending a response." raise RemoteProtocolError(msg)
self._h11_state.receive_data(data) else: # mypy fails to narrow the type in the above if statement above return event # type: ignore[return-value]
def _response_closed(self) -> None: with self._state_lock: if ( self._h11_state.our_state is h11.DONE and self._h11_state.their_state is h11.DONE ): self._state = HTTPConnectionState.IDLE self._h11_state.start_next_cycle() if self._keepalive_expiry is not None: now = time.monotonic() self._expire_at = now + self._keepalive_expiry else: self.close()
# Once the connection is no longer required...
def close(self) -> None: # Note that this method unilaterally closes the connection, and does # not have any kind of locking in place around it. self._state = HTTPConnectionState.CLOSED self._network_stream.close()
# The ConnectionInterface methods provide information about the state of # the connection, allowing for a connection pooling implementation to # determine when to reuse and when to close the connection...
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
def is_available(self) -> bool: # Note that HTTP/1.1 connections in the "NEW" state are not treated as # being "available". The control flow which created the connection will # be able to send an outgoing request, but the connection will not be # acquired from the connection pool for any other request. return self._state == HTTPConnectionState.IDLE
def has_expired(self) -> bool: now = time.monotonic() keepalive_expired = self._expire_at is not None and now > self._expire_at
# If the HTTP connection is idle but the socket is readable, then the # only valid state is that the socket is about to return b"", indicating # a server-initiated disconnect. server_disconnected = ( self._state == HTTPConnectionState.IDLE and self._network_stream.get_extra_info("is_readable") )
return keepalive_expired or server_disconnected
def is_idle(self) -> bool: return self._state == HTTPConnectionState.IDLE
def is_closed(self) -> bool: return self._state == HTTPConnectionState.CLOSED
def info(self) -> str: origin = str(self._origin) return ( f"{origin!r}, HTTP/1.1, {self._state.name}, " f"Request Count: {self._request_count}" )
def __repr__(self) -> str: class_name = self.__class__.__name__ origin = str(self._origin) return ( f"<{class_name} [{origin!r}, {self._state.name}, " f"Request Count: {self._request_count}]>" )
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
def __enter__(self) -> HTTP11Connection: return self
def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: self.close()
class HTTP11ConnectionByteStream: def __init__(self, connection: HTTP11Connection, request: Request) -> None: self._connection = connection self._request = request self._closed = False
def __iter__(self) -> typing.Iterator[bytes]: kwargs = {"request": self._request} try: with Trace("receive_response_body", logger, self._request, kwargs): for chunk in self._connection._receive_response_body(**kwargs): yield chunk except BaseException as exc: # If we get an exception while streaming the response, # we want to close the response (and possibly the connection) # before raising that exception. with ShieldCancellation(): self.close() raise exc
def close(self) -> None: if not self._closed: self._closed = True with Trace("response_closed", logger, self._request): self._connection._response_closed()
class HTTP11UpgradeStream(NetworkStream): def __init__(self, stream: NetworkStream, leading_data: bytes) -> None: self._stream = stream self._leading_data = leading_data
def read(self, max_bytes: int, timeout: float | None = None) -> bytes: if self._leading_data: buffer = self._leading_data[:max_bytes] self._leading_data = self._leading_data[max_bytes:] return buffer else: return self._stream.read(max_bytes, timeout)
def write(self, buffer: bytes, timeout: float | None = None) -> None: self._stream.write(buffer, timeout)
def close(self) -> None: self._stream.close()
def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> NetworkStream: return self._stream.start_tls(ssl_context, server_hostname, timeout)
def get_extra_info(self, info: str) -> typing.Any: return self._stream.get_extra_info(info)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107Metadata-Version: 2.4Name: packagingVersion: 26.0Summary: Core utilities for Python packagesAuthor-email: Donald Stufft <donald@stufft.io>Requires-Python: >=3.8Description-Content-Type: text/x-rstLicense-Expression: Apache-2.0 OR BSD-2-ClauseClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Typing :: TypedLicense-File: LICENSELicense-File: LICENSE.APACHELicense-File: LICENSE.BSDProject-URL: Documentation, https://packaging.pypa.io/Project-URL: Source, https://github.com/pypa/packaging
packaging=========
.. start-intro
Reusable core utilities for various Python Packaging`interoperability specifications <https://packaging.python.org/specifications/>`_.
This library provides utilities that implement the interoperabilityspecifications which have clearly one correct behaviour (eg: :pep:`440`)or benefit greatly from having a single shared implementation (eg: :pep:`425`).
.. end-intro
The ``packaging`` project includes the following: version handling, specifiers,markers, requirements, tags, metadata, lockfiles, utilities.
Documentation-------------
The `documentation`_ provides information and the API for the following:
- Version Handling- Specifiers- Markers- Requirements- Tags- Metadata- Lockfiles- Utilities
Installation------------
Use ``pip`` to install these utilities::
pip install packaging
The ``packaging`` library uses calendar-based versioning (``YY.N``).
Discussion----------
If you run into bugs, you can file them in our `issue tracker`_.
You can also join ``#pypa`` on Freenode to ask questions or get involved.
.. _`documentation`: https://packaging.pypa.io/.. _`issue tracker`: https://github.com/pypa/packaging/issues
Code of Conduct---------------
Everyone interacting in the packaging project's codebases, issue trackers, chatrooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
Contributing------------
The ``CONTRIBUTING.rst`` file outlines how to contribute to this project aswell as how to report a potential security issue. The documentation for thisproject also covers information about `project development`_ and `security`_.
.. _`project development`: https://packaging.pypa.io/en/latest/development/.. _`security`: https://packaging.pypa.io/en/latest/security/
Project History---------------
Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ forrecent changes and project history.
.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/
123456789101112131415161718192021222324packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309packaging-26.0.dist-info/RECORD,,1234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any123This software is made available under the terms of *either* of the licensesfound in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is madeunder the terms of *both* these licenses.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS1234567891011121314151617181920212223Copyright (c) Donald Stufft and individual contributors.All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
__title__ = "packaging"__summary__ = "Core utilities for Python packages"__uri__ = "https://github.com/pypa/packaging"
__version__ = "26.0"
__author__ = "Donald Stufft and individual contributors"__email__ = "donald@stufft.io"
__license__ = "BSD-2-Clause or Apache-2.0"__copyright__ = f"2014 {__author__}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""ELF file parser.
This provides a class ``ELFFile`` that parses an ELF executable in a similarinterface to ``ZipFile``. Only the read interface is implemented.
ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html"""
from __future__ import annotations
import enumimport osimport structfrom typing import IO
class ELFInvalid(ValueError): pass
class EIClass(enum.IntEnum): C32 = 1 C64 = 2
class EIData(enum.IntEnum): Lsb = 1 Msb = 2
class EMachine(enum.IntEnum): I386 = 3 S390 = 22 Arm = 40 X8664 = 62 AArc64 = 183
class ELFFile: """ Representation of an ELF executable. """
def __init__(self, f: IO[bytes]) -> None: self._f = f
try: ident = self._read("16B") except struct.error as e: raise ELFInvalid("unable to parse identification") from e magic = bytes(ident[:4]) if magic != b"\x7fELF": raise ELFInvalid(f"invalid magic: {magic!r}")
self.capacity = ident[4] # Format for program header (bitness). self.encoding = ident[5] # Data structure encoding (endianness).
try: # e_fmt: Format for program header. # p_fmt: Format for section header. # p_idx: Indexes to find p_type, p_offset, and p_filesz. e_fmt, self._p_fmt, self._p_idx = { (1, 1): ("<HHIIIIIHHH", "<IIIIIIII", (0, 1, 4)), # 32-bit LSB. (1, 2): (">HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. (2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB. (2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. }[(self.capacity, self.encoding)] except KeyError as e: raise ELFInvalid( f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})" ) from e
try: ( _, self.machine, # Architecture type. _, _, self._e_phoff, # Offset of program header. _, self.flags, # Processor-specific flags. _, self._e_phentsize, # Size of section. self._e_phnum, # Number of sections. ) = self._read(e_fmt) except struct.error as e: raise ELFInvalid("unable to parse machine and section information") from e
def _read(self, fmt: str) -> tuple[int, ...]: return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
@property def interpreter(self) -> str | None: """ The path recorded in the ``PT_INTERP`` section header. """ for index in range(self._e_phnum): self._f.seek(self._e_phoff + self._e_phentsize * index) try: data = self._read(self._p_fmt) except struct.error: continue if data[self._p_idx[0]] != 3: # Not PT_INTERP. continue self._f.seek(data[self._p_idx[1]]) return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262from __future__ import annotations
import collectionsimport contextlibimport functoolsimport osimport reimport sysimport warningsfrom typing import Generator, Iterator, NamedTuple, Sequence
from ._elffile import EIClass, EIData, ELFFile, EMachine
EF_ARM_ABIMASK = 0xFF000000EF_ARM_ABI_VER5 = 0x05000000EF_ARM_ABI_FLOAT_HARD = 0x00000400
_ALLOWED_ARCHS = { "x86_64", "aarch64", "ppc64", "ppc64le", "s390x", "loongarch64", "riscv64",}
# `os.PathLike` not a generic type until Python 3.9, so sticking with `str`# as the type for `path` until then.@contextlib.contextmanagerdef _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: try: with open(path, "rb") as f: yield ELFFile(f) except (OSError, TypeError, ValueError): yield None
def _is_linux_armhf(executable: str) -> bool: # hard-float ABI can be detected from the ELF header of the running # process # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf with _parse_elf(executable) as f: return ( f is not None and f.capacity == EIClass.C32 and f.encoding == EIData.Lsb and f.machine == EMachine.Arm and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD )
def _is_linux_i686(executable: str) -> bool: with _parse_elf(executable) as f: return ( f is not None and f.capacity == EIClass.C32 and f.encoding == EIData.Lsb and f.machine == EMachine.I386 )
def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: if "armv7l" in archs: return _is_linux_armhf(executable) if "i686" in archs: return _is_linux_i686(executable) return any(arch in _ALLOWED_ARCHS for arch in archs)
# If glibc ever changes its major version, we need to know what the last# minor version was, so we can build the complete list of all versions.# For now, guess what the highest minor version might be, assume it will# be 50 for testing. Once this actually happens, update the dictionary# with the actual value._LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
class _GLibCVersion(NamedTuple): major: int minor: int
def _glibc_version_string_confstr() -> str | None: """ Primary implementation of glibc_version_string using os.confstr. """ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platform module. # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 try: # Should be a string like "glibc 2.17". version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") assert version_string is not None _, version = version_string.rsplit() except (AssertionError, AttributeError, OSError, ValueError): # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... return None return version
def _glibc_version_string_ctypes() -> str | None: """ Fallback implementation of glibc_version_string using ctypes. """ try: import ctypes # noqa: PLC0415 except ImportError: return None
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. # # We must also handle the special case where the executable is not a # dynamically linked executable. This can occur when using musl libc, # for example. In this situation, dlopen() will error, leading to an # OSError. Interestingly, at least in the case of musl, there is no # errno set on the OSError. The single string argument used to construct # OSError comes from libc itself and is therefore not portable to # hard code here. In any case, failure to call dlopen() means we # can proceed, so we bail on our attempt. try: process_namespace = ctypes.CDLL(None) except OSError: return None
try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return None
# Call gnu_get_libc_version, which returns a string like "2.5" gnu_get_libc_version.restype = ctypes.c_char_p version_str: str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): version_str = version_str.decode("ascii")
return version_str
def _glibc_version_string() -> str | None: """Returns glibc version string, or None if not using glibc.""" return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
def _parse_glibc_version(version_str: str) -> _GLibCVersion: """Parse glibc version.
We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked versions of glibc (e.g. Linaro's version of glibc uses version strings like "2.20-2014.11"). See gh-3588. """ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str) if not m: warnings.warn( f"Expected glibc version with 2 components major.minor, got: {version_str}", RuntimeWarning, stacklevel=2, ) return _GLibCVersion(-1, -1) return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
@functools.lru_cachedef _get_glibc_version() -> _GLibCVersion: version_str = _glibc_version_string() if version_str is None: return _GLibCVersion(-1, -1) return _parse_glibc_version(version_str)
# From PEP 513, PEP 600def _is_compatible(arch: str, version: _GLibCVersion) -> bool: sys_glibc = _get_glibc_version() if sys_glibc < version: return False # Check for presence of _manylinux module. try: import _manylinux # noqa: PLC0415 except ImportError: return True if hasattr(_manylinux, "manylinux_compatible"): result = _manylinux.manylinux_compatible(version[0], version[1], arch) if result is not None: return bool(result) return True if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"): return bool(_manylinux.manylinux1_compatible) if version == _GLibCVersion(2, 12) and hasattr( _manylinux, "manylinux2010_compatible" ): return bool(_manylinux.manylinux2010_compatible) if version == _GLibCVersion(2, 17) and hasattr( _manylinux, "manylinux2014_compatible" ): return bool(_manylinux.manylinux2014_compatible) return True
_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { # CentOS 7 w/ glibc 2.17 (PEP 599) _GLibCVersion(2, 17): "manylinux2014", # CentOS 6 w/ glibc 2.12 (PEP 571) _GLibCVersion(2, 12): "manylinux2010", # CentOS 5 w/ glibc 2.5 (PEP 513) _GLibCVersion(2, 5): "manylinux1",}
def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate manylinux tags compatible to the current platform.
:param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be manylinux-compatible.
:returns: An iterator of compatible manylinux tags. """ if not _have_compatible_abi(sys.executable, archs): return # Oldest glibc to be supported regardless of architecture is (2, 17). too_old_glibc2 = _GLibCVersion(2, 16) if set(archs) & {"x86_64", "i686"}: # On x86/i686 also oldest glibc to be supported is (2, 5). too_old_glibc2 = _GLibCVersion(2, 4) current_glibc = _GLibCVersion(*_get_glibc_version()) glibc_max_list = [current_glibc] # We can assume compatibility across glibc major versions. # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 # # Build a list of maximum glibc versions so that we can # output the canonical list of all glibc from current_glibc # down to too_old_glibc2, including all intermediary versions. for glibc_major in range(current_glibc.major - 1, 1, -1): glibc_minor = _LAST_GLIBC_MINOR[glibc_major] glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) for arch in archs: for glibc_max in glibc_max_list: if glibc_max.major == too_old_glibc2.major: min_minor = too_old_glibc2.minor else: # For other glibc major versions oldest supported is (x, 0). min_minor = -1 for glibc_minor in range(glibc_max.minor, min_minor, -1): glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) if _is_compatible(arch, glibc_version): yield "manylinux_{}_{}_{}".format(*glibc_version, arch)
# Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version): yield f"{legacy_tag}_{arch}"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""PEP 656 support.
This module implements logic to detect if the currently running Python islinked against musl, and what musl version is used."""
from __future__ import annotations
import functoolsimport reimport subprocessimport sysfrom typing import Iterator, NamedTuple, Sequence
from ._elffile import ELFFile
class _MuslVersion(NamedTuple): major: int minor: int
def _parse_musl_version(output: str) -> _MuslVersion | None: lines = [n for n in (n.strip() for n in output.splitlines()) if n] if len(lines) < 2 or lines[0][:4] != "musl": return None m = re.match(r"Version (\d+)\.(\d+)", lines[1]) if not m: return None return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
@functools.lru_cachedef _get_musl_version(executable: str) -> _MuslVersion | None: """Detect currently-running musl runtime version.
This is done by checking the specified executable's dynamic linking information, and invoking the loader to parse its output for a version string. If the loader is musl, the output would be something like::
musl libc (x86_64) Version 1.2.2 Dynamic Program Loader """ try: with open(executable, "rb") as f: ld = ELFFile(f).interpreter except (OSError, TypeError, ValueError): return None if ld is None or "musl" not in ld: return None proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True) return _parse_musl_version(proc.stderr)
def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate musllinux tags compatible to the current platform.
:param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be musllinux-compatible.
:returns: An iterator of compatible musllinux tags. """ sys_musl = _get_musl_version(sys.executable) if sys_musl is None: # Python not dynamically linked against musl. return for arch in archs: for minor in range(sys_musl.minor, -1, -1): yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
if __name__ == "__main__": # pragma: no cover import sysconfig
plat = sysconfig.get_platform() assert plat.startswith("linux-"), "not linux"
print("plat:", plat) print("musl:", _get_musl_version(sys.executable)) print("tags:", end=" ") for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): print(t, end="\n ")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365"""Handwritten parser of dependency specifiers.
The docstring for each __parse_* function contains EBNF-inspired grammar representingthe implementation."""
from __future__ import annotations
import astfrom typing import List, Literal, NamedTuple, Sequence, Tuple, Union
from ._tokenizer import DEFAULT_RULES, Tokenizer
class Node: __slots__ = ("value",)
def __init__(self, value: str) -> None: self.value = value
def __str__(self) -> str: return self.value
def __repr__(self) -> str: return f"<{self.__class__.__name__}({self.value!r})>"
def serialize(self) -> str: raise NotImplementedError
class Variable(Node): __slots__ = ()
def serialize(self) -> str: return str(self)
class Value(Node): __slots__ = ()
def serialize(self) -> str: return f'"{self}"'
class Op(Node): __slots__ = ()
def serialize(self) -> str: return str(self)
MarkerLogical = Literal["and", "or"]MarkerVar = Union[Variable, Value]MarkerItem = Tuple[MarkerVar, Op, MarkerVar]MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
class ParsedRequirement(NamedTuple): name: str url: str extras: list[str] specifier: str marker: MarkerList | None
# --------------------------------------------------------------------------------------# Recursive descent parser for dependency specifier# --------------------------------------------------------------------------------------def parse_requirement(source: str) -> ParsedRequirement: return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: """ requirement = WS? IDENTIFIER WS? extras WS? requirement_details """ tokenizer.consume("WS")
name_token = tokenizer.expect( "IDENTIFIER", expected="package name at the start of dependency specifier" ) name = name_token.text tokenizer.consume("WS")
extras = _parse_extras(tokenizer) tokenizer.consume("WS")
url, specifier, marker = _parse_requirement_details(tokenizer) tokenizer.expect("END", expected="end of dependency specifier")
return ParsedRequirement(name, url, extras, specifier, marker)
def _parse_requirement_details( tokenizer: Tokenizer,) -> tuple[str, str, MarkerList | None]: """ requirement_details = AT URL (WS requirement_marker?)? | specifier WS? (requirement_marker)? """
specifier = "" url = "" marker = None
if tokenizer.check("AT"): tokenizer.read() tokenizer.consume("WS")
url_start = tokenizer.position url = tokenizer.expect("URL", expected="URL after @").text if tokenizer.check("END", peek=True): return (url, specifier, marker)
tokenizer.expect("WS", expected="whitespace after URL")
# The input might end after whitespace. if tokenizer.check("END", peek=True): return (url, specifier, marker)
marker = _parse_requirement_marker( tokenizer, span_start=url_start, expected="semicolon (after URL and whitespace)", ) else: specifier_start = tokenizer.position specifier = _parse_specifier(tokenizer) tokenizer.consume("WS")
if tokenizer.check("END", peek=True): return (url, specifier, marker)
marker = _parse_requirement_marker( tokenizer, span_start=specifier_start, expected=( "comma (within version specifier), semicolon (after version specifier)" if specifier else "semicolon (after name with no version specifier)" ), )
return (url, specifier, marker)
def _parse_requirement_marker( tokenizer: Tokenizer, *, span_start: int, expected: str) -> MarkerList: """ requirement_marker = SEMICOLON marker WS? """
if not tokenizer.check("SEMICOLON"): tokenizer.raise_syntax_error( f"Expected {expected} or end", span_start=span_start, span_end=None, ) tokenizer.read()
marker = _parse_marker(tokenizer) tokenizer.consume("WS")
return marker
def _parse_extras(tokenizer: Tokenizer) -> list[str]: """ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? """ if not tokenizer.check("LEFT_BRACKET", peek=True): return []
with tokenizer.enclosing_tokens( "LEFT_BRACKET", "RIGHT_BRACKET", around="extras", ): tokenizer.consume("WS") extras = _parse_extras_list(tokenizer) tokenizer.consume("WS")
return extras
def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: """ extras_list = identifier (wsp* ',' wsp* identifier)* """ extras: list[str] = []
if not tokenizer.check("IDENTIFIER"): return extras
extras.append(tokenizer.read().text)
while True: tokenizer.consume("WS") if tokenizer.check("IDENTIFIER", peek=True): tokenizer.raise_syntax_error("Expected comma between extra names") elif not tokenizer.check("COMMA"): break
tokenizer.read() tokenizer.consume("WS")
extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") extras.append(extra_token.text)
return extras
def _parse_specifier(tokenizer: Tokenizer) -> str: """ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS | WS? version_many WS? """ with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="version specifier", ): tokenizer.consume("WS") parsed_specifiers = _parse_version_many(tokenizer) tokenizer.consume("WS")
return parsed_specifiers
def _parse_version_many(tokenizer: Tokenizer) -> str: """ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? """ parsed_specifiers = "" while tokenizer.check("SPECIFIER"): span_start = tokenizer.position parsed_specifiers += tokenizer.read().text if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): tokenizer.raise_syntax_error( ".* suffix can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position + 1, ) if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): tokenizer.raise_syntax_error( "Local version label can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position, ) tokenizer.consume("WS") if not tokenizer.check("COMMA"): break parsed_specifiers += tokenizer.read().text tokenizer.consume("WS")
return parsed_specifiers
# --------------------------------------------------------------------------------------# Recursive descent parser for marker expression# --------------------------------------------------------------------------------------def parse_marker(source: str) -> MarkerList: return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: retval = _parse_marker(tokenizer) tokenizer.expect("END", expected="end of marker expression") return retval
def _parse_marker(tokenizer: Tokenizer) -> MarkerList: """ marker = marker_atom (BOOLOP marker_atom)+ """ expression = [_parse_marker_atom(tokenizer)] while tokenizer.check("BOOLOP"): token = tokenizer.read() expr_right = _parse_marker_atom(tokenizer) expression.extend((token.text, expr_right)) return expression
def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: """ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? | WS? marker_item WS? """
tokenizer.consume("WS") if tokenizer.check("LEFT_PARENTHESIS", peek=True): with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="marker expression", ): tokenizer.consume("WS") marker: MarkerAtom = _parse_marker(tokenizer) tokenizer.consume("WS") else: marker = _parse_marker_item(tokenizer) tokenizer.consume("WS") return marker
def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: """ marker_item = WS? marker_var WS? marker_op WS? marker_var WS? """ tokenizer.consume("WS") marker_var_left = _parse_marker_var(tokenizer) tokenizer.consume("WS") marker_op = _parse_marker_op(tokenizer) tokenizer.consume("WS") marker_var_right = _parse_marker_var(tokenizer) tokenizer.consume("WS") return (marker_var_left, marker_op, marker_var_right)
def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503 """ marker_var = VARIABLE | QUOTED_STRING """ if tokenizer.check("VARIABLE"): return process_env_var(tokenizer.read().text.replace(".", "_")) elif tokenizer.check("QUOTED_STRING"): return process_python_str(tokenizer.read().text) else: tokenizer.raise_syntax_error( message="Expected a marker variable or quoted string" )
def process_env_var(env_var: str) -> Variable: if env_var in ("platform_python_implementation", "python_implementation"): return Variable("platform_python_implementation") else: return Variable(env_var)
def process_python_str(python_str: str) -> Value: value = ast.literal_eval(python_str) return Value(str(value))
def _parse_marker_op(tokenizer: Tokenizer) -> Op: """ marker_op = IN | NOT IN | OP """ if tokenizer.check("IN"): tokenizer.read() return Op("in") elif tokenizer.check("NOT"): tokenizer.read() tokenizer.expect("WS", expected="whitespace after 'not'") tokenizer.expect("IN", expected="'in' after 'not'") return Op("not in") elif tokenizer.check("OP"): return Op(tokenizer.read().text) else: return tokenizer.raise_syntax_error( "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
import typing
@typing.finalclass InfinityType: __slots__ = ()
def __repr__(self) -> str: return "Infinity"
def __hash__(self) -> int: return hash(repr(self))
def __lt__(self, other: object) -> bool: return False
def __le__(self, other: object) -> bool: return False
def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__)
def __gt__(self, other: object) -> bool: return True
def __ge__(self, other: object) -> bool: return True
def __neg__(self: object) -> "NegativeInfinityType": return NegativeInfinity
Infinity = InfinityType()
@typing.finalclass NegativeInfinityType: __slots__ = ()
def __repr__(self) -> str: return "-Infinity"
def __hash__(self) -> int: return hash(repr(self))
def __lt__(self, other: object) -> bool: return True
def __le__(self, other: object) -> bool: return True
def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__)
def __gt__(self, other: object) -> bool: return False
def __ge__(self, other: object) -> bool: return False
def __neg__(self: object) -> InfinityType: return Infinity
NegativeInfinity = NegativeInfinityType()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193from __future__ import annotations
import contextlibimport refrom dataclasses import dataclassfrom typing import Generator, Mapping, NoReturn
from .specifiers import Specifier
@dataclassclass Token: name: str text: str position: int
class ParserSyntaxError(Exception): """The provided source text could not be parsed correctly."""
def __init__( self, message: str, *, source: str, span: tuple[int, int], ) -> None: self.span = span self.message = message self.source = source
super().__init__()
def __str__(self) -> str: marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" return f"{self.message}\n {self.source}\n {marker}"
DEFAULT_RULES: dict[str, re.Pattern[str]] = { "LEFT_PARENTHESIS": re.compile(r"\("), "RIGHT_PARENTHESIS": re.compile(r"\)"), "LEFT_BRACKET": re.compile(r"\["), "RIGHT_BRACKET": re.compile(r"\]"), "SEMICOLON": re.compile(r";"), "COMMA": re.compile(r","), "QUOTED_STRING": re.compile( r""" ( ('[^']*') | ("[^"]*") ) """, re.VERBOSE, ), "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"), "BOOLOP": re.compile(r"\b(or|and)\b"), "IN": re.compile(r"\bin\b"), "NOT": re.compile(r"\bnot\b"), "VARIABLE": re.compile( r""" \b( python_version |python_full_version |os[._]name |sys[._]platform |platform_(release|system) |platform[._](version|machine|python_implementation) |python_implementation |implementation_(name|version) |extras? |dependency_groups )\b """, re.VERBOSE, ), "SPECIFIER": re.compile( Specifier._operator_regex_str + Specifier._version_regex_str, re.VERBOSE | re.IGNORECASE, ), "AT": re.compile(r"\@"), "URL": re.compile(r"[^ \t]+"), "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), "WS": re.compile(r"[ \t]+"), "END": re.compile(r"$"),}
class Tokenizer: """Context-sensitive token parsing.
Provides methods to examine the input stream to check whether the next token matches. """
def __init__( self, source: str, *, rules: Mapping[str, re.Pattern[str]], ) -> None: self.source = source self.rules = rules self.next_token: Token | None = None self.position = 0
def consume(self, name: str) -> None: """Move beyond provided token name, if at current position.""" if self.check(name): self.read()
def check(self, name: str, *, peek: bool = False) -> bool: """Check whether the next token has the provided name.
By default, if the check succeeds, the token *must* be read before another check. If `peek` is set to `True`, the token is not loaded and would need to be checked again. """ assert self.next_token is None, ( f"Cannot check for {name!r}, already have {self.next_token!r}" ) assert name in self.rules, f"Unknown token name: {name!r}"
expression = self.rules[name]
match = expression.match(self.source, self.position) if match is None: return False if not peek: self.next_token = Token(name, match[0], self.position) return True
def expect(self, name: str, *, expected: str) -> Token: """Expect a certain token name next, failing with a syntax error otherwise.
The token is *not* read. """ if not self.check(name): raise self.raise_syntax_error(f"Expected {expected}") return self.read()
def read(self) -> Token: """Consume the next token and return it.""" token = self.next_token assert token is not None
self.position += len(token.text) self.next_token = None
return token
def raise_syntax_error( self, message: str, *, span_start: int | None = None, span_end: int | None = None, ) -> NoReturn: """Raise ParserSyntaxError at the given position.""" span = ( self.position if span_start is None else span_start, self.position if span_end is None else span_end, ) raise ParserSyntaxError( message, source=self.source, span=span, )
@contextlib.contextmanager def enclosing_tokens( self, open_token: str, close_token: str, *, around: str ) -> Generator[None, None, None]: if self.check(open_token): open_position = self.position self.read() else: open_position = None
yield
if open_position is None: return
if not self.check(close_token): self.raise_syntax_error( f"Expected matching {close_token} for {open_token}, after {around}", span_start=open_position, )
self.read()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147######################################################################################### Adapted from:# https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py## MIT License## Copyright (c) 2017-present Ofek Lev <oss@ofek.dev>## Permission is hereby granted, free of charge, to any person obtaining a copy of this# software and associated documentation files (the "Software"), to deal in the Software# without restriction, including without limitation the rights to use, copy, modify,# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to the following# conditions:## The above copyright notice and this permission notice shall be included in all copies# or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.### With additional allowance of arbitrary `LicenseRef-` identifiers, not just# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`.########################################################################################from __future__ import annotations
import refrom typing import NewType, cast
from ._spdx import EXCEPTIONS, LICENSES
__all__ = [ "InvalidLicenseExpression", "NormalizedLicenseExpression", "canonicalize_license_expression",]
license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$")
NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str)
class InvalidLicenseExpression(ValueError): """Raised when a license-expression string is invalid
>>> canonicalize_license_expression("invalid") Traceback (most recent call last): ... packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid' """
def canonicalize_license_expression( raw_license_expression: str,) -> NormalizedLicenseExpression: if not raw_license_expression: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message)
# Pad any parentheses so tokenization can be achieved by merely splitting on # whitespace. license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ") licenseref_prefix = "LicenseRef-" license_refs = { ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :] for ref in license_expression.split() if ref.lower().startswith(licenseref_prefix.lower()) }
# Normalize to lower case so we can look up licenses/exceptions # and so boolean operators are Python-compatible. license_expression = license_expression.lower()
tokens = license_expression.split()
# Rather than implementing a parenthesis/boolean logic parser, create an # expression that Python can parse. Everything that is not involved with the # grammar itself is replaced with the placeholder `False` and the resultant # expression should become a valid Python expression. python_tokens = [] for token in tokens: if token not in {"or", "and", "with", "(", ")"}: python_tokens.append("False") elif token == "with": python_tokens.append("or") elif ( token == "(" and python_tokens and python_tokens[-1] not in {"or", "and", "("} ) or (token == ")" and python_tokens and python_tokens[-1] == "("): message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) else: python_tokens.append(token)
python_expression = " ".join(python_tokens) try: compile(python_expression, "", "eval") except SyntaxError: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) from None
# Take a final pass to check for unknown licenses/exceptions. normalized_tokens = [] for token in tokens: if token in {"or", "and", "with", "(", ")"}: normalized_tokens.append(token.upper()) continue
if normalized_tokens and normalized_tokens[-1] == "WITH": if token not in EXCEPTIONS: message = f"Unknown license exception: {token!r}" raise InvalidLicenseExpression(message)
normalized_tokens.append(EXCEPTIONS[token]["id"]) else: if token.endswith("+"): final_token = token[:-1] suffix = "+" else: final_token = token suffix = ""
if final_token.startswith("licenseref-"): if not license_ref_allowed.match(final_token): message = f"Invalid licenseref: {final_token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(license_refs[final_token] + suffix) else: if final_token not in LICENSES: message = f"Unknown license: {final_token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(LICENSES[final_token]["id"] + suffix)
normalized_expression = " ".join(normalized_tokens)
return cast( "NormalizedLicenseExpression", normalized_expression.replace("( ", "(").replace(" )", ")"), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
from __future__ import annotations
from typing import TypedDict
class SPDXLicense(TypedDict): id: str deprecated: bool
class SPDXException(TypedDict): id: str deprecated: bool
VERSION = '3.27.0'
LICENSES: dict[str, SPDXLicense] = { '0bsd': {'id': '0BSD', 'deprecated': False}, '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False}, 'aal': {'id': 'AAL', 'deprecated': False}, 'abstyles': {'id': 'Abstyles', 'deprecated': False}, 'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False}, 'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False}, 'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False}, 'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False}, 'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False}, 'adsl': {'id': 'ADSL', 'deprecated': False}, 'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False}, 'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False}, 'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False}, 'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False}, 'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False}, 'afmparse': {'id': 'Afmparse', 'deprecated': False}, 'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True}, 'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False}, 'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False}, 'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True}, 'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False}, 'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False}, 'aladdin': {'id': 'Aladdin', 'deprecated': False}, 'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False}, 'amdplpa': {'id': 'AMDPLPA', 'deprecated': False}, 'aml': {'id': 'AML', 'deprecated': False}, 'aml-glslang': {'id': 'AML-glslang', 'deprecated': False}, 'ampas': {'id': 'AMPAS', 'deprecated': False}, 'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False}, 'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False}, 'any-osi': {'id': 'any-OSI', 'deprecated': False}, 'any-osi-perl-modules': {'id': 'any-OSI-perl-modules', 'deprecated': False}, 'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False}, 'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False}, 'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False}, 'apafml': {'id': 'APAFML', 'deprecated': False}, 'apl-1.0': {'id': 'APL-1.0', 'deprecated': False}, 'app-s2p': {'id': 'App-s2p', 'deprecated': False}, 'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False}, 'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False}, 'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False}, 'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False}, 'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False}, 'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False}, 'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False}, 'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False}, 'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False}, 'artistic-dist': {'id': 'Artistic-dist', 'deprecated': False}, 'aspell-ru': {'id': 'Aspell-RU', 'deprecated': False}, 'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False}, 'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False}, 'baekmuk': {'id': 'Baekmuk', 'deprecated': False}, 'bahyph': {'id': 'Bahyph', 'deprecated': False}, 'barr': {'id': 'Barr', 'deprecated': False}, 'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False}, 'beerware': {'id': 'Beerware', 'deprecated': False}, 'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False}, 'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False}, 'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False}, 'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False}, 'blessing': {'id': 'blessing', 'deprecated': False}, 'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False}, 'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False}, 'boehm-gc-without-fee': {'id': 'Boehm-GC-without-fee', 'deprecated': False}, 'borceux': {'id': 'Borceux', 'deprecated': False}, 'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False}, 'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False}, 'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False}, 'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False}, 'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False}, 'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False}, 'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True}, 'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True}, 'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False}, 'bsd-2-clause-pkgconf-disclaimer': {'id': 'BSD-2-Clause-pkgconf-disclaimer', 'deprecated': False}, 'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False}, 'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False}, 'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False}, 'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False}, 'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False}, 'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False}, 'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False}, 'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False}, 'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False}, 'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False}, 'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False}, 'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False}, 'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False}, 'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False}, 'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False}, 'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False}, 'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False}, 'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False}, 'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False}, 'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False}, 'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False}, 'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False}, 'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False}, 'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False}, 'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False}, 'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False}, 'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False}, 'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False}, 'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False}, 'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False}, 'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True}, 'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False}, 'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False}, 'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False}, 'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False}, 'caldera': {'id': 'Caldera', 'deprecated': False}, 'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False}, 'catharon': {'id': 'Catharon', 'deprecated': False}, 'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False}, 'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False}, 'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False}, 'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False}, 'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False}, 'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False}, 'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False}, 'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False}, 'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False}, 'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False}, 'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False}, 'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False}, 'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False}, 'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False}, 'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False}, 'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False}, 'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False}, 'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False}, 'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False}, 'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False}, 'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False}, 'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False}, 'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False}, 'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False}, 'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False}, 'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False}, 'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False}, 'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False}, 'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False}, 'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False}, 'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False}, 'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False}, 'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False}, 'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False}, 'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False}, 'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False}, 'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False}, 'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False}, 'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False}, 'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False}, 'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False}, 'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False}, 'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False}, 'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False}, 'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False}, 'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False}, 'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False}, 'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False}, 'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False}, 'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False}, 'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False}, 'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False}, 'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False}, 'cc-pdm-1.0': {'id': 'CC-PDM-1.0', 'deprecated': False}, 'cc-sa-1.0': {'id': 'CC-SA-1.0', 'deprecated': False}, 'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False}, 'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False}, 'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False}, 'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False}, 'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False}, 'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False}, 'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False}, 'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False}, 'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False}, 'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False}, 'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False}, 'cecill-b': {'id': 'CECILL-B', 'deprecated': False}, 'cecill-c': {'id': 'CECILL-C', 'deprecated': False}, 'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False}, 'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False}, 'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False}, 'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False}, 'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False}, 'cfitsio': {'id': 'CFITSIO', 'deprecated': False}, 'check-cvs': {'id': 'check-cvs', 'deprecated': False}, 'checkmk': {'id': 'checkmk', 'deprecated': False}, 'clartistic': {'id': 'ClArtistic', 'deprecated': False}, 'clips': {'id': 'Clips', 'deprecated': False}, 'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False}, 'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False}, 'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False}, 'cnri-python': {'id': 'CNRI-Python', 'deprecated': False}, 'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False}, 'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False}, 'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False}, 'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False}, 'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False}, 'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False}, 'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False}, 'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False}, 'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False}, 'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False}, 'cronyx': {'id': 'Cronyx', 'deprecated': False}, 'crossword': {'id': 'Crossword', 'deprecated': False}, 'cryptoswift': {'id': 'CryptoSwift', 'deprecated': False}, 'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False}, 'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False}, 'cube': {'id': 'Cube', 'deprecated': False}, 'curl': {'id': 'curl', 'deprecated': False}, 'cve-tou': {'id': 'cve-tou', 'deprecated': False}, 'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False}, 'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False}, 'diffmark': {'id': 'diffmark', 'deprecated': False}, 'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False}, 'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False}, 'doc': {'id': 'DOC', 'deprecated': False}, 'docbook-dtd': {'id': 'DocBook-DTD', 'deprecated': False}, 'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False}, 'docbook-stylesheet': {'id': 'DocBook-Stylesheet', 'deprecated': False}, 'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False}, 'dotseqn': {'id': 'Dotseqn', 'deprecated': False}, 'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False}, 'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False}, 'dsdp': {'id': 'DSDP', 'deprecated': False}, 'dtoa': {'id': 'dtoa', 'deprecated': False}, 'dvipdfm': {'id': 'dvipdfm', 'deprecated': False}, 'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False}, 'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False}, 'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True}, 'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False}, 'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False}, 'egenix': {'id': 'eGenix', 'deprecated': False}, 'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False}, 'entessa': {'id': 'Entessa', 'deprecated': False}, 'epics': {'id': 'EPICS', 'deprecated': False}, 'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False}, 'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False}, 'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False}, 'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False}, 'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False}, 'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False}, 'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False}, 'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False}, 'eurosym': {'id': 'Eurosym', 'deprecated': False}, 'fair': {'id': 'Fair', 'deprecated': False}, 'fbm': {'id': 'FBM', 'deprecated': False}, 'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False}, 'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False}, 'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False}, 'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False}, 'freeimage': {'id': 'FreeImage', 'deprecated': False}, 'fsfap': {'id': 'FSFAP', 'deprecated': False}, 'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False}, 'fsful': {'id': 'FSFUL', 'deprecated': False}, 'fsfullr': {'id': 'FSFULLR', 'deprecated': False}, 'fsfullrsd': {'id': 'FSFULLRSD', 'deprecated': False}, 'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False}, 'fsl-1.1-alv2': {'id': 'FSL-1.1-ALv2', 'deprecated': False}, 'fsl-1.1-mit': {'id': 'FSL-1.1-MIT', 'deprecated': False}, 'ftl': {'id': 'FTL', 'deprecated': False}, 'furuseth': {'id': 'Furuseth', 'deprecated': False}, 'fwlw': {'id': 'fwlw', 'deprecated': False}, 'game-programming-gems': {'id': 'Game-Programming-Gems', 'deprecated': False}, 'gcr-docs': {'id': 'GCR-docs', 'deprecated': False}, 'gd': {'id': 'GD', 'deprecated': False}, 'generic-xts': {'id': 'generic-xts', 'deprecated': False}, 'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True}, 'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False}, 'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False}, 'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False}, 'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False}, 'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False}, 'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False}, 'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True}, 'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False}, 'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False}, 'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False}, 'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False}, 'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False}, 'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False}, 'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True}, 'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False}, 'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False}, 'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False}, 'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False}, 'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False}, 'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False}, 'giftware': {'id': 'Giftware', 'deprecated': False}, 'gl2ps': {'id': 'GL2PS', 'deprecated': False}, 'glide': {'id': 'Glide', 'deprecated': False}, 'glulxe': {'id': 'Glulxe', 'deprecated': False}, 'glwtpl': {'id': 'GLWTPL', 'deprecated': False}, 'gnuplot': {'id': 'gnuplot', 'deprecated': False}, 'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True}, 'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True}, 'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False}, 'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False}, 'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True}, 'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True}, 'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False}, 'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False}, 'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True}, 'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True}, 'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True}, 'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True}, 'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True}, 'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True}, 'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True}, 'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False}, 'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False}, 'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True}, 'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True}, 'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False}, 'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False}, 'gtkbook': {'id': 'gtkbook', 'deprecated': False}, 'gutmann': {'id': 'Gutmann', 'deprecated': False}, 'haskellreport': {'id': 'HaskellReport', 'deprecated': False}, 'hdf5': {'id': 'HDF5', 'deprecated': False}, 'hdparm': {'id': 'hdparm', 'deprecated': False}, 'hidapi': {'id': 'HIDAPI', 'deprecated': False}, 'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False}, 'hp-1986': {'id': 'HP-1986', 'deprecated': False}, 'hp-1989': {'id': 'HP-1989', 'deprecated': False}, 'hpnd': {'id': 'HPND', 'deprecated': False}, 'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False}, 'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False}, 'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False}, 'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False}, 'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False}, 'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False}, 'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False}, 'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False}, 'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False}, 'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False}, 'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False}, 'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False}, 'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False}, 'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False}, 'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False}, 'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False}, 'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False}, 'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False}, 'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False}, 'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False}, 'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False}, 'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False}, 'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False}, 'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False}, 'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False}, 'icu': {'id': 'ICU', 'deprecated': False}, 'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False}, 'ijg': {'id': 'IJG', 'deprecated': False}, 'ijg-short': {'id': 'IJG-short', 'deprecated': False}, 'imagemagick': {'id': 'ImageMagick', 'deprecated': False}, 'imatix': {'id': 'iMatix', 'deprecated': False}, 'imlib2': {'id': 'Imlib2', 'deprecated': False}, 'info-zip': {'id': 'Info-ZIP', 'deprecated': False}, 'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False}, 'innosetup': {'id': 'InnoSetup', 'deprecated': False}, 'intel': {'id': 'Intel', 'deprecated': False}, 'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False}, 'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False}, 'ipa': {'id': 'IPA', 'deprecated': False}, 'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False}, 'isc': {'id': 'ISC', 'deprecated': False}, 'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False}, 'jam': {'id': 'Jam', 'deprecated': False}, 'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False}, 'jove': {'id': 'jove', 'deprecated': False}, 'jpl-image': {'id': 'JPL-image', 'deprecated': False}, 'jpnic': {'id': 'JPNIC', 'deprecated': False}, 'json': {'id': 'JSON', 'deprecated': False}, 'kastrup': {'id': 'Kastrup', 'deprecated': False}, 'kazlib': {'id': 'Kazlib', 'deprecated': False}, 'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False}, 'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False}, 'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False}, 'latex2e': {'id': 'Latex2e', 'deprecated': False}, 'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False}, 'leptonica': {'id': 'Leptonica', 'deprecated': False}, 'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True}, 'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True}, 'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False}, 'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False}, 'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True}, 'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True}, 'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False}, 'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False}, 'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True}, 'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True}, 'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False}, 'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False}, 'lgpllr': {'id': 'LGPLLR', 'deprecated': False}, 'libpng': {'id': 'Libpng', 'deprecated': False}, 'libpng-1.6.35': {'id': 'libpng-1.6.35', 'deprecated': False}, 'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False}, 'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False}, 'libtiff': {'id': 'libtiff', 'deprecated': False}, 'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False}, 'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False}, 'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False}, 'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False}, 'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False}, 'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False}, 'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False}, 'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False}, 'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False}, 'loop': {'id': 'LOOP', 'deprecated': False}, 'lpd-document': {'id': 'LPD-document', 'deprecated': False}, 'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False}, 'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False}, 'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False}, 'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False}, 'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False}, 'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False}, 'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False}, 'lsof': {'id': 'lsof', 'deprecated': False}, 'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False}, 'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False}, 'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False}, 'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False}, 'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False}, 'magaz': {'id': 'magaz', 'deprecated': False}, 'mailprio': {'id': 'mailprio', 'deprecated': False}, 'makeindex': {'id': 'MakeIndex', 'deprecated': False}, 'man2html': {'id': 'man2html', 'deprecated': False}, 'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False}, 'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False}, 'metamail': {'id': 'metamail', 'deprecated': False}, 'minpack': {'id': 'Minpack', 'deprecated': False}, 'mips': {'id': 'MIPS', 'deprecated': False}, 'miros': {'id': 'MirOS', 'deprecated': False}, 'mit': {'id': 'MIT', 'deprecated': False}, 'mit-0': {'id': 'MIT-0', 'deprecated': False}, 'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False}, 'mit-click': {'id': 'MIT-Click', 'deprecated': False}, 'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False}, 'mit-enna': {'id': 'MIT-enna', 'deprecated': False}, 'mit-feh': {'id': 'MIT-feh', 'deprecated': False}, 'mit-festival': {'id': 'MIT-Festival', 'deprecated': False}, 'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False}, 'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False}, 'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False}, 'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False}, 'mit-wu': {'id': 'MIT-Wu', 'deprecated': False}, 'mitnfa': {'id': 'MITNFA', 'deprecated': False}, 'mmixware': {'id': 'MMIXware', 'deprecated': False}, 'motosoto': {'id': 'Motosoto', 'deprecated': False}, 'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False}, 'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False}, 'mpich2': {'id': 'mpich2', 'deprecated': False}, 'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False}, 'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False}, 'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False}, 'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False}, 'mplus': {'id': 'mplus', 'deprecated': False}, 'ms-lpl': {'id': 'MS-LPL', 'deprecated': False}, 'ms-pl': {'id': 'MS-PL', 'deprecated': False}, 'ms-rl': {'id': 'MS-RL', 'deprecated': False}, 'mtll': {'id': 'MTLL', 'deprecated': False}, 'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False}, 'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False}, 'multics': {'id': 'Multics', 'deprecated': False}, 'mup': {'id': 'Mup', 'deprecated': False}, 'naist-2003': {'id': 'NAIST-2003', 'deprecated': False}, 'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False}, 'naumen': {'id': 'Naumen', 'deprecated': False}, 'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False}, 'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False}, 'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False}, 'ncl': {'id': 'NCL', 'deprecated': False}, 'ncsa': {'id': 'NCSA', 'deprecated': False}, 'net-snmp': {'id': 'Net-SNMP', 'deprecated': True}, 'netcdf': {'id': 'NetCDF', 'deprecated': False}, 'newsletr': {'id': 'Newsletr', 'deprecated': False}, 'ngpl': {'id': 'NGPL', 'deprecated': False}, 'ngrep': {'id': 'ngrep', 'deprecated': False}, 'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False}, 'nist-pd': {'id': 'NIST-PD', 'deprecated': False}, 'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False}, 'nist-software': {'id': 'NIST-Software', 'deprecated': False}, 'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False}, 'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False}, 'nlpl': {'id': 'NLPL', 'deprecated': False}, 'nokia': {'id': 'Nokia', 'deprecated': False}, 'nosl': {'id': 'NOSL', 'deprecated': False}, 'noweb': {'id': 'Noweb', 'deprecated': False}, 'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False}, 'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False}, 'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False}, 'nrl': {'id': 'NRL', 'deprecated': False}, 'ntia-pd': {'id': 'NTIA-PD', 'deprecated': False}, 'ntp': {'id': 'NTP', 'deprecated': False}, 'ntp-0': {'id': 'NTP-0', 'deprecated': False}, 'nunit': {'id': 'Nunit', 'deprecated': True}, 'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False}, 'oar': {'id': 'OAR', 'deprecated': False}, 'occt-pl': {'id': 'OCCT-PL', 'deprecated': False}, 'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False}, 'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False}, 'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False}, 'offis': {'id': 'OFFIS', 'deprecated': False}, 'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False}, 'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False}, 'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False}, 'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False}, 'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False}, 'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False}, 'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False}, 'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False}, 'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False}, 'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False}, 'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False}, 'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False}, 'ogtsl': {'id': 'OGTSL', 'deprecated': False}, 'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False}, 'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False}, 'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False}, 'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False}, 'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False}, 'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False}, 'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False}, 'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False}, 'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False}, 'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False}, 'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False}, 'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False}, 'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False}, 'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False}, 'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False}, 'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False}, 'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False}, 'oml': {'id': 'OML', 'deprecated': False}, 'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False}, 'openssl': {'id': 'OpenSSL', 'deprecated': False}, 'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False}, 'openvision': {'id': 'OpenVision', 'deprecated': False}, 'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False}, 'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False}, 'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False}, 'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False}, 'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False}, 'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False}, 'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False}, 'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False}, 'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False}, 'padl': {'id': 'PADL', 'deprecated': False}, 'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False}, 'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False}, 'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False}, 'php-3.0': {'id': 'PHP-3.0', 'deprecated': False}, 'php-3.01': {'id': 'PHP-3.01', 'deprecated': False}, 'pixar': {'id': 'Pixar', 'deprecated': False}, 'pkgconf': {'id': 'pkgconf', 'deprecated': False}, 'plexus': {'id': 'Plexus', 'deprecated': False}, 'pnmstitch': {'id': 'pnmstitch', 'deprecated': False}, 'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False}, 'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False}, 'postgresql': {'id': 'PostgreSQL', 'deprecated': False}, 'ppl': {'id': 'PPL', 'deprecated': False}, 'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False}, 'psfrag': {'id': 'psfrag', 'deprecated': False}, 'psutils': {'id': 'psutils', 'deprecated': False}, 'python-2.0': {'id': 'Python-2.0', 'deprecated': False}, 'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False}, 'python-ldap': {'id': 'python-ldap', 'deprecated': False}, 'qhull': {'id': 'Qhull', 'deprecated': False}, 'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False}, 'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False}, 'radvd': {'id': 'radvd', 'deprecated': False}, 'rdisc': {'id': 'Rdisc', 'deprecated': False}, 'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False}, 'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False}, 'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False}, 'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False}, 'rsa-md': {'id': 'RSA-MD', 'deprecated': False}, 'rscpl': {'id': 'RSCPL', 'deprecated': False}, 'ruby': {'id': 'Ruby', 'deprecated': False}, 'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False}, 'sax-pd': {'id': 'SAX-PD', 'deprecated': False}, 'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False}, 'saxpath': {'id': 'Saxpath', 'deprecated': False}, 'scea': {'id': 'SCEA', 'deprecated': False}, 'schemereport': {'id': 'SchemeReport', 'deprecated': False}, 'sendmail': {'id': 'Sendmail', 'deprecated': False}, 'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False}, 'sendmail-open-source-1.1': {'id': 'Sendmail-Open-Source-1.1', 'deprecated': False}, 'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False}, 'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False}, 'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False}, 'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False}, 'sgp4': {'id': 'SGP4', 'deprecated': False}, 'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False}, 'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False}, 'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False}, 'sissl': {'id': 'SISSL', 'deprecated': False}, 'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False}, 'sl': {'id': 'SL', 'deprecated': False}, 'sleepycat': {'id': 'Sleepycat', 'deprecated': False}, 'smail-gpl': {'id': 'SMAIL-GPL', 'deprecated': False}, 'smlnj': {'id': 'SMLNJ', 'deprecated': False}, 'smppl': {'id': 'SMPPL', 'deprecated': False}, 'snia': {'id': 'SNIA', 'deprecated': False}, 'snprintf': {'id': 'snprintf', 'deprecated': False}, 'sofa': {'id': 'SOFA', 'deprecated': False}, 'softsurfer': {'id': 'softSurfer', 'deprecated': False}, 'soundex': {'id': 'Soundex', 'deprecated': False}, 'spencer-86': {'id': 'Spencer-86', 'deprecated': False}, 'spencer-94': {'id': 'Spencer-94', 'deprecated': False}, 'spencer-99': {'id': 'Spencer-99', 'deprecated': False}, 'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False}, 'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False}, 'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False}, 'ssh-short': {'id': 'SSH-short', 'deprecated': False}, 'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False}, 'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False}, 'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True}, 'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False}, 'sul-1.0': {'id': 'SUL-1.0', 'deprecated': False}, 'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False}, 'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False}, 'sunpro': {'id': 'SunPro', 'deprecated': False}, 'swl': {'id': 'SWL', 'deprecated': False}, 'swrule': {'id': 'swrule', 'deprecated': False}, 'symlinks': {'id': 'Symlinks', 'deprecated': False}, 'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False}, 'tcl': {'id': 'TCL', 'deprecated': False}, 'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False}, 'termreadkey': {'id': 'TermReadKey', 'deprecated': False}, 'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False}, 'thirdeye': {'id': 'ThirdEye', 'deprecated': False}, 'threeparttable': {'id': 'threeparttable', 'deprecated': False}, 'tmate': {'id': 'TMate', 'deprecated': False}, 'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False}, 'tosl': {'id': 'TOSL', 'deprecated': False}, 'tpdl': {'id': 'TPDL', 'deprecated': False}, 'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False}, 'trustedqsl': {'id': 'TrustedQSL', 'deprecated': False}, 'ttwl': {'id': 'TTWL', 'deprecated': False}, 'ttyp0': {'id': 'TTYP0', 'deprecated': False}, 'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False}, 'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False}, 'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False}, 'ucar': {'id': 'UCAR', 'deprecated': False}, 'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False}, 'ulem': {'id': 'ulem', 'deprecated': False}, 'umich-merit': {'id': 'UMich-Merit', 'deprecated': False}, 'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False}, 'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False}, 'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False}, 'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False}, 'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False}, 'unlicense': {'id': 'Unlicense', 'deprecated': False}, 'unlicense-libtelnet': {'id': 'Unlicense-libtelnet', 'deprecated': False}, 'unlicense-libwhirlpool': {'id': 'Unlicense-libwhirlpool', 'deprecated': False}, 'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False}, 'urt-rle': {'id': 'URT-RLE', 'deprecated': False}, 'vim': {'id': 'Vim', 'deprecated': False}, 'vostrom': {'id': 'VOSTROM', 'deprecated': False}, 'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False}, 'w3c': {'id': 'W3C', 'deprecated': False}, 'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False}, 'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False}, 'w3m': {'id': 'w3m', 'deprecated': False}, 'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False}, 'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False}, 'wsuipa': {'id': 'Wsuipa', 'deprecated': False}, 'wtfpl': {'id': 'WTFPL', 'deprecated': False}, 'wwl': {'id': 'wwl', 'deprecated': False}, 'wxwindows': {'id': 'wxWindows', 'deprecated': True}, 'x11': {'id': 'X11', 'deprecated': False}, 'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False}, 'x11-swapped': {'id': 'X11-swapped', 'deprecated': False}, 'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False}, 'xerox': {'id': 'Xerox', 'deprecated': False}, 'xfig': {'id': 'Xfig', 'deprecated': False}, 'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False}, 'xinetd': {'id': 'xinetd', 'deprecated': False}, 'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False}, 'xlock': {'id': 'xlock', 'deprecated': False}, 'xnet': {'id': 'Xnet', 'deprecated': False}, 'xpp': {'id': 'xpp', 'deprecated': False}, 'xskat': {'id': 'XSkat', 'deprecated': False}, 'xzoom': {'id': 'xzoom', 'deprecated': False}, 'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False}, 'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False}, 'zed': {'id': 'Zed', 'deprecated': False}, 'zeeff': {'id': 'Zeeff', 'deprecated': False}, 'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False}, 'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False}, 'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False}, 'zlib': {'id': 'Zlib', 'deprecated': False}, 'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False}, 'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False}, 'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False}, 'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False},}
EXCEPTIONS: dict[str, SPDXException] = { '389-exception': {'id': '389-exception', 'deprecated': False}, 'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False}, 'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False}, 'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False}, 'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False}, 'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False}, 'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False}, 'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False}, 'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False}, 'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False}, 'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False}, 'cgal-linking-exception': {'id': 'CGAL-linking-exception', 'deprecated': False}, 'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False}, 'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False}, 'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False}, 'digia-qt-lgpl-exception-1.1': {'id': 'Digia-Qt-LGPL-exception-1.1', 'deprecated': False}, 'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False}, 'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False}, 'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False}, 'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False}, 'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False}, 'fmt-exception': {'id': 'fmt-exception', 'deprecated': False}, 'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False}, 'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False}, 'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False}, 'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False}, 'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False}, 'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False}, 'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False}, 'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False}, 'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False}, 'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False}, 'gpl-3.0-389-ds-base-exception': {'id': 'GPL-3.0-389-ds-base-exception', 'deprecated': False}, 'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False}, 'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False}, 'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False}, 'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False}, 'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False}, 'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False}, 'harbour-exception': {'id': 'harbour-exception', 'deprecated': False}, 'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False}, 'independent-modules-exception': {'id': 'Independent-modules-exception', 'deprecated': False}, 'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False}, 'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False}, 'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False}, 'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False}, 'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False}, 'llgpl': {'id': 'LLGPL', 'deprecated': False}, 'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False}, 'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False}, 'mif-exception': {'id': 'mif-exception', 'deprecated': False}, 'mxml-exception': {'id': 'mxml-exception', 'deprecated': False}, 'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True}, 'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False}, 'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False}, 'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False}, 'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False}, 'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False}, 'polyparse-exception': {'id': 'polyparse-exception', 'deprecated': False}, 'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False}, 'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False}, 'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False}, 'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False}, 'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False}, 'romic-exception': {'id': 'romic-exception', 'deprecated': False}, 'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False}, 'sane-exception': {'id': 'SANE-exception', 'deprecated': False}, 'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False}, 'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False}, 'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False}, 'swi-exception': {'id': 'SWI-exception', 'deprecated': False}, 'swift-exception': {'id': 'Swift-exception', 'deprecated': False}, 'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False}, 'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False}, 'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False}, 'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False}, 'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False}, 'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False}, 'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False},}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
from __future__ import annotations
import operatorimport osimport platformimport sysfrom typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
from ._parser import MarkerAtom, MarkerList, Op, Value, Variablefrom ._parser import parse_marker as _parse_markerfrom ._tokenizer import ParserSyntaxErrorfrom .specifiers import InvalidSpecifier, Specifierfrom .utils import canonicalize_name
__all__ = [ "Environment", "EvaluateContext", "InvalidMarker", "Marker", "UndefinedComparison", "UndefinedEnvironmentName", "default_environment",]
Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]EvaluateContext = Literal["metadata", "lock_file", "requirement"]MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}MARKERS_REQUIRING_VERSION = { "implementation_version", "platform_release", "python_full_version", "python_version",}
class InvalidMarker(ValueError): """ An invalid marker was found, users should refer to PEP 508. """
class UndefinedComparison(ValueError): """ An invalid operation was attempted on a value that doesn't support it. """
class UndefinedEnvironmentName(ValueError): """ A name was attempted to be used that does not exist inside of the environment. """
class Environment(TypedDict): implementation_name: str """The implementation's identifier, e.g. ``'cpython'``."""
implementation_version: str """ The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or ``'7.3.13'`` for PyPy3.10 v7.3.13. """
os_name: str """ The value of :py:data:`os.name`. The name of the operating system dependent module imported, e.g. ``'posix'``. """
platform_machine: str """ Returns the machine type, e.g. ``'i386'``.
An empty string if the value cannot be determined. """
platform_release: str """ The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
An empty string if the value cannot be determined. """
platform_system: str """ The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
An empty string if the value cannot be determined. """
platform_version: str """ The system's release version, e.g. ``'#3 on degas'``.
An empty string if the value cannot be determined. """
python_full_version: str """ The Python version as string ``'major.minor.patchlevel'``.
Note that unlike the Python :py:data:`sys.version`, this value will always include the patchlevel (it defaults to 0). """
platform_python_implementation: str """ A string identifying the Python implementation, e.g. ``'CPython'``. """
python_version: str """The Python version as string ``'major.minor'``."""
sys_platform: str """ This string contains a platform identifier that can be used to append platform-specific components to :py:data:`sys.path`, for instance.
For Unix systems, except on Linux and AIX, this is the lowercased OS name as returned by ``uname -s`` with the first part of the version as returned by ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python was built. """
def _normalize_extras( result: MarkerList | MarkerAtom | str,) -> MarkerList | MarkerAtom | str: if not isinstance(result, tuple): return result
lhs, op, rhs = result if isinstance(lhs, Variable) and lhs.value == "extra": normalized_extra = canonicalize_name(rhs.value) rhs = Value(normalized_extra) elif isinstance(rhs, Variable) and rhs.value == "extra": normalized_extra = canonicalize_name(lhs.value) lhs = Value(normalized_extra) return lhs, op, rhs
def _normalize_extra_values(results: MarkerList) -> MarkerList: """ Normalize extra values. """
return [_normalize_extras(r) for r in results]
def _format_marker( marker: list[str] | MarkerAtom | str, first: bool | None = True) -> str: assert isinstance(marker, (list, tuple, str))
# Sometimes we have a structure like [[...]] which is a single item list # where the single item is itself it's own list. In that case we want skip # the rest of this function so that we don't get extraneous () on the # outside. if ( isinstance(marker, list) and len(marker) == 1 and isinstance(marker[0], (list, tuple)) ): return _format_marker(marker[0])
if isinstance(marker, list): inner = (_format_marker(m, first=False) for m in marker) if first: return " ".join(inner) else: return "(" + " ".join(inner) + ")" elif isinstance(marker, tuple): return " ".join([m.serialize() for m in marker]) else: return marker
_operators: dict[str, Operator] = { "in": lambda lhs, rhs: lhs in rhs, "not in": lambda lhs, rhs: lhs not in rhs, "<": lambda _lhs, _rhs: False, "<=": operator.eq, "==": operator.eq, "!=": operator.ne, ">=": operator.eq, ">": lambda _lhs, _rhs: False,}
def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool: op_str = op.serialize() if key in MARKERS_REQUIRING_VERSION: try: spec = Specifier(f"{op_str}{rhs}") except InvalidSpecifier: pass else: return spec.contains(lhs, prereleases=True)
oper: Operator | None = _operators.get(op_str) if oper is None: raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
return oper(lhs, rhs)
def _normalize( lhs: str, rhs: str | AbstractSet[str], key: str) -> tuple[str, str | AbstractSet[str]]: # PEP 685 - Comparison of extra names for optional distribution dependencies # https://peps.python.org/pep-0685/ # > When comparing extra names, tools MUST normalize the names being # > compared using the semantics outlined in PEP 503 for names if key == "extra": assert isinstance(rhs, str), "extra value must be a string" # Both sides are normalized at this point already return (lhs, rhs) if key in MARKERS_ALLOWING_SET: if isinstance(rhs, str): # pragma: no cover return (canonicalize_name(lhs), canonicalize_name(rhs)) else: return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})
# other environment markers don't have such standards return lhs, rhs
def _evaluate_markers( markers: MarkerList, environment: dict[str, str | AbstractSet[str]]) -> bool: groups: list[list[bool]] = [[]]
for marker in markers: if isinstance(marker, list): groups[-1].append(_evaluate_markers(marker, environment)) elif isinstance(marker, tuple): lhs, op, rhs = marker
if isinstance(lhs, Variable): environment_key = lhs.value lhs_value = environment[environment_key] rhs_value = rhs.value else: lhs_value = lhs.value environment_key = rhs.value rhs_value = environment[environment_key]
assert isinstance(lhs_value, str), "lhs must be a string" lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key)) elif marker == "or": groups.append([]) elif marker == "and": pass else: # pragma: nocover raise TypeError(f"Unexpected marker {marker!r}")
return any(all(item) for item in groups)
def format_full_version(info: sys._version_info) -> str: version = f"{info.major}.{info.minor}.{info.micro}" kind = info.releaselevel if kind != "final": version += kind[0] + str(info.serial) return version
def default_environment() -> Environment: iver = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name return { "implementation_name": implementation_name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": ".".join(platform.python_version_tuple()[:2]), "sys_platform": sys.platform, }
class Marker: def __init__(self, marker: str) -> None: # Note: We create a Marker object without calling this constructor in # packaging.requirements.Requirement. If any additional logic is # added here, make sure to mirror/adapt Requirement.
# If this fails and throws an error, the repr still expects _markers to # be defined. self._markers: MarkerList = []
try: self._markers = _normalize_extra_values(_parse_marker(marker)) # The attribute `_markers` can be described in terms of a recursive type: # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] # # For example, the following expression: # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") # # is parsed into: # [ # (<Variable('python_version')>, <Op('>')>, <Value('3.6')>), # 'and', # [ # (<Variable('python_version')>, <Op('==')>, <Value('3.6')>), # 'or', # (<Variable('os_name')>, <Op('==')>, <Value('unix')>) # ] # ] except ParserSyntaxError as e: raise InvalidMarker(str(e)) from e
def __str__(self) -> str: return _format_marker(self._markers)
def __repr__(self) -> str: return f"<{self.__class__.__name__}('{self}')>"
def __hash__(self) -> int: return hash(str(self))
def __eq__(self, other: object) -> bool: if not isinstance(other, Marker): return NotImplemented
return str(self) == str(other)
def evaluate( self, environment: Mapping[str, str | AbstractSet[str]] | None = None, context: EvaluateContext = "metadata", ) -> bool: """Evaluate a marker.
Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The *context* parameter specifies what context the markers are being evaluated for, which influences what markers are considered valid. Acceptable values are "metadata" (for core metadata; default), "lock_file", and "requirement" (i.e. all other situations).
The environment is determined from the current Python process. """ current_environment = cast( "dict[str, str | AbstractSet[str]]", default_environment() ) if context == "lock_file": current_environment.update( extras=frozenset(), dependency_groups=frozenset() ) elif context == "metadata": current_environment["extra"] = ""
if environment is not None: current_environment.update(environment) if "extra" in current_environment: # The API used to allow setting extra to None. We need to handle # this case for backwards compatibility. Also skip running # normalize name if extra is empty. extra = cast("str | None", current_environment["extra"]) current_environment["extra"] = canonicalize_name(extra) if extra else ""
return _evaluate_markers( self._markers, _repair_python_full_version(current_environment) )
def _repair_python_full_version( env: dict[str, str | AbstractSet[str]],) -> dict[str, str | AbstractSet[str]]: """ Work around platform.python_version() returning something that is not PEP 440 compliant for non-tagged Python builds. """ python_full_version = cast("str", env["python_full_version"]) if python_full_version.endswith("+"): env["python_full_version"] = f"{python_full_version}local" return env123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978from __future__ import annotations
import email.feedparserimport email.headerimport email.messageimport email.parserimport email.policyimport keywordimport pathlibimport sysimport typingfrom typing import ( Any, Callable, Generic, Literal, TypedDict, cast,)
from . import licenses, requirements, specifiers, utilsfrom . import version as version_module
if typing.TYPE_CHECKING: from .licenses import NormalizedLicenseExpression
T = typing.TypeVar("T")
if sys.version_info >= (3, 11): # pragma: no cover ExceptionGroup = ExceptionGroup # noqa: F821else: # pragma: no cover
class ExceptionGroup(Exception): """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
If :external:exc:`ExceptionGroup` is already defined by Python itself, that version is used instead. """
message: str exceptions: list[Exception]
def __init__(self, message: str, exceptions: list[Exception]) -> None: self.message = message self.exceptions = exceptions
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
class InvalidMetadata(ValueError): """A metadata field contains invalid data."""
field: str """The name of the field that contains invalid data."""
def __init__(self, field: str, message: str) -> None: self.field = field super().__init__(message)
# The RawMetadata class attempts to make as few assumptions about the underlying# serialization formats as possible. The idea is that as long as a serialization# formats offer some very basic primitives in *some* way then we can support# serializing to and from that format.class RawMetadata(TypedDict, total=False): """A dictionary of raw core metadata.
Each field in core metadata maps to a key of this dictionary (when data is provided). The key is lower-case and underscores are used instead of dashes compared to the equivalent core metadata field. Any core metadata field that can be specified multiple times or can hold multiple values in a single field have a key with a plural name. See :class:`Metadata` whose attributes match the keys of this dictionary.
Core metadata fields that can be specified multiple times are stored as a list or dict depending on which is appropriate for the field. Any fields which hold multiple values in a single field are stored as a list.
"""
# Metadata 1.0 - PEP 241 metadata_version: str name: str version: str platforms: list[str] summary: str description: str keywords: list[str] home_page: str author: str author_email: str license: str
# Metadata 1.1 - PEP 314 supported_platforms: list[str] download_url: str classifiers: list[str] requires: list[str] provides: list[str] obsoletes: list[str]
# Metadata 1.2 - PEP 345 maintainer: str maintainer_email: str requires_dist: list[str] provides_dist: list[str] obsoletes_dist: list[str] requires_python: str requires_external: list[str] project_urls: dict[str, str]
# Metadata 2.0 # PEP 426 attempted to completely revamp the metadata format # but got stuck without ever being able to build consensus on # it and ultimately ended up withdrawn. # # However, a number of tools had started emitting METADATA with # `2.0` Metadata-Version, so for historical reasons, this version # was skipped.
# Metadata 2.1 - PEP 566 description_content_type: str provides_extra: list[str]
# Metadata 2.2 - PEP 643 dynamic: list[str]
# Metadata 2.3 - PEP 685 # No new fields were added in PEP 685, just some edge case were # tightened up to provide better interoperability.
# Metadata 2.4 - PEP 639 license_expression: str license_files: list[str]
# Metadata 2.5 - PEP 794 import_names: list[str] import_namespaces: list[str]
# 'keywords' is special as it's a string in the core metadata spec, but we# represent it as a list._STRING_FIELDS = { "author", "author_email", "description", "description_content_type", "download_url", "home_page", "license", "license_expression", "maintainer", "maintainer_email", "metadata_version", "name", "requires_python", "summary", "version",}
_LIST_FIELDS = { "classifiers", "dynamic", "license_files", "obsoletes", "obsoletes_dist", "platforms", "provides", "provides_dist", "provides_extra", "requires", "requires_dist", "requires_external", "supported_platforms", "import_names", "import_namespaces",}
_DICT_FIELDS = { "project_urls",}
def _parse_keywords(data: str) -> list[str]: """Split a string of comma-separated keywords into a list of keywords.""" return [k.strip() for k in data.split(",")]
def _parse_project_urls(data: list[str]) -> dict[str, str]: """Parse a list of label/URL string pairings separated by a comma.""" urls = {} for pair in data: # Our logic is slightly tricky here as we want to try and do # *something* reasonable with malformed data. # # The main thing that we have to worry about, is data that does # not have a ',' at all to split the label from the Value. There # isn't a singular right answer here, and we will fail validation # later on (if the caller is validating) so it doesn't *really* # matter, but since the missing value has to be an empty str # and our return value is dict[str, str], if we let the key # be the missing value, then they'd have multiple '' values that # overwrite each other in a accumulating dict. # # The other potential issue is that it's possible to have the # same label multiple times in the metadata, with no solid "right" # answer with what to do in that case. As such, we'll do the only # thing we can, which is treat the field as unparsable and add it # to our list of unparsed fields. # # TODO: The spec doesn't say anything about if the keys should be # considered case sensitive or not... logically they should # be case-preserving and case-insensitive, but doing that # would open up more cases where we might have duplicate # entries. label, _, url = (s.strip() for s in pair.partition(","))
if label in urls: # The label already exists in our set of urls, so this field # is unparsable, and we can just add the whole thing to our # unparsable data and stop processing it. raise KeyError("duplicate labels in project urls") urls[label] = url
return urls
def _get_payload(msg: email.message.Message, source: bytes | str) -> str: """Get the body of the message.""" # If our source is a str, then our caller has managed encodings for us, # and we don't need to deal with it. if isinstance(source, str): payload = msg.get_payload() assert isinstance(payload, str) return payload # If our source is a bytes, then we're managing the encoding and we need # to deal with it. else: bpayload = msg.get_payload(decode=True) assert isinstance(bpayload, bytes) try: return bpayload.decode("utf8", "strict") except UnicodeDecodeError as exc: raise ValueError("payload in an invalid encoding") from exc
# The various parse_FORMAT functions here are intended to be as lenient as# possible in their parsing, while still returning a correctly typed# RawMetadata.## To aid in this, we also generally want to do as little touching of the# data as possible, except where there are possibly some historic holdovers# that make valid data awkward to work with.## While this is a lower level, intermediate format than our ``Metadata``# class, some light touch ups can make a massive difference in usability.
# Map METADATA fields to RawMetadata._EMAIL_TO_RAW_MAPPING = { "author": "author", "author-email": "author_email", "classifier": "classifiers", "description": "description", "description-content-type": "description_content_type", "download-url": "download_url", "dynamic": "dynamic", "home-page": "home_page", "import-name": "import_names", "import-namespace": "import_namespaces", "keywords": "keywords", "license": "license", "license-expression": "license_expression", "license-file": "license_files", "maintainer": "maintainer", "maintainer-email": "maintainer_email", "metadata-version": "metadata_version", "name": "name", "obsoletes": "obsoletes", "obsoletes-dist": "obsoletes_dist", "platform": "platforms", "project-url": "project_urls", "provides": "provides", "provides-dist": "provides_dist", "provides-extra": "provides_extra", "requires": "requires", "requires-dist": "requires_dist", "requires-external": "requires_external", "requires-python": "requires_python", "summary": "summary", "supported-platform": "supported_platforms", "version": "version",}_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
# This class is for writing RFC822 messagesclass RFC822Policy(email.policy.EmailPolicy): """ This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse`` implementation that handles multi-line values, and some nice defaults. """
utf8 = True mangle_from_ = False max_line_length = 0
def header_store_parse(self, name: str, value: str) -> tuple[str, str]: size = len(name) + 2 value = value.replace("\n", "\n" + " " * size) return (name, value)
# This class is for writing RFC822 messagesclass RFC822Message(email.message.EmailMessage): """ This is :class:`email.message.EmailMessage` with two small changes: it defaults to our `RFC822Policy`, and it correctly writes unicode when being called with `bytes()`. """
def __init__(self) -> None: super().__init__(policy=RFC822Policy())
def as_bytes( self, unixfrom: bool = False, policy: email.policy.Policy | None = None ) -> bytes: """ Return the bytes representation of the message.
This handles unicode encoding. """ return self.as_string(unixfrom, policy=policy).encode("utf-8")
def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
This function returns a two-item tuple of dicts. The first dict is of recognized fields from the core metadata specification. Fields that can be parsed and translated into Python's built-in types are converted appropriately. All other fields are left as-is. Fields that are allowed to appear multiple times are stored as lists.
The second dict contains all other fields from the metadata. This includes any unrecognized fields. It also includes any fields which are expected to be parsed into a built-in type but were not formatted appropriately. Finally, any fields that are expected to appear only once but are repeated are included in this dict.
""" raw: dict[str, str | list[str] | dict[str, str]] = {} unparsed: dict[str, list[str]] = {}
if isinstance(data, str): parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) else: parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
# We have to wrap parsed.keys() in a set, because in the case of multiple # values for a key (a list), the key will appear multiple times in the # list of keys, but we're avoiding that by using get_all(). for name_with_case in frozenset(parsed.keys()): # Header names in RFC are case insensitive, so we'll normalize to all # lower case to make comparisons easier. name = name_with_case.lower()
# We use get_all() here, even for fields that aren't multiple use, # because otherwise someone could have e.g. two Name fields, and we # would just silently ignore it rather than doing something about it. headers = parsed.get_all(name) or []
# The way the email module works when parsing bytes is that it # unconditionally decodes the bytes as ascii using the surrogateescape # handler. When you pull that data back out (such as with get_all() ), # it looks to see if the str has any surrogate escapes, and if it does # it wraps it in a Header object instead of returning the string. # # As such, we'll look for those Header objects, and fix up the encoding. value = [] # Flag if we have run into any issues processing the headers, thus # signalling that the data belongs in 'unparsed'. valid_encoding = True for h in headers: # It's unclear if this can return more types than just a Header or # a str, so we'll just assert here to make sure. assert isinstance(h, (email.header.Header, str))
# If it's a header object, we need to do our little dance to get # the real data out of it. In cases where there is invalid data # we're going to end up with mojibake, but there's no obvious, good # way around that without reimplementing parts of the Header object # ourselves. # # That should be fine since, if mojibacked happens, this key is # going into the unparsed dict anyways. if isinstance(h, email.header.Header): # The Header object stores it's data as chunks, and each chunk # can be independently encoded, so we'll need to check each # of them. chunks: list[tuple[bytes, str | None]] = [] for binary, _encoding in email.header.decode_header(h): try: binary.decode("utf8", "strict") except UnicodeDecodeError: # Enable mojibake. encoding = "latin1" valid_encoding = False else: encoding = "utf8" chunks.append((binary, encoding))
# Turn our chunks back into a Header object, then let that # Header object do the right thing to turn them into a # string for us. value.append(str(email.header.make_header(chunks))) # This is already a string, so just add it. else: value.append(h)
# We've processed all of our values to get them into a list of str, # but we may have mojibake data, in which case this is an unparsed # field. if not valid_encoding: unparsed[name] = value continue
raw_name = _EMAIL_TO_RAW_MAPPING.get(name) if raw_name is None: # This is a bit of a weird situation, we've encountered a key that # we don't know what it means, so we don't know whether it's meant # to be a list or not. # # Since we can't really tell one way or another, we'll just leave it # as a list, even though it may be a single item list, because that's # what makes the most sense for email headers. unparsed[name] = value continue
# If this is one of our string fields, then we'll check to see if our # value is a list of a single item. If it is then we'll assume that # it was emitted as a single string, and unwrap the str from inside # the list. # # If it's any other kind of data, then we haven't the faintest clue # what we should parse it as, and we have to just add it to our list # of unparsed stuff. if raw_name in _STRING_FIELDS and len(value) == 1: raw[raw_name] = value[0] # If this is import_names, we need to special case the empty field # case, which converts to an empty list instead of None. We can't let # the empty case slip through, as it will fail validation. elif raw_name == "import_names" and value == [""]: raw[raw_name] = [] # If this is one of our list of string fields, then we can just assign # the value, since email *only* has strings, and our get_all() call # above ensures that this is a list. elif raw_name in _LIST_FIELDS: raw[raw_name] = value # Special Case: Keywords # The keywords field is implemented in the metadata spec as a str, # but it conceptually is a list of strings, and is serialized using # ", ".join(keywords), so we'll do some light data massaging to turn # this into what it logically is. elif raw_name == "keywords" and len(value) == 1: raw[raw_name] = _parse_keywords(value[0]) # Special Case: Project-URL # The project urls is implemented in the metadata spec as a list of # specially-formatted strings that represent a key and a value, which # is fundamentally a mapping, however the email format doesn't support # mappings in a sane way, so it was crammed into a list of strings # instead. # # We will do a little light data massaging to turn this into a map as # it logically should be. elif raw_name == "project_urls": try: raw[raw_name] = _parse_project_urls(value) except KeyError: unparsed[name] = value # Nothing that we've done has managed to parse this, so it'll just # throw it in our unparsable data and move on. else: unparsed[name] = value
# We need to support getting the Description from the message payload in # addition to getting it from the the headers. This does mean, though, there # is the possibility of it being set both ways, in which case we put both # in 'unparsed' since we don't know which is right. try: payload = _get_payload(parsed, data) except ValueError: unparsed.setdefault("description", []).append( parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] ) else: if payload: # Check to see if we've already got a description, if so then both # it, and this body move to unparsable. if "description" in raw: description_header = cast("str", raw.pop("description")) unparsed.setdefault("description", []).extend( [description_header, payload] ) elif "description" in unparsed: unparsed["description"].append(payload) else: raw["description"] = payload
# We need to cast our `raw` to a metadata, because a TypedDict only support # literal key names, but we're computing our key names on purpose, but the # way this function is implemented, our `TypedDict` can only have valid key # names. return cast("RawMetadata", raw), unparsed
_NOT_FOUND = object()
# Keep the two values in sync._VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
class _Validator(Generic[T]): """Validate a metadata field.
All _process_*() methods correspond to a core metadata field. The method is called with the field's raw value. If the raw value is valid it is returned in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause as appropriate). """
name: str raw_name: str added: _MetadataVersion
def __init__( self, *, added: _MetadataVersion = "1.0", ) -> None: self.added = added
def __set_name__(self, _owner: Metadata, name: str) -> None: self.name = name self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: # With Python 3.8, the caching can be replaced with functools.cached_property(). # No need to check the cache as attribute lookup will resolve into the # instance's __dict__ before __get__ is called. cache = instance.__dict__ value = instance._raw.get(self.name)
# To make the _process_* methods easier, we'll check if the value is None # and if this field is NOT a required attribute, and if both of those # things are true, we'll skip the the converter. This will mean that the # converters never have to deal with the None union. if self.name in _REQUIRED_ATTRS or value is not None: try: converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") except AttributeError: pass else: value = converter(value)
cache[self.name] = value try: del instance._raw[self.name] # type: ignore[misc] except KeyError: pass
return cast("T", value)
def _invalid_metadata( self, msg: str, cause: Exception | None = None ) -> InvalidMetadata: exc = InvalidMetadata( self.raw_name, msg.format_map({"field": repr(self.raw_name)}) ) exc.__cause__ = cause return exc
def _process_metadata_version(self, value: str) -> _MetadataVersion: # Implicitly makes Metadata-Version required. if value not in _VALID_METADATA_VERSIONS: raise self._invalid_metadata(f"{value!r} is not a valid metadata version") return cast("_MetadataVersion", value)
def _process_name(self, value: str) -> str: if not value: raise self._invalid_metadata("{field} is a required field") # Validate the name as a side-effect. try: utils.canonicalize_name(value, validate=True) except utils.InvalidName as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) from exc else: return value
def _process_version(self, value: str) -> version_module.Version: if not value: raise self._invalid_metadata("{field} is a required field") try: return version_module.parse(value) except version_module.InvalidVersion as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) from exc
def _process_summary(self, value: str) -> str: """Check the field contains no newlines.""" if "\n" in value: raise self._invalid_metadata("{field} must be a single line") return value
def _process_description_content_type(self, value: str) -> str: content_types = {"text/plain", "text/x-rst", "text/markdown"} message = email.message.EmailMessage() message["content-type"] = value
content_type, parameters = ( # Defaults to `text/plain` if parsing failed. message.get_content_type().lower(), message["content-type"].params, ) # Check if content-type is valid or defaulted to `text/plain` and thus was # not parseable. if content_type not in content_types or content_type not in value.lower(): raise self._invalid_metadata( f"{{field}} must be one of {list(content_types)}, not {value!r}" )
charset = parameters.get("charset", "UTF-8") if charset != "UTF-8": raise self._invalid_metadata( f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" )
markdown_variants = {"GFM", "CommonMark"} variant = parameters.get("variant", "GFM") # Use an acceptable default. if content_type == "text/markdown" and variant not in markdown_variants: raise self._invalid_metadata( f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " f"not {variant!r}", ) return value
def _process_dynamic(self, value: list[str]) -> list[str]: for dynamic_field in map(str.lower, value): if dynamic_field in {"name", "version", "metadata-version"}: raise self._invalid_metadata( f"{dynamic_field!r} is not allowed as a dynamic field" ) elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: raise self._invalid_metadata( f"{dynamic_field!r} is not a valid dynamic field" ) return list(map(str.lower, value))
def _process_provides_extra( self, value: list[str], ) -> list[utils.NormalizedName]: normalized_names = [] try: for name in value: normalized_names.append(utils.canonicalize_name(name, validate=True)) except utils.InvalidName as exc: raise self._invalid_metadata( f"{name!r} is invalid for {{field}}", cause=exc ) from exc else: return normalized_names
def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: try: return specifiers.SpecifierSet(value) except specifiers.InvalidSpecifier as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) from exc
def _process_requires_dist( self, value: list[str], ) -> list[requirements.Requirement]: reqs = [] try: for req in value: reqs.append(requirements.Requirement(req)) except requirements.InvalidRequirement as exc: raise self._invalid_metadata( f"{req!r} is invalid for {{field}}", cause=exc ) from exc else: return reqs
def _process_license_expression(self, value: str) -> NormalizedLicenseExpression: try: return licenses.canonicalize_license_expression(value) except ValueError as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) from exc
def _process_license_files(self, value: list[str]) -> list[str]: paths = [] for path in value: if ".." in path: raise self._invalid_metadata( f"{path!r} is invalid for {{field}}, " "parent directory indicators are not allowed" ) if "*" in path: raise self._invalid_metadata( f"{path!r} is invalid for {{field}}, paths must be resolved" ) if ( pathlib.PurePosixPath(path).is_absolute() or pathlib.PureWindowsPath(path).is_absolute() ): raise self._invalid_metadata( f"{path!r} is invalid for {{field}}, paths must be relative" ) if pathlib.PureWindowsPath(path).as_posix() != path: raise self._invalid_metadata( f"{path!r} is invalid for {{field}}, paths must use '/' delimiter" ) paths.append(path) return paths
def _process_import_names(self, value: list[str]) -> list[str]: for import_name in value: name, semicolon, private = import_name.partition(";") name = name.rstrip() for identifier in name.split("."): if not identifier.isidentifier(): raise self._invalid_metadata( f"{name!r} is invalid for {{field}}; " f"{identifier!r} is not a valid identifier" ) elif keyword.iskeyword(identifier): raise self._invalid_metadata( f"{name!r} is invalid for {{field}}; " f"{identifier!r} is a keyword" ) if semicolon and private.lstrip() != "private": raise self._invalid_metadata( f"{import_name!r} is invalid for {{field}}; " "the only valid option is 'private'" ) return value
_process_import_namespaces = _process_import_names
class Metadata: """Representation of distribution metadata.
Compared to :class:`RawMetadata`, this class provides objects representing metadata fields instead of only using built-in types. Any invalid metadata will cause :exc:`InvalidMetadata` to be raised (with a :py:attr:`~BaseException.__cause__` attribute as appropriate). """
_raw: RawMetadata
@classmethod def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: """Create an instance from :class:`RawMetadata`.
If *validate* is true, all metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ ins = cls() ins._raw = data.copy() # Mutations occur due to caching enriched values.
if validate: exceptions: list[Exception] = [] try: metadata_version = ins.metadata_version metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) except InvalidMetadata as metadata_version_exc: exceptions.append(metadata_version_exc) metadata_version = None
# Make sure to check for the fields that are present, the required # fields (so their absence can be reported). fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS # Remove fields that have already been checked. fields_to_check -= {"metadata_version"}
for key in fields_to_check: try: if metadata_version: # Can't use getattr() as that triggers descriptor protocol which # will fail due to no value for the instance argument. try: field_metadata_version = cls.__dict__[key].added except KeyError: exc = InvalidMetadata(key, f"unrecognized field: {key!r}") exceptions.append(exc) continue field_age = _VALID_METADATA_VERSIONS.index( field_metadata_version ) if field_age > metadata_age: field = _RAW_TO_EMAIL_MAPPING[key] exc = InvalidMetadata( field, f"{field} introduced in metadata version " f"{field_metadata_version}, not {metadata_version}", ) exceptions.append(exc) continue getattr(ins, key) except InvalidMetadata as exc: exceptions.append(exc)
if exceptions: raise ExceptionGroup("invalid metadata", exceptions)
return ins
@classmethod def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: """Parse metadata from email headers.
If *validate* is true, the metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ raw, unparsed = parse_email(data)
if validate: exceptions: list[Exception] = [] for unparsed_key in unparsed: if unparsed_key in _EMAIL_TO_RAW_MAPPING: message = f"{unparsed_key!r} has invalid data" else: message = f"unrecognized field: {unparsed_key!r}" exceptions.append(InvalidMetadata(unparsed_key, message))
if exceptions: raise ExceptionGroup("unparsed", exceptions)
try: return cls.from_raw(raw, validate=validate) except ExceptionGroup as exc_group: raise ExceptionGroup( "invalid or unparsed metadata", exc_group.exceptions ) from None
metadata_version: _Validator[_MetadataVersion] = _Validator() """:external:ref:`core-metadata-metadata-version` (required; validated to be a valid metadata version)""" # `name` is not normalized/typed to NormalizedName so as to provide access to # the original/raw name. name: _Validator[str] = _Validator() """:external:ref:`core-metadata-name` (required; validated using :func:`~packaging.utils.canonicalize_name` and its *validate* parameter)""" version: _Validator[version_module.Version] = _Validator() """:external:ref:`core-metadata-version` (required)""" dynamic: _Validator[list[str] | None] = _Validator( added="2.2", ) """:external:ref:`core-metadata-dynamic` (validated against core metadata field names and lowercased)""" platforms: _Validator[list[str] | None] = _Validator() """:external:ref:`core-metadata-platform`""" supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") """:external:ref:`core-metadata-supported-platform`""" summary: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body """:external:ref:`core-metadata-description`""" description_content_type: _Validator[str | None] = _Validator(added="2.1") """:external:ref:`core-metadata-description-content-type` (validated)""" keywords: _Validator[list[str] | None] = _Validator() """:external:ref:`core-metadata-keywords`""" home_page: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-home-page`""" download_url: _Validator[str | None] = _Validator(added="1.1") """:external:ref:`core-metadata-download-url`""" author: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-author`""" author_email: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-author-email`""" maintainer: _Validator[str | None] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer`""" maintainer_email: _Validator[str | None] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer-email`""" license: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-license`""" license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( added="2.4" ) """:external:ref:`core-metadata-license-expression`""" license_files: _Validator[list[str] | None] = _Validator(added="2.4") """:external:ref:`core-metadata-license-file`""" classifiers: _Validator[list[str] | None] = _Validator(added="1.1") """:external:ref:`core-metadata-classifier`""" requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-dist`""" requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-python`""" # Because `Requires-External` allows for non-PEP 440 version specifiers, we # don't do any processing on the values. requires_external: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-requires-external`""" project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-project-url`""" # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation # regardless of metadata version. provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( added="2.1", ) """:external:ref:`core-metadata-provides-extra`""" provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-provides-dist`""" obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-obsoletes-dist`""" import_names: _Validator[list[str] | None] = _Validator(added="2.5") """:external:ref:`core-metadata-import-name`""" import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") """:external:ref:`core-metadata-import-namespace`""" requires: _Validator[list[str] | None] = _Validator(added="1.1") """``Requires`` (deprecated)""" provides: _Validator[list[str] | None] = _Validator(added="1.1") """``Provides`` (deprecated)""" obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") """``Obsoletes`` (deprecated)"""
def as_rfc822(self) -> RFC822Message: """ Return an RFC822 message with the metadata. """ message = RFC822Message() self._write_metadata(message) return message
def _write_metadata(self, message: RFC822Message) -> None: """ Return an RFC822 message with the metadata. """ for name, validator in self.__class__.__dict__.items(): if isinstance(validator, _Validator) and name != "description": value = getattr(self, name) email_name = _RAW_TO_EMAIL_MAPPING[name] if value is not None: if email_name == "project-url": for label, url in value.items(): message[email_name] = f"{label}, {url}" elif email_name == "keywords": message[email_name] = ",".join(value) elif email_name == "import-name" and value == []: message[email_name] = "" elif isinstance(value, list): for item in value: message[email_name] = str(item) else: message[email_name] = str(value)
# The description is a special case because it is in the body of the message. if self.description is not None: message.set_payload(self.description)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635from __future__ import annotations
import dataclassesimport loggingimport refrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetimefrom typing import ( TYPE_CHECKING, Any, Callable, Protocol, TypeVar,)
from .markers import Markerfrom .specifiers import SpecifierSetfrom .utils import NormalizedName, is_normalized_namefrom .version import Version
if TYPE_CHECKING: # pragma: no cover from pathlib import Path
from typing_extensions import Self
_logger = logging.getLogger(__name__)
__all__ = [ "Package", "PackageArchive", "PackageDirectory", "PackageSdist", "PackageVcs", "PackageWheel", "Pylock", "PylockUnsupportedVersionError", "PylockValidationError", "is_valid_pylock_path",]
_T = TypeVar("_T")_T2 = TypeVar("_T2")
class _FromMappingProtocol(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$")
def is_valid_pylock_path(path: Path) -> bool: """Check if the given path is a valid pylock file path.""" return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))
def _toml_key(key: str) -> str: return key.replace("_", "-")
def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 if isinstance(value, (Version, Marker, SpecifierSet)): return str(value) if isinstance(value, Sequence) and key == "environments": return [str(v) for v in value] return value
def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return { _toml_key(key): _toml_value(key, value) for key, value in data if value is not None }
def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type): raise PylockValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value
def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _PylockRequiredKeyError(key) return value
def _get_sequence( d: Mapping[str, Any], expected_item_type: type[_T], key: str) -> Sequence[_T] | None: """Get a list value from the dictionary and verify it's the expected items type.""" if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] return None if isinstance(value, (str, bytes)): # special case: str and bytes are Sequences, but we want to reject it raise PylockValidationError( f"Unexpected type {type(value).__name__} (expected Sequence)", context=key, ) for i, item in enumerate(value): if not isinstance(item, expected_item_type): raise PylockValidationError( f"Unexpected type {type(item).__name__} " f"(expected {expected_item_type.__name__})", context=f"{key}[{i}]", ) return value
def _get_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str,) -> _T2 | None: """Get a value from the dictionary, verify it's the expected type, and convert to the target type.
This assumes the target_type constructor accepts the value. """ if (value := _get(d, expected_type, key)) is None: return None try: return target_type(value) except Exception as e: raise PylockValidationError(e, context=key) from e
def _get_required_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str,) -> _T2: """Get a required value from the dict, verify it's the expected type, and convert to the target type.""" if (value := _get_as(d, expected_type, target_type, key)) is None: raise _PylockRequiredKeyError(key) return value
def _get_sequence_as( d: Mapping[str, Any], expected_item_type: type[_T], target_item_type: Callable[[_T], _T2], key: str,) -> list[_T2] | None: """Get list value from dictionary and verify expected items type.""" if (value := _get_sequence(d, expected_item_type, key)) is None: return None result = [] try: for item in value: typed_item = target_item_type(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result
def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise PylockValidationError(e, context=key) from e
def _get_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str) -> list[_FromMappingProtocolT] | None: """Get a list value from the dictionary and convert its items to a dataclass.""" if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] return None result: list[_FromMappingProtocolT] = [] try: for item in value: typed_item = target_item_type._from_dict(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result
def _get_required_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str) -> Sequence[_FromMappingProtocolT]: """Get a required list value from the dictionary and convert its items to a dataclass.""" if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: raise _PylockRequiredKeyError(key) return result
def _validate_normalized_name(name: str) -> NormalizedName: """Validate that a string is a NormalizedName.""" if not is_normalized_name(name): raise PylockValidationError(f"Name {name!r} is not normalized") return NormalizedName(name)
def _validate_path_url(path: str | None, url: str | None) -> None: if not path and not url: raise PylockValidationError("path or url must be provided")
def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: if not hashes: raise PylockValidationError("At least one hash must be provided") if not all(isinstance(hash_val, str) for hash_val in hashes.values()): raise PylockValidationError("Hash values must be strings") return hashes
class PylockValidationError(Exception): """Raised when when input data is not spec-compliant."""
context: str | None = None message: str
def __init__( self, cause: str | Exception, *, context: str | None = None, ) -> None: if isinstance(cause, PylockValidationError): if cause.context: self.context = ( f"{context}.{cause.context}" if context else cause.context ) else: self.context = context self.message = cause.message else: self.context = context self.message = str(cause)
def __str__(self) -> str: if self.context: return f"{self.message} in {self.context!r}" return self.message
class _PylockRequiredKeyError(PylockValidationError): def __init__(self, key: str) -> None: super().__init__("Missing required value", context=key)
class PylockUnsupportedVersionError(PylockValidationError): """Raised when encountering an unsupported `lock_version`."""
@dataclass(frozen=True, init=False)class PackageVcs: type: str url: str | None = None path: str | None = None requested_revision: str | None = None commit_id: str # type: ignore[misc] subdirectory: str | None = None
def __init__( self, *, type: str, url: str | None = None, path: str | None = None, requested_revision: str | None = None, commit_id: str, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "type", type) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "requested_revision", requested_revision) object.__setattr__(self, "commit_id", commit_id) object.__setattr__(self, "subdirectory", subdirectory)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_vcs = cls( type=_get_required(d, str, "type"), url=_get(d, str, "url"), path=_get(d, str, "path"), requested_revision=_get(d, str, "requested-revision"), commit_id=_get_required(d, str, "commit-id"), subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_vcs.path, package_vcs.url) return package_vcs
@dataclass(frozen=True, init=False)class PackageDirectory: path: str editable: bool | None = None subdirectory: str | None = None
def __init__( self, *, path: str, editable: bool | None = None, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "path", path) object.__setattr__(self, "editable", editable) object.__setattr__(self, "subdirectory", subdirectory)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: return cls( path=_get_required(d, str, "path"), editable=_get(d, bool, "editable"), subdirectory=_get(d, str, "subdirectory"), )
@dataclass(frozen=True, init=False)class PackageArchive: url: str | None = None path: str | None = None size: int | None = None upload_time: datetime | None = None hashes: Mapping[str, str] # type: ignore[misc] subdirectory: str | None = None
def __init__( self, *, url: str | None = None, path: str | None = None, size: int | None = None, upload_time: datetime | None = None, hashes: Mapping[str, str], subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "hashes", hashes) object.__setattr__(self, "subdirectory", subdirectory)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_archive = cls( url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), upload_time=_get(d, datetime, "upload-time"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_archive.path, package_archive.url) return package_archive
@dataclass(frozen=True, init=False)class PackageSdist: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc]
def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_sdist = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_sdist.path, package_sdist.url) return package_sdist
@dataclass(frozen=True, init=False)class PackageWheel: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc]
def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_wheel = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_wheel.path, package_wheel.url) return package_wheel
@dataclass(frozen=True, init=False)class Package: name: NormalizedName version: Version | None = None marker: Marker | None = None requires_python: SpecifierSet | None = None dependencies: Sequence[Mapping[str, Any]] | None = None vcs: PackageVcs | None = None directory: PackageDirectory | None = None archive: PackageArchive | None = None index: str | None = None sdist: PackageSdist | None = None wheels: Sequence[PackageWheel] | None = None attestation_identities: Sequence[Mapping[str, Any]] | None = None tool: Mapping[str, Any] | None = None
def __init__( self, *, name: NormalizedName, version: Version | None = None, marker: Marker | None = None, requires_python: SpecifierSet | None = None, dependencies: Sequence[Mapping[str, Any]] | None = None, vcs: PackageVcs | None = None, directory: PackageDirectory | None = None, archive: PackageArchive | None = None, index: str | None = None, sdist: PackageSdist | None = None, wheels: Sequence[PackageWheel] | None = None, attestation_identities: Sequence[Mapping[str, Any]] | None = None, tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "version", version) object.__setattr__(self, "marker", marker) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "dependencies", dependencies) object.__setattr__(self, "vcs", vcs) object.__setattr__(self, "directory", directory) object.__setattr__(self, "archive", archive) object.__setattr__(self, "index", index) object.__setattr__(self, "sdist", sdist) object.__setattr__(self, "wheels", wheels) object.__setattr__(self, "attestation_identities", attestation_identities) object.__setattr__(self, "tool", tool)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package = cls( name=_get_required_as(d, str, _validate_normalized_name, "name"), version=_get_as(d, str, Version, "version"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] marker=_get_as(d, str, Marker, "marker"), vcs=_get_object(d, PackageVcs, "vcs"), directory=_get_object(d, PackageDirectory, "directory"), archive=_get_object(d, PackageArchive, "archive"), index=_get(d, str, "index"), sdist=_get_object(d, PackageSdist, "sdist"), wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) distributions = bool(package.sdist) + len(package.wheels or []) direct_urls = ( bool(package.vcs) + bool(package.directory) + bool(package.archive) ) if distributions > 0 and direct_urls > 0: raise PylockValidationError( "None of vcs, directory, archive must be set if sdist or wheels are set" ) if distributions == 0 and direct_urls != 1: raise PylockValidationError( "Exactly one of vcs, directory, archive must be set " "if sdist and wheels are not set" ) try: for i, attestation_identity in enumerate( # noqa: B007 package.attestation_identities or [] ): _get_required(attestation_identity, str, "kind") except Exception as e: raise PylockValidationError( e, context=f"attestation-identities[{i}]" ) from e return package
@property def is_direct(self) -> bool: return not (self.sdist or self.wheels)
@dataclass(frozen=True, init=False)class Pylock: """A class representing a pylock file."""
lock_version: Version environments: Sequence[Marker] | None = None requires_python: SpecifierSet | None = None extras: Sequence[NormalizedName] | None = None dependency_groups: Sequence[str] | None = None default_groups: Sequence[str] | None = None created_by: str # type: ignore[misc] packages: Sequence[Package] # type: ignore[misc] tool: Mapping[str, Any] | None = None
def __init__( self, *, lock_version: Version, environments: Sequence[Marker] | None = None, requires_python: SpecifierSet | None = None, extras: Sequence[NormalizedName] | None = None, dependency_groups: Sequence[str] | None = None, default_groups: Sequence[str] | None = None, created_by: str, packages: Sequence[Package], tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "lock_version", lock_version) object.__setattr__(self, "environments", environments) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "extras", extras) object.__setattr__(self, "dependency_groups", dependency_groups) object.__setattr__(self, "default_groups", default_groups) object.__setattr__(self, "created_by", created_by) object.__setattr__(self, "packages", packages) object.__setattr__(self, "tool", tool)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: pylock = cls( lock_version=_get_required_as(d, str, Version, "lock-version"), environments=_get_sequence_as(d, str, Marker, "environments"), extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), dependency_groups=_get_sequence(d, str, "dependency-groups"), default_groups=_get_sequence(d, str, "default-groups"), created_by=_get_required(d, str, "created-by"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), packages=_get_required_sequence_of_objects(d, Package, "packages"), tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) if not Version("1") <= pylock.lock_version < Version("2"): raise PylockUnsupportedVersionError( f"pylock version {pylock.lock_version} is not supported" ) if pylock.lock_version > Version("1.0"): _logger.warning( "pylock minor version %s is not supported", pylock.lock_version ) return pylock
@classmethod def from_dict(cls, d: Mapping[str, Any], /) -> Self: """Create and validate a Pylock instance from a TOML dictionary.
Raises :class:`PylockValidationError` if the input data is not spec-compliant. """ return cls._from_dict(d)
def to_dict(self) -> Mapping[str, Any]: """Convert the Pylock instance to a TOML dictionary.""" return dataclasses.asdict(self, dict_factory=_toml_dict_factory)
def validate(self) -> None: """Validate the Pylock instance against the specification.
Raises :class:`PylockValidationError` otherwise.""" self.from_dict(self.to_dict())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.from __future__ import annotations
from typing import Iterator
from ._parser import parse_requirement as _parse_requirementfrom ._tokenizer import ParserSyntaxErrorfrom .markers import Marker, _normalize_extra_valuesfrom .specifiers import SpecifierSetfrom .utils import canonicalize_name
class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """
class Requirement: """Parse a requirement.
Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """
# TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name?
def __init__(self, requirement_string: str) -> None: try: parsed = _parse_requirement(requirement_string) except ParserSyntaxError as e: raise InvalidRequirement(str(e)) from e
self.name: str = parsed.name self.url: str | None = parsed.url or None self.extras: set[str] = set(parsed.extras or []) self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) self.marker: Marker | None = None if parsed.marker is not None: self.marker = Marker.__new__(Marker) self.marker._markers = _normalize_extra_values(parsed.marker)
def _iter_parts(self, name: str) -> Iterator[str]: yield name
if self.extras: formatted_extras = ",".join(sorted(self.extras)) yield f"[{formatted_extras}]"
if self.specifier: yield str(self.specifier)
if self.url: yield f" @ {self.url}" if self.marker: yield " "
if self.marker: yield f"; {self.marker}"
def __str__(self) -> str: return "".join(self._iter_parts(self.name))
def __repr__(self) -> str: return f"<{self.__class__.__name__}('{self}')>"
def __hash__(self) -> int: return hash(tuple(self._iter_parts(canonicalize_name(self.name))))
def __eq__(self, other: object) -> bool: if not isinstance(other, Requirement): return NotImplemented
return ( canonicalize_name(self.name) == canonicalize_name(other.name) and self.extras == other.extras and self.specifier == other.specifier and self.url == other.url and self.marker == other.marker )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.""".. testsetup::
from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier from packaging.version import Version"""
from __future__ import annotations
import abcimport itertoolsimport refrom typing import Callable, Final, Iterable, Iterator, TypeVar, Union
from .utils import canonicalize_versionfrom .version import InvalidVersion, Version
UnparsedVersion = Union[Version, str]UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)CallableOperator = Callable[[Version, str], bool]
def _coerce_version(version: UnparsedVersion) -> Version | None: if not isinstance(version, Version): try: version = Version(version) except InvalidVersion: return None return version
def _public_version(version: Version) -> Version: return version.__replace__(local=None)
def _base_version(version: Version) -> Version: return version.__replace__(pre=None, post=None, dev=None, local=None)
class InvalidSpecifier(ValueError): """ Raised when attempting to create a :class:`Specifier` with a specifier string that is invalid.
>>> Specifier("lolwat") Traceback (most recent call last): ... packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' """
class BaseSpecifier(metaclass=abc.ABCMeta): __slots__ = () __match_args__ = ("_str",)
@property def _str(self) -> str: """Internal property for match_args""" return str(self)
@abc.abstractmethod def __str__(self) -> str: """ Returns the str representation of this Specifier-like object. This should be representative of the Specifier itself. """
@abc.abstractmethod def __hash__(self) -> int: """ Returns a hash value for this Specifier-like object. """
@abc.abstractmethod def __eq__(self, other: object) -> bool: """ Returns a boolean representing whether or not the two Specifier-like objects are equal.
:param other: The other object to check against. """
@property @abc.abstractmethod def prereleases(self) -> bool | None: """Whether or not pre-releases as a whole are allowed.
This can be set to either ``True`` or ``False`` to explicitly enable or disable prereleases or it can be set to ``None`` (the default) to use default semantics. """
@prereleases.setter # noqa: B027 def prereleases(self, value: bool) -> None: """Setter for :attr:`prereleases`.
:param value: The value to set. """
@abc.abstractmethod def contains(self, item: str, prereleases: bool | None = None) -> bool: """ Determines if the given item is contained within this specifier. """
@abc.abstractmethod def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None ) -> Iterator[UnparsedVersionVar]: """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """
class Specifier(BaseSpecifier): """This class abstracts handling of version specifiers.
.. tip::
It is generally not required to instantiate this manually. You should instead prefer to work with :class:`SpecifierSet` instead, which can parse comma-separated version specifiers (which is what package metadata contains). """
__slots__ = ("_prereleases", "_spec", "_spec_version")
_operator_regex_str = r""" (?P<operator>(~=|==|!=|<=|>=|<|>|===)) """ _version_regex_str = r""" (?P<version> (?: # The identity operators allow for an escape hatch that will # do an exact string match of the version you wish to install. # This will not be parsed by PEP 440 and we cannot determine # any semantic meaning from it. This operator is discouraged # but included entirely as an escape hatch. (?<====) # Only match for the identity operator \s* [^\s;)]* # The arbitrary version can be just about anything, # we match everything except for whitespace, a # semi-colon for marker support, and a closing paren # since versions can be enclosed in them. ) | (?: # The (non)equality operators allow for wild card and local # versions to be specified so we have to define these two # operators separately to enable that. (?<===|!=) # Only match for equals and not equals
\s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release
# You cannot use a wild card and a pre-release, post-release, a dev or # local version together so group them with a | and make them optional. (?: \.\* # Wild card syntax of .* | (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local )? ) | (?: # The compatible operator requires at least two digits in the # release segment. (?<=~=) # Only match for the compatible operator
\s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) | (?: # All other operators only allow a sub set of what the # (non)equality operators do. Specifically they do not allow # local versions to be specified nor do they allow the prefix # matching wild cards. (?<!==|!=|~=) # We have special cases for these # operators so we want to make sure they # don't match here.
\s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) ) """
_regex = re.compile( r"\s*" + _operator_regex_str + _version_regex_str + r"\s*", re.VERBOSE | re.IGNORECASE, )
_operators: Final = { "~=": "compatible", "==": "equal", "!=": "not_equal", "<=": "less_than_equal", ">=": "greater_than_equal", "<": "less_than", ">": "greater_than", "===": "arbitrary", }
def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: """Initialize a Specifier instance.
:param spec: The string representation of a specifier which will be parsed and normalized before use. :param prereleases: This tells the specifier if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given specifier is invalid (i.e. bad syntax). """ match = self._regex.fullmatch(spec) if not match: raise InvalidSpecifier(f"Invalid specifier: {spec!r}")
self._spec: tuple[str, str] = ( match.group("operator").strip(), match.group("version").strip(), )
# Store whether or not this Specifier should accept prereleases self._prereleases = prereleases
# Specifier version cache self._spec_version: tuple[str, Version] | None = None
def _get_spec_version(self, version: str) -> Version | None: """One element cache, as only one spec Version is needed per Specifier.""" if self._spec_version is not None and self._spec_version[0] == version: return self._spec_version[1]
version_specifier = _coerce_version(version) if version_specifier is None: return None
self._spec_version = (version, version_specifier) return version_specifier
def _require_spec_version(self, version: str) -> Version: """Get spec version, asserting it's valid (not for === operator).
This method should only be called for operators where version strings are guaranteed to be valid PEP 440 versions (not ===). """ spec_version = self._get_spec_version(version) assert spec_version is not None return spec_version
@property def prereleases(self) -> bool | None: # If there is an explicit prereleases set for this, then we'll just # blindly use that. if self._prereleases is not None: return self._prereleases
# Only the "!=" operator does not imply prereleases when # the version in the specifier is a prerelease. operator, version_str = self._spec if operator != "!=": # The == specifier with trailing .* cannot include prereleases # e.g. "==1.0a1.*" is not valid. if operator == "==" and version_str.endswith(".*"): return False
# "===" can have arbitrary string versions, so we cannot parse # those, we take prereleases as unknown (None) for those. version = self._get_spec_version(version_str) if version is None: return None
# For all other operators, use the check if spec Version # object implies pre-releases. if version.is_prerelease: return True
return False
@prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value
@property def operator(self) -> str: """The operator of this specifier.
>>> Specifier("==1.2.3").operator '==' """ return self._spec[0]
@property def version(self) -> str: """The version of this specifier.
>>> Specifier("==1.2.3").version '1.2.3' """ return self._spec[1]
def __repr__(self) -> str: """A representation of the Specifier that shows all internal state.
>>> Specifier('>=1.0.0') <Specifier('>=1.0.0')> >>> Specifier('>=1.0.0', prereleases=False) <Specifier('>=1.0.0', prereleases=False)> >>> Specifier('>=1.0.0', prereleases=True) <Specifier('>=1.0.0', prereleases=True)> """ pre = ( f", prereleases={self.prereleases!r}" if self._prereleases is not None else "" )
return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
def __str__(self) -> str: """A string representation of the Specifier that can be round-tripped.
>>> str(Specifier('>=1.0.0')) '>=1.0.0' >>> str(Specifier('>=1.0.0', prereleases=False)) '>=1.0.0' """ return "{}{}".format(*self._spec)
@property def _canonical_spec(self) -> tuple[str, str]: operator, version = self._spec if operator == "===" or version.endswith(".*"): return operator, version
spec_version = self._require_spec_version(version)
canonical_version = canonicalize_version( spec_version, strip_trailing_zero=(operator != "~=") )
return operator, canonical_version
def __hash__(self) -> int: return hash(self._canonical_spec)
def __eq__(self, other: object) -> bool: """Whether or not the two Specifier-like objects are equal.
:param other: The other object to check against.
The value of :attr:`prereleases` is ignored.
>>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") True >>> (Specifier("==1.2.3", prereleases=False) == ... Specifier("==1.2.3", prereleases=True)) True >>> Specifier("==1.2.3") == "==1.2.3" True >>> Specifier("==1.2.3") == Specifier("==1.2.4") False >>> Specifier("==1.2.3") == Specifier("~=1.2.3") False """ if isinstance(other, str): try: other = self.__class__(str(other)) except InvalidSpecifier: return NotImplemented elif not isinstance(other, self.__class__): return NotImplemented
return self._canonical_spec == other._canonical_spec
def _get_operator(self, op: str) -> CallableOperator: operator_callable: CallableOperator = getattr( self, f"_compare_{self._operators[op]}" ) return operator_callable
def _compare_compatible(self, prospective: Version, spec: str) -> bool: # Compatible releases have an equivalent combination of >= and ==. That # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to # implement this in terms of the other specifiers instead of # implementing it ourselves. The only thing we need to do is construct # the other specifiers.
# We want everything but the last item in the version, but we want to # ignore suffix segments. prefix = _version_join( list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] )
# Add the prefix notation to the end of our string prefix += ".*"
return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( prospective, prefix )
def _compare_equal(self, prospective: Version, spec: str) -> bool: # We need special logic to handle prefix matching if spec.endswith(".*"): # In the case of prefix matching we want to ignore local segment. normalized_prospective = canonicalize_version( _public_version(prospective), strip_trailing_zero=False ) # Get the normalized version string ignoring the trailing .* normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) # Split the spec out by bangs and dots, and pretend that there is # an implicit dot in between a release segment and a pre-release segment. split_spec = _version_split(normalized_spec)
# Split the prospective version out by bangs and dots, and pretend # that there is an implicit dot in between a release segment and # a pre-release segment. split_prospective = _version_split(normalized_prospective)
# 0-pad the prospective version before shortening it to get the correct # shortened version. padded_prospective, _ = _pad_version(split_prospective, split_spec)
# Shorten the prospective version to be the same length as the spec # so that we can determine if the specifier is a prefix of the # prospective version or not. shortened_prospective = padded_prospective[: len(split_spec)]
return shortened_prospective == split_spec else: # Convert our spec string into a Version spec_version = self._require_spec_version(spec)
# If the specifier does not have a local segment, then we want to # act as if the prospective version also does not have a local # segment. if not spec_version.local: prospective = _public_version(prospective)
return prospective == spec_version
def _compare_not_equal(self, prospective: Version, spec: str) -> bool: return not self._compare_equal(prospective, spec)
def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: # NB: Local version identifiers are NOT permitted in the version # specifier, so local version labels can be universally removed from # the prospective version. return _public_version(prospective) <= self._require_spec_version(spec)
def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: # NB: Local version identifiers are NOT permitted in the version # specifier, so local version labels can be universally removed from # the prospective version. return _public_version(prospective) >= self._require_spec_version(spec)
def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = self._require_spec_version(spec_str)
# Check to see if the prospective version is less than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective < spec: return False
# This special case is here so that, unless the specifier itself # includes is a pre-release version, that we do not accept pre-release # versions for the version mentioned in the specifier (e.g. <3.1 should # not match 3.1.dev0, but should match 3.0.dev0). if ( not spec.is_prerelease and prospective.is_prerelease and _base_version(prospective) == _base_version(spec) ): return False
# If we've gotten to here, it means that prospective version is both # less than the spec version *and* it's not a pre-release of the same # version in the spec. return True
def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = self._require_spec_version(spec_str)
# Check to see if the prospective version is greater than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective > spec: return False
# This special case is here so that, unless the specifier itself # includes is a post-release version, that we do not accept # post-release versions for the version mentioned in the specifier # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). if ( not spec.is_postrelease and prospective.is_postrelease and _base_version(prospective) == _base_version(spec) ): return False
# Ensure that we do not allow a local version of the version mentioned # in the specifier, which is technically greater than, to match. if prospective.local is not None and _base_version( prospective ) == _base_version(spec): return False
# If we've gotten to here, it means that prospective version is both # greater than the spec version *and* it's not a pre-release of the # same version in the spec. return True
def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool: return str(prospective).lower() == str(spec).lower()
def __contains__(self, item: str | Version) -> bool: """Return whether or not the item is contained in this specifier.
:param item: The item to check for.
This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed.
>>> "1.2.3" in Specifier(">=1.2.3") True >>> Version("1.2.3") in Specifier(">=1.2.3") True >>> "1.0.0" in Specifier(">=1.2.3") False >>> "1.3.0a1" in Specifier(">=1.2.3") True >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) True """ return self.contains(item)
def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: """Return whether or not the item is contained in this specifier.
:param item: The item to check for, which can be a version string or a :class:`Version` instance. :param prereleases: Whether or not to match prereleases with this Specifier. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases, as there are no other versions.
>>> Specifier(">=1.2.3").contains("1.2.3") True >>> Specifier(">=1.2.3").contains(Version("1.2.3")) True >>> Specifier(">=1.2.3").contains("1.0.0") False >>> Specifier(">=1.2.3").contains("1.3.0a1") True >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1") False >>> Specifier(">=1.2.3").contains("1.3.0a1") True """
return bool(list(self.filter([item], prereleases=prereleases)))
def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None ) -> Iterator[UnparsedVersionVar]: """Filter items in the given iterable, that match the specifier.
:param iterable: An iterable that can contain version strings and :class:`Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions.
>>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) ['1.2.3', '1.3', <Version('1.4')>] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] """ prereleases_versions = [] found_non_prereleases = False
# Determine if to include prereleases by default include_prereleases = ( prereleases if prereleases is not None else self.prereleases )
# Get the matching operator operator_callable = self._get_operator(self.operator)
# Filter versions for version in iterable: parsed_version = _coerce_version(version) if parsed_version is None: # === operator can match arbitrary (non-version) strings if self.operator == "===" and self._compare_arbitrary( version, self.version ): yield version elif operator_callable(parsed_version, self.version): # If it's not a prerelease or prereleases are allowed, yield it directly if not parsed_version.is_prerelease or include_prereleases: found_non_prereleases = True yield version # Otherwise collect prereleases for potential later use elif prereleases is None and self._prereleases is not False: prereleases_versions.append(version)
# If no non-prereleases were found and prereleases weren't # explicitly forbidden, yield the collected prereleases if ( not found_non_prereleases and prereleases is None and self._prereleases is not False ): yield from prereleases_versions
_prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)")
def _version_split(version: str) -> list[str]: """Split version into components.
The split components are intended for version comparison. The logic does not attempt to retain the original version string, so joining the components back with :func:`_version_join` may not produce the original version string. """ result: list[str] = []
epoch, _, rest = version.rpartition("!") result.append(epoch or "0")
for item in rest.split("."): match = _prefix_regex.fullmatch(item) if match: result.extend(match.groups()) else: result.append(item) return result
def _version_join(components: list[str]) -> str: """Join split version components into a version string.
This function assumes the input came from :func:`_version_split`, where the first component must be the epoch (either empty or numeric), and all other components numeric. """ epoch, *rest = components return f"{epoch}!{'.'.join(rest)}"
def _is_not_suffix(segment: str) -> bool: return not any( segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") )
def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]: left_split, right_split = [], []
# Get the release segment of our versions left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
# Get the rest of our versions left_split.append(left[len(left_split[0]) :]) right_split.append(right[len(right_split[0]) :])
# Insert our padding left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
return ( list(itertools.chain.from_iterable(left_split)), list(itertools.chain.from_iterable(right_split)), )
class SpecifierSet(BaseSpecifier): """This class abstracts handling of a set of version specifiers.
It can be passed a single specifier (``>=3.0``), a comma-separated list of specifiers (``>=3.0,!=3.1``), or no specifier at all. """
__slots__ = ("_prereleases", "_specs")
def __init__( self, specifiers: str | Iterable[Specifier] = "", prereleases: bool | None = None, ) -> None: """Initialize a SpecifierSet instance.
:param specifiers: The string representation of a specifier or a comma-separated list of specifiers which will be parsed and normalized before use. May also be an iterable of ``Specifier`` instances, which will be used as is. :param prereleases: This tells the SpecifierSet if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers.
:raises InvalidSpecifier: If the given ``specifiers`` are not parseable than this exception will be raised. """
if isinstance(specifiers, str): # Split on `,` to break each individual specifier into its own item, and # strip each item to remove leading/trailing whitespace. split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
# Make each individual specifier a Specifier and save in a frozen set # for later. self._specs = frozenset(map(Specifier, split_specifiers)) else: # Save the supplied specifiers in a frozen set. self._specs = frozenset(specifiers)
# Store our prereleases value so we can use it later to determine if # we accept prereleases or not. self._prereleases = prereleases
@property def prereleases(self) -> bool | None: # If we have been given an explicit prerelease modifier, then we'll # pass that through here. if self._prereleases is not None: return self._prereleases
# If we don't have any specifiers, and we don't have a forced value, # then we'll just return None since we don't know if this should have # pre-releases or not. if not self._specs: return None
# Otherwise we'll see if any of the given specifiers accept # prereleases, if any of them do we'll return True, otherwise False. if any(s.prereleases for s in self._specs): return True
return None
@prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value
def __repr__(self) -> str: """A representation of the specifier set that shows all internal state.
Note that the ordering of the individual specifiers within the set may not match the input string.
>>> SpecifierSet('>=1.0.0,!=2.0.0') <SpecifierSet('!=2.0.0,>=1.0.0')> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=False)> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=True)> """ pre = ( f", prereleases={self.prereleases!r}" if self._prereleases is not None else "" )
return f"<SpecifierSet({str(self)!r}{pre})>"
def __str__(self) -> str: """A string representation of the specifier set that can be round-tripped.
Note that the ordering of the individual specifiers within the set may not match the input string.
>>> str(SpecifierSet(">=1.0.0,!=1.0.1")) '!=1.0.1,>=1.0.0' >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) '!=1.0.1,>=1.0.0' """ return ",".join(sorted(str(s) for s in self._specs))
def __hash__(self) -> int: return hash(self._specs)
def __and__(self, other: SpecifierSet | str) -> SpecifierSet: """Return a SpecifierSet which is a combination of the two sets.
:param other: The other object to combine with.
>>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')> >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')> """ if isinstance(other, str): other = SpecifierSet(other) elif not isinstance(other, SpecifierSet): return NotImplemented
specifier = SpecifierSet() specifier._specs = frozenset(self._specs | other._specs)
if self._prereleases is None and other._prereleases is not None: specifier._prereleases = other._prereleases elif ( self._prereleases is not None and other._prereleases is None ) or self._prereleases == other._prereleases: specifier._prereleases = self._prereleases else: raise ValueError( "Cannot combine SpecifierSets with True and False prerelease overrides." )
return specifier
def __eq__(self, other: object) -> bool: """Whether or not the two SpecifierSet-like objects are equal.
:param other: The other object to check against.
The value of :attr:`prereleases` is ignored.
>>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") True >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) True >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" True >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") False >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") False """ if isinstance(other, (str, Specifier)): other = SpecifierSet(str(other)) elif not isinstance(other, SpecifierSet): return NotImplemented
return self._specs == other._specs
def __len__(self) -> int: """Returns the number of specifiers in this specifier set.""" return len(self._specs)
def __iter__(self) -> Iterator[Specifier]: """ Returns an iterator over all the underlying :class:`Specifier` instances in this specifier set.
>>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) [<Specifier('!=1.0.1')>, <Specifier('>=1.0.0')>] """ return iter(self._specs)
def __contains__(self, item: UnparsedVersion) -> bool: """Return whether or not the item is contained in this specifier.
:param item: The item to check for.
This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed.
>>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") True >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") True >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") False >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") True >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) True """ return self.contains(item)
def contains( self, item: UnparsedVersion, prereleases: bool | None = None, installed: bool | None = None, ) -> bool: """Return whether or not the item is contained in this SpecifierSet.
:param item: The item to check for, which can be a version string or a :class:`Version` instance. :param prereleases: Whether or not to match prereleases with this SpecifierSet. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases, as there are no other versions. :param installed: Whether or not the item is installed. If set to ``True``, it will accept prerelease versions even if the specifier does not allow them.
>>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") False >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") True >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1") False >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) True """ version = _coerce_version(item)
if version is not None and installed and version.is_prerelease: prereleases = True
check_item = item if version is None else version return bool(list(self.filter([check_item], prereleases=prereleases)))
def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None ) -> Iterator[UnparsedVersionVar]: """Filter items in the given iterable, that match the specifiers in this set.
:param iterable: An iterable that can contain version strings and :class:`Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions.
>>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) ['1.3', <Version('1.4')>] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1']
An "empty" SpecifierSet will filter items based on the presence of prerelease versions in the set.
>>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet("").filter(["1.5a1"])) ['1.5a1'] >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] """ # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None and self.prereleases is not None: prereleases = self.prereleases
# If we have any specifiers, then we want to wrap our iterable in the # filter method for each one, this will act as a logical AND amongst # each specifier. if self._specs: # When prereleases is None, we need to let all versions through # the individual filters, then decide about prereleases at the end # based on whether any non-prereleases matched ALL specs. for spec in self._specs: iterable = spec.filter( iterable, prereleases=True if prereleases is None else prereleases )
if prereleases is not None: # If we have a forced prereleases value, # we can immediately return the iterator. return iter(iterable) else: # Handle empty SpecifierSet cases where prereleases is not None. if prereleases is True: return iter(iterable)
if prereleases is False: return ( item for item in iterable if (version := _coerce_version(item)) is None or not version.is_prerelease )
# Finally if prereleases is None, apply PEP 440 logic: # exclude prereleases unless there are no final releases that matched. filtered_items: list[UnparsedVersionVar] = [] found_prereleases: list[UnparsedVersionVar] = [] found_final_release = False
for item in iterable: parsed_version = _coerce_version(item) # Arbitrary strings are always included as it is not # possible to determine if they are prereleases, # and they have already passed all specifiers. if parsed_version is None: filtered_items.append(item) found_prereleases.append(item) elif parsed_version.is_prerelease: found_prereleases.append(item) else: filtered_items.append(item) found_final_release = True
return iter(filtered_items if found_final_release else found_prereleases)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
from __future__ import annotations
import loggingimport platformimport reimport structimport subprocessimport sysimport sysconfigfrom importlib.machinery import EXTENSION_SUFFIXESfrom typing import ( Any, Iterable, Iterator, Sequence, Tuple, cast,)
from . import _manylinux, _musllinux
logger = logging.getLogger(__name__)
PythonVersion = Sequence[int]AppleVersion = Tuple[int, int]
INTERPRETER_SHORT_NAMES: dict[str, str] = { "python": "py", # Generic. "cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy",}
_32_BIT_INTERPRETER = struct.calcsize("P") == 4
class Tag: """ A representation of the tag triple for a wheel.
Instances are considered immutable and thus are hashable. Equality checking is also supported. """
__slots__ = ["_abi", "_hash", "_interpreter", "_platform"]
def __init__(self, interpreter: str, abi: str, platform: str) -> None: self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() # The __hash__ of every single element in a Set[Tag] will be evaluated each time # that a set calls its `.disjoint()` method, which may be called hundreds of # times when scanning a page of links for packages with tags matching that # Set[Tag]. Pre-computing the value here produces significant speedups for # downstream consumers. self._hash = hash((self._interpreter, self._abi, self._platform))
@property def interpreter(self) -> str: return self._interpreter
@property def abi(self) -> str: return self._abi
@property def platform(self) -> str: return self._platform
def __eq__(self, other: object) -> bool: if not isinstance(other, Tag): return NotImplemented
return ( (self._hash == other._hash) # Short-circuit ASAP for perf reasons. and (self._platform == other._platform) and (self._abi == other._abi) and (self._interpreter == other._interpreter) )
def __hash__(self) -> int: return self._hash
def __str__(self) -> str: return f"{self._interpreter}-{self._abi}-{self._platform}"
def __repr__(self) -> str: return f"<{self} @ {id(self)}>"
def __setstate__(self, state: tuple[None, dict[str, Any]]) -> None: # The cached _hash is wrong when unpickling. _, slots = state for k, v in slots.items(): setattr(self, k, v) self._hash = hash((self._interpreter, self._abi, self._platform))
def parse_tag(tag: str) -> frozenset[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
Returning a set is required due to the possibility that the tag is a compressed tag set. """ tags = set() interpreters, abis, platforms = tag.split("-") for interpreter in interpreters.split("."): for abi in abis.split("."): for platform_ in platforms.split("."): tags.add(Tag(interpreter, abi, platform_)) return frozenset(tags)
def _get_config_var(name: str, warn: bool = False) -> int | str | None: value: int | str | None = sysconfig.get_config_var(name) if value is None and warn: logger.debug( "Config variable '%s' is unset, Python ABI tag may be incorrect", name ) return value
def _normalize_string(string: str) -> str: return string.replace(".", "_").replace("-", "_").replace(" ", "_")
def _is_threaded_cpython(abis: list[str]) -> bool: """ Determine if the ABI corresponds to a threaded (`--disable-gil`) build.
The threaded builds are indicated by a "t" in the abiflags. """ if len(abis) == 0: return False # expect e.g., cp313 m = re.match(r"cp\d+(.*)", abis[0]) if not m: return False abiflags = m.group(1) return "t" in abiflags
def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: """ Determine if the Python version supports abi3.
PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`) builds do not support abi3. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: py_version = tuple(py_version) # To allow for version comparison. abis = [] version = _version_nodot(py_version[:2]) threading = debug = pymalloc = ucs4 = "" with_debug = _get_config_var("Py_DEBUG", warn) has_refcount = hasattr(sys, "gettotalrefcount") # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled # extension modules is the best option. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 has_ext = "_d.pyd" in EXTENSION_SUFFIXES if with_debug or (with_debug is None and (has_refcount or has_ext)): debug = "d" if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): threading = "t" if py_version < (3, 8): with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) if with_pymalloc or with_pymalloc is None: pymalloc = "m" if py_version < (3, 3): unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) if unicode_size == 4 or ( unicode_size is None and sys.maxunicode == 0x10FFFF ): ucs4 = "u" elif debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}{threading}") abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") return abis
def cpython_tags( python_version: PythonVersion | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False,) -> Iterator[Tag]: """ Yields the tags for a CPython interpreter.
The tags consist of: - cp<python_version>-<abi>-<platform> - cp<python_version>-abi3-<platform> - cp<python_version>-none-<platform> - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.
If python_version only specifies a major version then user-provided ABIs and the 'none' ABItag will be used.
If 'abi3' or 'none' are specified in 'abis' then they will be yielded at their normal position and not at the beginning. """ if not python_version: python_version = sys.version_info[:2]
interpreter = f"cp{_version_nodot(python_version[:2])}"
if abis is None: abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else [] abis = list(abis) # 'abi3' and 'none' are explicitly handled later. for explicit_abi in ("abi3", "none"): try: abis.remove(explicit_abi) except ValueError: # noqa: PERF203 pass
platforms = list(platforms or platform_tags()) for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_)
threading = _is_threaded_cpython(abis) use_abi3 = _abi3_applies(python_version, threading) if use_abi3: yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
if use_abi3: for minor_version in range(python_version[1] - 1, 1, -1): for platform_ in platforms: version = _version_nodot((python_version[0], minor_version)) interpreter = f"cp{version}" yield Tag(interpreter, "abi3", platform_)
def _generic_abi() -> list[str]: """ Return the ABI tag based on EXT_SUFFIX. """ # The following are examples of `EXT_SUFFIX`. # We want to keep the parts which are related to the ABI and remove the # parts which are related to the platform: # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 # - mac: '.cpython-310-darwin.so' => cp310 # - win: '.cp310-win_amd64.pyd' => cp310 # - win: '.pyd' => cp37 (uses _cpython_abis()) # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' # => graalpy_38_native
ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") parts = ext_suffix.split(".") if len(parts) < 3: # CPython3.7 and earlier uses ".pyd" on Windows. return _cpython_abis(sys.version_info[:2]) soabi = parts[1] if soabi.startswith("cpython"): # non-windows abi = "cp" + soabi.split("-")[1] elif soabi.startswith("cp"): # windows abi = soabi.split("-")[0] elif soabi.startswith("pypy"): abi = "-".join(soabi.split("-")[:2]) elif soabi.startswith("graalpy"): abi = "-".join(soabi.split("-")[:3]) elif soabi: # pyston, ironpython, others? abi = soabi else: return [] return [_normalize_string(abi)]
def generic_tags( interpreter: str | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False,) -> Iterator[Tag]: """ Yields the tags for a generic interpreter.
The tags consist of: - <interpreter>-<abi>-<platform>
The "none" ABI will be added if it was not explicitly provided. """ if not interpreter: interp_name = interpreter_name() interp_version = interpreter_version(warn=warn) interpreter = f"{interp_name}{interp_version}" abis = _generic_abi() if abis is None else list(abis) platforms = list(platforms or platform_tags()) if "none" not in abis: abis.append("none") for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_)
def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: """ Yields Python versions in descending order.
After the latest version, the major-only version will be yielded, and then all previous versions of that major version. """ if len(py_version) > 1: yield f"py{_version_nodot(py_version[:2])}" yield f"py{py_version[0]}" if len(py_version) > 1: for minor in range(py_version[1] - 1, -1, -1): yield f"py{_version_nodot((py_version[0], minor))}"
def compatible_tags( python_version: PythonVersion | None = None, interpreter: str | None = None, platforms: Iterable[str] | None = None,) -> Iterator[Tag]: """ Yields the sequence of tags that are compatible with a specific version of Python.
The tags consist of: - py*-none-<platform> - <interpreter>-none-any # ... if `interpreter` is provided. - py*-none-any """ if not python_version: python_version = sys.version_info[:2] platforms = list(platforms or platform_tags()) for version in _py_interpreter_range(python_version): for platform_ in platforms: yield Tag(version, "none", platform_) if interpreter: yield Tag(interpreter, "none", "any") for version in _py_interpreter_range(python_version): yield Tag(version, "none", "any")
def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: if not is_32bit: return arch
if arch.startswith("ppc"): return "ppc"
return "i386"
def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: formats = [cpu_arch] if cpu_arch == "x86_64": if version < (10, 4): return [] formats.extend(["intel", "fat64", "fat32"])
elif cpu_arch == "i386": if version < (10, 4): return [] formats.extend(["intel", "fat32", "fat"])
elif cpu_arch == "ppc64": # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? if version > (10, 5) or version < (10, 4): return [] formats.append("fat64")
elif cpu_arch == "ppc": if version > (10, 6): return [] formats.extend(["fat32", "fat"])
if cpu_arch in {"arm64", "x86_64"}: formats.append("universal2")
if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: formats.append("universal")
return formats
def mac_platforms( version: AppleVersion | None = None, arch: str | None = None) -> Iterator[str]: """ Yields the platform tags for a macOS system.
The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system. """ version_str, _, cpu_arch = platform.mac_ver() if version is None: version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) if version == (10, 16): # When built against an older macOS SDK, Python will report macOS 10.16 # instead of the real version. version_str = subprocess.run( [ sys.executable, "-sS", "-c", "import platform; print(platform.mac_ver()[0])", ], check=True, env={"SYSTEM_VERSION_COMPAT": "0"}, stdout=subprocess.PIPE, text=True, ).stdout version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2])))
if arch is None: arch = _mac_arch(cpu_arch)
if (10, 0) <= version < (11, 0): # Prior to Mac OS 11, each yearly release of Mac OS bumped the # "minor" version number. The major version was always 10. major_version = 10 for minor_version in range(version[1], -1, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}"
if version >= (11, 0): # Starting with Mac OS 11, each yearly release bumps the major version # number. The minor versions are now the midyear updates. minor_version = 0 for major_version in range(version[0], 10, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}"
if version >= (11, 0): # Mac OS 11 on x86_64 is compatible with binaries from previous releases. # Arm64 support was introduced in 11.0, so no Arm binaries from previous # releases exist. # # However, the "universal2" binary format can have a # macOS version earlier than 11.0 when the x86_64 part of the binary supports # that version of macOS. major_version = 10 if arch == "x86_64": for minor_version in range(16, 3, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}" else: for minor_version in range(16, 3, -1): compat_version = major_version, minor_version binary_format = "universal2" yield f"macosx_{major_version}_{minor_version}_{binary_format}"
def ios_platforms( version: AppleVersion | None = None, multiarch: str | None = None) -> Iterator[str]: """ Yields the platform tags for an iOS system.
:param version: A two-item tuple specifying the iOS version to generate platform tags for. Defaults to the current iOS version. :param multiarch: The CPU architecture+ABI to generate platform tags for - (the value used by `sys.implementation._multiarch` e.g., `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current multiarch value. """ if version is None: # if iOS is the current platform, ios_ver *must* be defined. However, # it won't exist for CPython versions before 3.13, which causes a mypy # error. _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] version = cast("AppleVersion", tuple(map(int, release.split(".")[:2])))
if multiarch is None: multiarch = sys.implementation._multiarch multiarch = multiarch.replace("-", "_")
ios_platform_template = "ios_{major}_{minor}_{multiarch}"
# Consider any iOS major.minor version from the version requested, down to # 12.0. 12.0 is the first iOS version that is known to have enough features # to support CPython. Consider every possible minor release up to X.9. There # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra # candidates that won't ever match doesn't really hurt, and it saves us from # having to keep an explicit list of known iOS versions in the code. Return # the results descending order of version number.
# If the requested major version is less than 12, there won't be any matches. if version[0] < 12: return
# Consider the actual X.Y version that was requested. yield ios_platform_template.format( major=version[0], minor=version[1], multiarch=multiarch )
# Consider every minor version from X.0 to the minor version prior to the # version requested by the platform. for minor in range(version[1] - 1, -1, -1): yield ios_platform_template.format( major=version[0], minor=minor, multiarch=multiarch )
for major in range(version[0] - 1, 11, -1): for minor in range(9, -1, -1): yield ios_platform_template.format( major=major, minor=minor, multiarch=multiarch )
def android_platforms( api_level: int | None = None, abi: str | None = None) -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on non-Android platforms, the ``api_level`` and ``abi`` arguments are required.
:param int api_level: The maximum `API level <https://developer.android.com/tools/releases/platforms>`__ to return. Defaults to the current system's version, as returned by ``platform.android_ver``. :param str abi: The `Android ABI <https://developer.android.com/ndk/guides/abis>`__, e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by ``sysconfig.get_platform``. Hyphens and periods will be replaced with underscores. """ if platform.system() != "Android" and (api_level is None or abi is None): raise TypeError( "on non-Android platforms, the api_level and abi arguments are required" )
if api_level is None: # Python 3.13 was the first version to return platform.system() == "Android", # and also the first version to define platform.android_ver(). api_level = platform.android_ver().api_level # type: ignore[attr-defined]
if abi is None: abi = sysconfig.get_platform().split("-")[-1] abi = _normalize_string(abi)
# 16 is the minimum API level known to have enough features to support CPython # without major patching. Yield every API level from the maximum down to the # minimum, inclusive. min_api_level = 16 for ver in range(api_level, min_api_level - 1, -1): yield f"android_{ver}_{abi}"
def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: linux = _normalize_string(sysconfig.get_platform()) if not linux.startswith("linux_"): # we should never be here, just yield the sysconfig one and return yield linux return if is_32bit: if linux == "linux_x86_64": linux = "linux_i686" elif linux == "linux_aarch64": linux = "linux_armv8l" _, arch = linux.split("_", 1) archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) yield from _manylinux.platform_tags(archs) yield from _musllinux.platform_tags(archs) for arch in archs: yield f"linux_{arch}"
def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform())
def platform_tags() -> Iterator[str]: """ Provides the platform tags for this installation. """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "iOS": return ios_platforms() elif platform.system() == "Android": return android_platforms() elif platform.system() == "Linux": return _linux_platforms() else: return _generic_platforms()
def interpreter_name() -> str: """ Returns the name of the running interpreter.
Some implementations have a reserved, two-letter abbreviation which will be returned when appropriate. """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name
def interpreter_version(*, warn: bool = False) -> str: """ Returns the version of the running interpreter. """ version = _get_config_var("py_version_nodot", warn=warn) return str(version) if version else _version_nodot(sys.version_info[:2])
def _version_nodot(version: PythonVersion) -> str: return "".join(map(str, version))
def sys_tags(*, warn: bool = False) -> Iterator[Tag]: """ Returns the sequence of tag triples for the running interpreter.
The order of the sequence corresponds to priority order for the interpreter, from most to least important. """
interp_name = interpreter_name() if interp_name == "cp": yield from cpython_tags(warn=warn) else: yield from generic_tags()
if interp_name == "pp": interp = "pp3" elif interp_name == "cp": interp = "cp" + interpreter_version(warn=warn) else: interp = None yield from compatible_tags(interpreter=interp)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
from __future__ import annotations
import refrom typing import NewType, Tuple, Union, cast
from .tags import Tag, parse_tagfrom .version import InvalidVersion, Version, _TrimmedRelease
BuildTag = Union[Tuple[()], Tuple[int, str]]NormalizedName = NewType("NormalizedName", str)
class InvalidName(ValueError): """ An invalid distribution name; users should refer to the packaging user guide. """
class InvalidWheelFilename(ValueError): """ An invalid wheel filename was found, users should refer to PEP 427. """
class InvalidSdistFilename(ValueError): """ An invalid sdist filename was found, users should refer to the packaging user guide. """
# Core metadata spec for `Name`_validate_regex = re.compile(r"[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9]", re.IGNORECASE)_normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]")# PEP 427: The build number must start with a digit._build_tag_regex = re.compile(r"(\d+)(.*)")
def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: if validate and not _validate_regex.fullmatch(name): raise InvalidName(f"name is invalid: {name!r}") # Ensure all ``.`` and ``_`` are ``-`` # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 # Much faster than re, and even faster than str.translate value = name.lower().replace("_", "-").replace(".", "-") # Condense repeats (faster than regex) while "--" in value: value = value.replace("--", "-") return cast("NormalizedName", value)
def is_normalized_name(name: str) -> bool: return _normalized_regex.fullmatch(name) is not None
def canonicalize_version( version: Version | str, *, strip_trailing_zero: bool = True) -> str: """ Return a canonical form of a version as a string.
>>> canonicalize_version('1.0.1') '1.0.1'
Per PEP 625, versions may have multiple canonical forms, differing only by trailing zeros.
>>> canonicalize_version('1.0.0') '1' >>> canonicalize_version('1.0.0', strip_trailing_zero=False) '1.0.0'
Invalid versions are returned unaltered.
>>> canonicalize_version('foo bar baz') 'foo bar baz' """ if isinstance(version, str): try: version = Version(version) except InvalidVersion: return str(version) return str(_TrimmedRelease(version) if strip_trailing_zero else version)
def parse_wheel_filename( filename: str,) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: if not filename.endswith(".whl"): raise InvalidWheelFilename( f"Invalid wheel filename (extension must be '.whl'): {filename!r}" )
filename = filename[:-4] dashes = filename.count("-") if dashes not in (4, 5): raise InvalidWheelFilename( f"Invalid wheel filename (wrong number of parts): {filename!r}" )
parts = filename.split("-", dashes - 2) name_part = parts[0] # See PEP 427 for the rules on escaping the project name. if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: raise InvalidWheelFilename(f"Invalid project name: {filename!r}") name = canonicalize_name(name_part)
try: version = Version(parts[1]) except InvalidVersion as e: raise InvalidWheelFilename( f"Invalid wheel filename (invalid version): {filename!r}" ) from e
if dashes == 5: build_part = parts[2] build_match = _build_tag_regex.match(build_part) if build_match is None: raise InvalidWheelFilename( f"Invalid build number: {build_part} in {filename!r}" ) build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2))) else: build = () tags = parse_tag(parts[-1]) return (name, version, build, tags)
def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: if filename.endswith(".tar.gz"): file_stem = filename[: -len(".tar.gz")] elif filename.endswith(".zip"): file_stem = filename[: -len(".zip")] else: raise InvalidSdistFilename( f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" f" {filename!r}" )
# We are requiring a PEP 440 version, which cannot contain dashes, # so we split on the last dash. name_part, sep, version_part = file_stem.rpartition("-") if not sep: raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}")
name = canonicalize_name(name_part)
try: version = Version(version_part) except InvalidVersion as e: raise InvalidSdistFilename( f"Invalid sdist filename (invalid version): {filename!r}" ) from e
return (name, version)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.""".. testsetup::
from packaging.version import parse, Version"""
from __future__ import annotations
import reimport sysimport typingfrom typing import ( Any, Callable, Literal, NamedTuple, SupportsInt, Tuple, TypedDict, Union,)
from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
if typing.TYPE_CHECKING: from typing_extensions import Self, Unpack
if sys.version_info >= (3, 13): # pragma: no cover from warnings import deprecated as _deprecatedelif typing.TYPE_CHECKING: from typing_extensions import deprecated as _deprecatedelse: # pragma: no cover import functools import warnings
def _deprecated(message: str) -> object: def decorator(func: object) -> object: @functools.wraps(func) def wrapper(*args: object, **kwargs: object) -> object: warnings.warn( message, category=DeprecationWarning, stacklevel=2, ) return func(*args, **kwargs)
return wrapper
return decorator
_LETTER_NORMALIZATION = { "alpha": "a", "beta": "b", "c": "rc", "pre": "rc", "preview": "rc", "rev": "post", "r": "post",}
__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"]
LocalType = Tuple[Union[int, str], ...]
CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]]CmpLocalType = Union[ NegativeInfinityType, Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...],]CmpKey = Tuple[ int, Tuple[int, ...], CmpPrePostDevType, CmpPrePostDevType, CmpPrePostDevType, CmpLocalType,]VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
class _VersionReplace(TypedDict, total=False): epoch: int | None release: tuple[int, ...] | None pre: tuple[Literal["a", "b", "rc"], int] | None post: int | None dev: int | None local: str | None
def parse(version: str) -> Version: """Parse the given version string.
>>> parse('1.0.dev1') <Version('1.0.dev1')>
:param version: The version string to parse. :raises InvalidVersion: When the version string is not a valid version. """ return Version(version)
class InvalidVersion(ValueError): """Raised when a version string is not a valid version.
>>> Version("invalid") Traceback (most recent call last): ... packaging.version.InvalidVersion: Invalid version: 'invalid' """
class _BaseVersion: __slots__ = ()
# This can also be a normal member (see the packaging_legacy package); # we are just requiring it to be readable. Actually defining a property # has runtime effect on subclasses, so it's typing only. if typing.TYPE_CHECKING:
@property def _key(self) -> tuple[Any, ...]: ...
def __hash__(self) -> int: return hash(self._key)
# Please keep the duplicated `isinstance` check # in the six comparisons hereunder # unless you find a way to avoid adding overhead function calls. def __lt__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key < other._key
def __le__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key <= other._key
def __eq__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key == other._key
def __ge__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key >= other._key
def __gt__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key > other._key
def __ne__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key != other._key
# Deliberately not anchored to the start and end of the string, to make it# easier for 3rd party code to reuse
# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here_VERSION_PATTERN = r""" v?+ # optional leading v (?: (?:(?P<epoch>[0-9]+)!)?+ # epoch (?P<release>[0-9]+(?:\.[0-9]+)*+) # release segment (?P<pre> # pre-release [._-]?+ (?P<pre_l>alpha|a|beta|b|preview|pre|c|rc) [._-]?+ (?P<pre_n>[0-9]+)? )?+ (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [._-]? (?P<post_l>post|rev|r) [._-]? (?P<post_n2>[0-9]+)? ) )?+ (?P<dev> # dev release [._-]?+ (?P<dev_l>dev) [._-]?+ (?P<dev_n>[0-9]+)? )?+ ) (?:\+ (?P<local> # local version [a-z0-9]+ (?:[._-][a-z0-9]+)*+ ) )?+"""
_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
# Possessive qualifiers were added in Python 3.11.# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795# Older PyPy also had a bug.VERSION_PATTERN = ( _VERSION_PATTERN_OLD if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5)) or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13)) or sys.version_info < (3, 11) else _VERSION_PATTERN)"""A string containing the regular expression used to match a valid version.
The pattern is not anchored at either end, and is intended for embedding in largerexpressions (for example, matching a version number as part of a file name). Theregular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``flags set.
:meta hide-value:"""
# Validation pattern for local version in replace()_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE)
def _validate_epoch(value: object, /) -> int: epoch = value or 0 if isinstance(epoch, int) and epoch >= 0: return epoch msg = f"epoch must be non-negative integer, got {epoch}" raise InvalidVersion(msg)
def _validate_release(value: object, /) -> tuple[int, ...]: release = (0,) if value is None else value if ( isinstance(release, tuple) and len(release) > 0 and all(isinstance(i, int) and i >= 0 for i in release) ): return release msg = f"release must be a non-empty tuple of non-negative integers, got {release}" raise InvalidVersion(msg)
def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None: if value is None: return value if ( isinstance(value, tuple) and len(value) == 2 and value[0] in ("a", "b", "rc") and isinstance(value[1], int) and value[1] >= 0 ): return value msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}" raise InvalidVersion(msg)
def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None: if value is None: return value if isinstance(value, int) and value >= 0: return ("post", value) msg = f"post must be non-negative integer, got {value}" raise InvalidVersion(msg)
def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None: if value is None: return value if isinstance(value, int) and value >= 0: return ("dev", value) msg = f"dev must be non-negative integer, got {value}" raise InvalidVersion(msg)
def _validate_local(value: object, /) -> LocalType | None: if value is None: return value if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value): return _parse_local_version(value) msg = f"local must be a valid version string, got {value!r}" raise InvalidVersion(msg)
# Backward compatibility for internals before 26.0. Do not use.class _Version(NamedTuple): epoch: int release: tuple[int, ...] dev: tuple[str, int] | None pre: tuple[str, int] | None post: tuple[str, int] | None local: LocalType | None
class Version(_BaseVersion): """This class abstracts handling of a project's versions.
A :class:`Version` instance is comparison aware and can be compared and sorted using the standard Python interfaces.
>>> v1 = Version("1.0a5") >>> v2 = Version("1.0") >>> v1 <Version('1.0a5')> >>> v2 <Version('1.0')> >>> v1 < v2 True >>> v1 == v2 False >>> v1 > v2 False >>> v1 >= v2 False >>> v1 <= v2 True """
__slots__ = ("_dev", "_epoch", "_key_cache", "_local", "_post", "_pre", "_release") __match_args__ = ("_str",)
_regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
_epoch: int _release: tuple[int, ...] _dev: tuple[str, int] | None _pre: tuple[str, int] | None _post: tuple[str, int] | None _local: LocalType | None
_key_cache: CmpKey | None
def __init__(self, version: str) -> None: """Initialize a Version object.
:param version: The string representation of a version which will be parsed and normalized before use. :raises InvalidVersion: If the ``version`` does not conform to PEP 440 in any way then this exception will be raised. """ # Validate the version and parse it into pieces match = self._regex.fullmatch(version) if not match: raise InvalidVersion(f"Invalid version: {version!r}") self._epoch = int(match.group("epoch")) if match.group("epoch") else 0 self._release = tuple(map(int, match.group("release").split("."))) self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n")) self._post = _parse_letter_version( match.group("post_l"), match.group("post_n1") or match.group("post_n2") ) self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n")) self._local = _parse_local_version(match.group("local"))
# Key which will be used for sorting self._key_cache = None
def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self: epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch release = ( _validate_release(kwargs["release"]) if "release" in kwargs else self._release ) pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
if ( epoch == self._epoch and release == self._release and pre == self._pre and post == self._post and dev == self._dev and local == self._local ): return self
new_version = self.__class__.__new__(self.__class__) new_version._key_cache = None new_version._epoch = epoch new_version._release = release new_version._pre = pre new_version._post = post new_version._dev = dev new_version._local = local
return new_version
@property def _key(self) -> CmpKey: if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) return self._key_cache
@property @_deprecated("Version._version is private and will be removed soon") def _version(self) -> _Version: return _Version( self._epoch, self._release, self._dev, self._pre, self._post, self._local )
@_version.setter @_deprecated("Version._version is private and will be removed soon") def _version(self, value: _Version) -> None: self._epoch = value.epoch self._release = value.release self._dev = value.dev self._pre = value.pre self._post = value.post self._local = value.local self._key_cache = None
def __repr__(self) -> str: """A representation of the Version that shows all internal state.
>>> Version('1.0.0') <Version('1.0.0')> """ return f"<Version('{self}')>"
def __str__(self) -> str: """A string representation of the version that can be round-tripped.
>>> str(Version("1.0a5")) '1.0a5' """ # This is a hot function, so not calling self.base_version version = ".".join(map(str, self.release))
# Epoch if self.epoch: version = f"{self.epoch}!{version}"
# Pre-release if self.pre is not None: version += "".join(map(str, self.pre))
# Post-release if self.post is not None: version += f".post{self.post}"
# Development release if self.dev is not None: version += f".dev{self.dev}"
# Local version segment if self.local is not None: version += f"+{self.local}"
return version
@property def _str(self) -> str: """Internal property for match_args""" return str(self)
@property def epoch(self) -> int: """The epoch of the version.
>>> Version("2.0.0").epoch 0 >>> Version("1!2.0.0").epoch 1 """ return self._epoch
@property def release(self) -> tuple[int, ...]: """The components of the "release" segment of the version.
>>> Version("1.2.3").release (1, 2, 3) >>> Version("2.0.0").release (2, 0, 0) >>> Version("1!2.0.0.post0").release (2, 0, 0)
Includes trailing zeroes but not the epoch or any pre-release / development / post-release suffixes. """ return self._release
@property def pre(self) -> tuple[str, int] | None: """The pre-release segment of the version.
>>> print(Version("1.2.3").pre) None >>> Version("1.2.3a1").pre ('a', 1) >>> Version("1.2.3b1").pre ('b', 1) >>> Version("1.2.3rc1").pre ('rc', 1) """ return self._pre
@property def post(self) -> int | None: """The post-release number of the version.
>>> print(Version("1.2.3").post) None >>> Version("1.2.3.post1").post 1 """ return self._post[1] if self._post else None
@property def dev(self) -> int | None: """The development number of the version.
>>> print(Version("1.2.3").dev) None >>> Version("1.2.3.dev1").dev 1 """ return self._dev[1] if self._dev else None
@property def local(self) -> str | None: """The local version segment of the version.
>>> print(Version("1.2.3").local) None >>> Version("1.2.3+abc").local 'abc' """ if self._local: return ".".join(str(x) for x in self._local) else: return None
@property def public(self) -> str: """The public portion of the version.
>>> Version("1.2.3").public '1.2.3' >>> Version("1.2.3+abc").public '1.2.3' >>> Version("1!1.2.3dev1+abc").public '1!1.2.3.dev1' """ return str(self).split("+", 1)[0]
@property def base_version(self) -> str: """The "base version" of the version.
>>> Version("1.2.3").base_version '1.2.3' >>> Version("1.2.3+abc").base_version '1.2.3' >>> Version("1!1.2.3dev1+abc").base_version '1!1.2.3'
The "base version" is the public version of the project without any pre or post release markers. """ release_segment = ".".join(map(str, self.release)) return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
@property def is_prerelease(self) -> bool: """Whether this version is a pre-release.
>>> Version("1.2.3").is_prerelease False >>> Version("1.2.3a1").is_prerelease True >>> Version("1.2.3b1").is_prerelease True >>> Version("1.2.3rc1").is_prerelease True >>> Version("1.2.3dev1").is_prerelease True """ return self.dev is not None or self.pre is not None
@property def is_postrelease(self) -> bool: """Whether this version is a post-release.
>>> Version("1.2.3").is_postrelease False >>> Version("1.2.3.post1").is_postrelease True """ return self.post is not None
@property def is_devrelease(self) -> bool: """Whether this version is a development release.
>>> Version("1.2.3").is_devrelease False >>> Version("1.2.3.dev1").is_devrelease True """ return self.dev is not None
@property def major(self) -> int: """The first item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").major 1 """ return self.release[0] if len(self.release) >= 1 else 0
@property def minor(self) -> int: """The second item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").minor 2 >>> Version("1").minor 0 """ return self.release[1] if len(self.release) >= 2 else 0
@property def micro(self) -> int: """The third item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").micro 3 >>> Version("1").micro 0 """ return self.release[2] if len(self.release) >= 3 else 0
class _TrimmedRelease(Version): __slots__ = ()
def __init__(self, version: str | Version) -> None: if isinstance(version, Version): self._epoch = version._epoch self._release = version._release self._dev = version._dev self._pre = version._pre self._post = version._post self._local = version._local self._key_cache = version._key_cache return super().__init__(version) # pragma: no cover
@property def release(self) -> tuple[int, ...]: """ Release segment without any trailing zeros.
>>> _TrimmedRelease('1.0.0').release (1,) >>> _TrimmedRelease('0.0').release (0,) """ # This leaves one 0. rel = super().release len_release = len(rel) i = len_release while i > 1 and rel[i - 1] == 0: i -= 1 return rel if i == len_release else rel[:i]
def _parse_letter_version( letter: str | None, number: str | bytes | SupportsInt | None) -> tuple[str, int] | None: if letter: # We normalize any letters to their lower case form letter = letter.lower()
# We consider some words to be alternate spellings of other words and # in those cases we want to normalize the spellings to our preferred # spelling. letter = _LETTER_NORMALIZATION.get(letter, letter)
# We consider there to be an implicit 0 in a pre-release if there is # not a numeral associated with it. return letter, int(number or 0)
if number: # We assume if we are given a number, but we are not given a letter # then this is using the implicit post release syntax (e.g. 1.0-1) return "post", int(number)
return None
_local_version_separators = re.compile(r"[\._-]")
def _parse_local_version(local: str | None) -> LocalType | None: """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) ) return None
def _cmpkey( epoch: int, release: tuple[int, ...], pre: tuple[str, int] | None, post: tuple[str, int] | None, dev: tuple[str, int] | None, local: LocalType | None,) -> CmpKey: # When we compare a release version, we want to compare it with all of the # trailing zeros removed. We will use this for our sorting key. len_release = len(release) i = len_release while i and release[i - 1] == 0: i -= 1 _release = release if i == len_release else release[:i]
# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0. # We'll do this by abusing the pre segment, but we _only_ want to do this # if there is not a pre or a post segment. If we have one of those then # the normal sorting rules will handle this case correctly. if pre is None and post is None and dev is not None: _pre: CmpPrePostDevType = NegativeInfinity # Versions without a pre-release (except as noted above) should sort after # those with one. elif pre is None: _pre = Infinity else: _pre = pre
# Versions without a post segment should sort before those with one. if post is None: _post: CmpPrePostDevType = NegativeInfinity
else: _post = post
# Versions without a development segment should sort after those with one. if dev is None: _dev: CmpPrePostDevType = Infinity
else: _dev = dev
if local is None: # Versions without a local segment should sort before those with one. _local: CmpLocalType = NegativeInfinity else: # Versions with a local segment need that segment parsed to implement # the sorting rules in PEP440. # - Alpha numeric segments sort before numeric segments # - Alpha numeric segments sort lexicographically # - Numeric segments sort numerically # - Shorter versions sort before longer versions when the prefixes # match exactly _local = tuple( (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local )
return epoch, _release, _pre, _post, _dev, _local123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412Metadata-Version: 2.4Name: typerVersion: 0.24.1Summary: Typer, build great CLIs. Easy to code. Based on Python type hints.Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>License-Expression: MITLicense-File: LICENSEClassifier: Intended Audience :: Information TechnologyClassifier: Intended Audience :: System AdministratorsClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: PythonClassifier: Topic :: Software Development :: Libraries :: Application FrameworksClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Software Development :: LibrariesClassifier: Topic :: Software DevelopmentClassifier: Typing :: TypedClassifier: Development Status :: 4 - BetaClassifier: Intended Audience :: DevelopersClassifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Project-URL: Homepage, https://github.com/fastapi/typerProject-URL: Documentation, https://typer.tiangolo.comProject-URL: Repository, https://github.com/fastapi/typerProject-URL: Issues, https://github.com/fastapi/typer/issuesProject-URL: Changelog, https://typer.tiangolo.com/release-notes/Requires-Python: >=3.10Requires-Dist: click>=8.2.1Requires-Dist: shellingham>=1.3.0Requires-Dist: rich>=12.3.0Requires-Dist: annotated-doc>=0.0.2Description-Content-Type: text/markdown
<p align="center"> <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>
</p><p align="center"> <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em></p><p align="center"><a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test"></a><a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish" target="_blank"> <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish"></a><a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer" target="_blank"> <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage"><a href="https://pypi.org/project/typer" target="_blank"> <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version"></a></p>
---
**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com</a>
**Source Code**: <a href="https://github.com/fastapi/typer" target="_blank">https://github.com/fastapi/typer</a>
---
Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.
It's also a command line tool to run scripts, automatically converting them to CLI applications.
The key features are:
* **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.* **Run scripts**: Typer includes a `typer` command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.
## 2026 February - Typer developer survey
Help us define Typer's future by filling the <a href="https://forms.gle/nYvutPrVkmBQZLas7" class="external-link" target="_blank">Typer developer survey</a>. ✨
## FastAPI of CLIs
**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.
## Installation
Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:
<div class="termy">
```console$ pip install typer---> 100%Successfully installed typer rich shellingham```
</div>
## Example
### The absolute minimum
* Create a file `main.py` with:
```Pythondef main(name: str): print(f"Hello {name}")```
This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.
### Run it
Run your application with the `typer` command:
<div class="termy">
```console// Run your application$ typer main.py run
// You get a nice error, you are missing NAMEUsage: typer [PATH_OR_MODULE] run [OPTIONS] NAMETry 'typer [PATH_OR_MODULE] run --help' for help.╭─ Error ───────────────────────────────────────────╮│ Missing argument 'NAME'. │╰───────────────────────────────────────────────────╯
// You get a --help for free$ typer main.py run --help
Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
Run the provided Typer app.
╭─ Arguments ───────────────────────────────────────╮│ * name TEXT [default: None] [required] |╰───────────────────────────────────────────────────╯╭─ Options ─────────────────────────────────────────╮│ --help Show this message and exit. │╰───────────────────────────────────────────────────╯
// Now pass the NAME argument$ typer main.py run Camila
Hello Camila
// It works! 🎉```
</div>
This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.
**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.
## Use Typer in your code
Now let's start using Typer in your own code, update `main.py` with:
```Pythonimport typer
def main(name: str): print(f"Hello {name}")
if __name__ == "__main__": typer.run(main)```
Now you could run it with Python directly:
<div class="termy">
```console// Run your application$ python main.py
// You get a nice error, you are missing NAMEUsage: main.py [OPTIONS] NAMETry 'main.py --help' for help.╭─ Error ───────────────────────────────────────────╮│ Missing argument 'NAME'. │╰───────────────────────────────────────────────────╯
// You get a --help for free$ python main.py --help
Usage: main.py [OPTIONS] NAME
╭─ Arguments ───────────────────────────────────────╮│ * name TEXT [default: None] [required] |╰───────────────────────────────────────────────────╯╭─ Options ─────────────────────────────────────────╮│ --help Show this message and exit. │╰───────────────────────────────────────────────────╯
// Now pass the NAME argument$ python main.py Camila
Hello Camila
// It works! 🎉```
</div>
**Note**: you can also call this same script with the `typer` command, but you don't need to.
## Example upgrade
This was the simplest example possible.
Now let's see one a bit more complex.
### An example with two subcommands
Modify the file `main.py`.
Create a `typer.Typer()` app, and create two subcommands with their parameters.
```Python hl_lines="3 6 11 20"import typer
app = typer.Typer()
@app.command()def hello(name: str): print(f"Hello {name}")
@app.command()def goodbye(name: str, formal: bool = False): if formal: print(f"Goodbye Ms. {name}. Have a good day.") else: print(f"Bye {name}!")
if __name__ == "__main__": app()```
And that will:
* Explicitly create a `typer.Typer` app. * The previous `typer.run` actually creates one implicitly for you.* Add two subcommands with `@app.command()`.* Execute the `app()` itself, as if it was a function (instead of `typer.run`).
### Run the upgraded example
Check the new help:
<div class="termy">
```console$ python main.py --help
Usage: main.py [OPTIONS] COMMAND [ARGS]...
╭─ Options ───────────────────────────────��─────────╮│ --install-completion Install completion ││ for the current ││ shell. ││ --show-completion Show completion for ││ the current shell, ││ to copy it or ││ customize the ││ installation. ││ --help Show this message ││ and exit. │╰───────────────────────────────────────────────────╯╭─ Commands ────────────────────────────────────────╮│ goodbye ││ hello │╰───────────────────────────────────────────────────╯
// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion
// You have 2 subcommands (the 2 functions): goodbye and hello```
</div>
Now check the help for the `hello` command:
<div class="termy">
```console$ python main.py hello --help
Usage: main.py hello [OPTIONS] NAME
╭─ Arguments ───────────────────────────────────────╮│ * name TEXT [default: None] [required] │╰───────────────────────────────────────────────────╯╭─ Options ─────────────────────────────────────────╮│ --help Show this message and exit. │╰───────────────────────────────────────────────────╯```
</div>
And now check the help for the `goodbye` command:
<div class="termy">
```console$ python main.py goodbye --help
Usage: main.py goodbye [OPTIONS] NAME
╭─ Arguments ───────────────────────────────────────╮│ * name TEXT [default: None] [required] │╰───────────────────────────────────────────────────╯╭─ Options ─────────────────────────────────────────╮│ --formal --no-formal [default: no-formal] ││ --help Show this message ││ and exit. │╰───────────────────────────────────────────────────╯
// Automatic --formal and --no-formal for the bool option 🎉```
</div>
Now you can try out the new command line application:
<div class="termy">
```console// Use it with the hello command
$ python main.py hello Camila
Hello Camila
// And with the goodbye command
$ python main.py goodbye Camila
Bye Camila!
// And with --formal
$ python main.py goodbye --formal Camila
Goodbye Ms. Camila. Have a good day.```
</div>
**Note**: If your app only has one command, by default the command name is **omitted** in usage: `python main.py Camila`. However, when there are multiple commands, you must **explicitly include the command name**: `python main.py hello Camila`. See [One or Multiple Commands](https://typer.tiangolo.com/tutorial/commands/one-or-multiple/) for more details.
### Recap
In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.
You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
Just standard **Python**.
For example, for an `int`:
```Pythontotal: int```
or for a `bool` flag:
```Pythonforce: bool```
And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.
**You get**: great editor support, including **completion** and **type checks** everywhere.
**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the `typer` command.
For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
## Dependencies
**Typer** stands on the shoulders of giants. It has three required dependencies:
* <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>: a popular tool for building CLIs in Python. Typer is based on it.* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: to automatically detect the current shell when installing completion.
### `typer-slim`
There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.
However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.
If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.
## License
This project is licensed under the terms of the MIT license.12345678910111213141516171819202122typer-0.24.1.dist-info/METADATA,sha256=V4OWoWjBhPNcoIaOxhr1cszo69nePKOHMRXERkMscKs,16057typer-0.24.1.dist-info/WHEEL,sha256=Wb0ASbVj8JvWHpOiIpPi7ucfIgJeCi__PzivviEAQFc,90typer-0.24.1.dist-info/entry_points.txt,sha256=YO13ByiqWeuas9V0JADLUARZFUe_cwU_7wmTNvxBYQ8,57typer-0.24.1.dist-info/licenses/LICENSE,sha256=WJks68-N-25AxOIRLtEhJsJDZm3KORKj14t-ysSFnUk,1086typer/__init__.py,sha256=WOelHJu4PW0hk9nfjEX0Qxssb58NCh1km_Xq5LY_33s,1596typer/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30typer/_completion_classes.py,sha256=R9v4D8pJ_-n8fLOuyxrRSu7sP5lpXIy5fsLUW8zwsDU,7039typer/_completion_shared.py,sha256=-uhCUIMc2S1ywdB-fBSSccH70mIBEsVTxHomcmy-klE,9129typer/_types.py,sha256=0lcBDLcsxqr1sxTsqObj_u0Dfa37lWJYUY4PNkX4QlA,974typer/_typing.py,sha256=QOw5o-B2L--C3ly2DQH6aUwag6x5brV5FhVaBZ5gzMg,1727typer/cli.py,sha256=icRbazvdRdbYeaidPZOmJDOzrP3RAa7vj2INVV9Zb8Q,10183typer/colors.py,sha256=e42j8uB520hLpX5C_0fiR3OOoIFMbhO3ADZvv6hlAV8,430typer/completion.py,sha256=FRTR9hP_IPdJp-4GXPOq0btXo5SvgAtLVfS3ZkAMpgQ,4793typer/core.py,sha256=O5NywSwHPyYbLhZkPYSfwIj7Za2hPnoPP4xPXRa97a0,27947typer/main.py,sha256=xyNex-QfGUi-enu9j9rl-_wofApxs5VwdpCthAUAAkk,69005typer/models.py,sha256=OwPG3MAXiUD5ih3p8eNVciXUsL07UIJfNWy3JiNpDfg,19843typer/params.py,sha256=AovViRtl-VvUIXnmKKpnxoWK9_gHUbyQgXxxv3h_7lI,59713typer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0typer/rich_utils.py,sha256=RTyeoxwz16ZZXYbwoEixB_LSEnqpoStG_TGCRTz6zFQ,25424typer/testing.py,sha256=-ovLNjUNNEFCJoau-41iTJIobsjPbqyTrRq7-8ac4z4,871typer/utils.py,sha256=wnJ1DWXBFMnxLHaMN_HDYntxLRby0K-rux63aokHInI,7599typer-0.24.1.dist-info/RECORD,,1234Wheel-Version: 1.0Generator: pdm-backend (2.4.7)Root-Is-Purelib: trueTag: py3-none-any12345[console_scripts]typer = typer.cli:main
[gui_scripts]
123456789101112131415161718192021The MIT License (MIT)
Copyright (c) 2019 Sebastián Ramírez
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839"""Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.24.1"
from shutil import get_terminal_size as get_terminal_size
from click.exceptions import Abort as Abortfrom click.exceptions import BadParameter as BadParameterfrom click.exceptions import Exit as Exitfrom click.termui import clear as clearfrom click.termui import confirm as confirmfrom click.termui import echo_via_pager as echo_via_pagerfrom click.termui import edit as editfrom click.termui import getchar as getcharfrom click.termui import pause as pausefrom click.termui import progressbar as progressbarfrom click.termui import prompt as promptfrom click.termui import secho as sechofrom click.termui import style as stylefrom click.termui import unstyle as unstylefrom click.utils import echo as echofrom click.utils import format_filename as format_filenamefrom click.utils import get_app_dir as get_app_dirfrom click.utils import get_binary_stream as get_binary_streamfrom click.utils import get_text_stream as get_text_streamfrom click.utils import open_file as open_file
from . import colors as colorsfrom .main import Typer as Typerfrom .main import launch as launchfrom .main import run as runfrom .models import CallbackParam as CallbackParamfrom .models import Context as Contextfrom .models import FileBinaryRead as FileBinaryReadfrom .models import FileBinaryWrite as FileBinaryWritefrom .models import FileText as FileTextfrom .models import FileTextWrite as FileTextWritefrom .params import Argument as Argumentfrom .params import Option as Option123from .cli import main
main().cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/__init__.pyAdded+39
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection.pyAdded+222
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/connection_pool.pyAdded+420
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http11.pyAdded+379
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http2.pyAdded+592
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/http_proxy.pyAdded+367
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/interfaces.pyAdded+137
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_async/socks_proxy.pyAdded+341
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/__init__.pyAdded
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/anyio.pyAdded+146
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/auto.pyAdded+52
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/base.pyAdded+101
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/mock.pyAdded+143
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/sync.pyAdded+241
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_backends/trio.pyAdded+159
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/__init__.pyAdded+39
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection.pyAdded+222
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/connection_pool.pyAdded+420
.cache/uv/archive-v0/8WKOeGv-F2f2SCEEN3LbW/httpcore/_sync/http11.pyAdded+379
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/METADATAAdded+107
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/RECORDAdded+24
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/WHEELAdded+4
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSEAdded+3
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.APACHEAdded+177
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging-26.0.dist-info/licenses/LICENSE.BSDAdded+23
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/__init__.pyAdded+15
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_elffile.pyAdded+108
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_manylinux.pyAdded+262
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_musllinux.pyAdded+85
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_parser.pyAdded+365
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_structures.pyAdded+69
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/_tokenizer.pyAdded+193
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/__init__.pyAdded+147
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/licenses/_spdx.pyAdded+799
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/markers.pyAdded+388
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/metadata.pyAdded+978
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/py.typedAdded
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/pylock.pyAdded+635
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/requirements.pyAdded+86
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/specifiers.pyAdded+1068
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/tags.pyAdded+651
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/utils.pyAdded+158
.cache/uv/archive-v0/H82JQ_dwrBujk5fQo_3yi/packaging/version.pyAdded+792
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/METADATAAdded+412
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/RECORDAdded+22
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/WHEELAdded+4
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/entry_points.txtAdded+5
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer-0.24.1.dist-info/licenses/LICENSEAdded+21
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__init__.pyAdded+39
.cache/uv/archive-v0/Yxk4umppjsX1n0Zo__Hkm/typer/__main__.pyAdded+3