Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/main.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/index_command.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/cache.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/check.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/completion.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/download.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/hash.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/help.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/pip/_internal/index/__init__.py +1 -0
- .venv/lib/python3.12/site-packages/pip/_internal/locations/__init__.py +440 -0
- .venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py +173 -0
- .venv/lib/python3.12/site-packages/pip/_internal/locations/_sysconfig.py +218 -0
- .venv/lib/python3.12/site-packages/pip/_internal/metadata/__init__.py +169 -0
- .venv/lib/python3.12/site-packages/pip/_internal/metadata/base.py +685 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/__init__.py +1 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/direct_url.py +227 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/index.py +28 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/installation_report.py +57 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/link.py +617 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/release_control.py +92 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/search_scope.py +126 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/selection_prefs.py +56 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/target_python.py +122 -0
- .venv/lib/python3.12/site-packages/pip/_internal/models/wheel.py +80 -0
- .venv/lib/python3.12/site-packages/pip/_internal/network/__init__.py +1 -0
- .venv/lib/python3.12/site-packages/pip/_internal/network/auth.py +568 -0
- .venv/lib/python3.12/site-packages/pip/_internal/network/cache.py +128 -0
- .venv/lib/python3.12/site-packages/pip/_internal/network/download.py +341 -0
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (746 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc
ADDED
|
Binary file (25.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc
ADDED
|
Binary file (12.4 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc
ADDED
|
Binary file (18.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc
ADDED
|
Binary file (43.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (629 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc
ADDED
|
Binary file (4.08 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc
ADDED
|
Binary file (9.96 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (270 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc
ADDED
|
Binary file (11.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc
ADDED
|
Binary file (35.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc
ADDED
|
Binary file (1.81 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/index_command.cpython-312.pyc
ADDED
|
Binary file (7.86 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (2.23 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc
ADDED
|
Binary file (4.94 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc
ADDED
|
Binary file (18.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc
ADDED
|
Binary file (6.09 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc
ADDED
|
Binary file (16.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc
ADDED
|
Binary file (370 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (4.11 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/cache.cpython-312.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/check.cpython-312.pyc
ADDED
|
Binary file (2.55 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/completion.cpython-312.pyc
ADDED
|
Binary file (5.45 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-312.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/download.cpython-312.pyc
ADDED
|
Binary file (7.22 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-312.pyc
ADDED
|
Binary file (4.28 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/hash.cpython-312.pyc
ADDED
|
Binary file (2.93 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/help.cpython-312.pyc
ADDED
|
Binary file (1.63 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/pip/_internal/index/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Index interaction code"""
|
.venv/lib/python3.12/site-packages/pip/_internal/locations/__init__.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import pathlib
|
| 7 |
+
import sys
|
| 8 |
+
import sysconfig
|
| 9 |
+
|
| 10 |
+
from pip._internal.models.scheme import SCHEME_KEYS, Scheme
|
| 11 |
+
from pip._internal.utils.compat import WINDOWS
|
| 12 |
+
from pip._internal.utils.deprecation import deprecated
|
| 13 |
+
from pip._internal.utils.virtualenv import running_under_virtualenv
|
| 14 |
+
|
| 15 |
+
from . import _sysconfig
|
| 16 |
+
from .base import (
|
| 17 |
+
USER_CACHE_DIR,
|
| 18 |
+
get_major_minor_version,
|
| 19 |
+
get_src_prefix,
|
| 20 |
+
is_osx_framework,
|
| 21 |
+
site_packages,
|
| 22 |
+
user_site,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"USER_CACHE_DIR",
|
| 27 |
+
"get_bin_prefix",
|
| 28 |
+
"get_bin_user",
|
| 29 |
+
"get_major_minor_version",
|
| 30 |
+
"get_platlib",
|
| 31 |
+
"get_purelib",
|
| 32 |
+
"get_scheme",
|
| 33 |
+
"get_src_prefix",
|
| 34 |
+
"site_packages",
|
| 35 |
+
"user_site",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.getLogger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
_PLATLIBDIR: str = getattr(sys, "platlibdir", "lib")
|
| 43 |
+
|
| 44 |
+
_USE_SYSCONFIG_DEFAULT = sys.version_info >= (3, 10)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _should_use_sysconfig() -> bool:
|
| 48 |
+
"""This function determines the value of _USE_SYSCONFIG.
|
| 49 |
+
|
| 50 |
+
By default, pip uses sysconfig on Python 3.10+.
|
| 51 |
+
But Python distributors can override this decision by setting:
|
| 52 |
+
sysconfig._PIP_USE_SYSCONFIG = True / False
|
| 53 |
+
Rationale in https://github.com/pypa/pip/issues/10647
|
| 54 |
+
|
| 55 |
+
This is a function for testability, but should be constant during any one
|
| 56 |
+
run.
|
| 57 |
+
"""
|
| 58 |
+
return bool(getattr(sysconfig, "_PIP_USE_SYSCONFIG", _USE_SYSCONFIG_DEFAULT))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
_USE_SYSCONFIG = _should_use_sysconfig()
|
| 62 |
+
|
| 63 |
+
if not _USE_SYSCONFIG:
|
| 64 |
+
# Import distutils lazily to avoid deprecation warnings,
|
| 65 |
+
# but import it soon enough that it is in memory and available during
|
| 66 |
+
# a pip reinstall.
|
| 67 |
+
from . import _distutils
|
| 68 |
+
|
| 69 |
+
# Be noisy about incompatibilities if this platforms "should" be using
|
| 70 |
+
# sysconfig, but is explicitly opting out and using distutils instead.
|
| 71 |
+
if _USE_SYSCONFIG_DEFAULT and not _USE_SYSCONFIG:
|
| 72 |
+
_MISMATCH_LEVEL = logging.WARNING
|
| 73 |
+
else:
|
| 74 |
+
_MISMATCH_LEVEL = logging.DEBUG
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _looks_like_bpo_44860() -> bool:
|
| 78 |
+
"""The resolution to bpo-44860 will change this incorrect platlib.
|
| 79 |
+
|
| 80 |
+
See <https://bugs.python.org/issue44860>.
|
| 81 |
+
"""
|
| 82 |
+
from distutils.command.install import INSTALL_SCHEMES
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
unix_user_platlib = INSTALL_SCHEMES["unix_user"]["platlib"]
|
| 86 |
+
except KeyError:
|
| 87 |
+
return False
|
| 88 |
+
return unix_user_platlib == "$usersite"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _looks_like_red_hat_patched_platlib_purelib(scheme: dict[str, str]) -> bool:
|
| 92 |
+
platlib = scheme["platlib"]
|
| 93 |
+
if "/$platlibdir/" in platlib:
|
| 94 |
+
platlib = platlib.replace("/$platlibdir/", f"/{_PLATLIBDIR}/")
|
| 95 |
+
if "/lib64/" not in platlib:
|
| 96 |
+
return False
|
| 97 |
+
unpatched = platlib.replace("/lib64/", "/lib/")
|
| 98 |
+
return unpatched.replace("$platbase/", "$base/") == scheme["purelib"]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@functools.cache
|
| 102 |
+
def _looks_like_red_hat_lib() -> bool:
|
| 103 |
+
"""Red Hat patches platlib in unix_prefix and unix_home, but not purelib.
|
| 104 |
+
|
| 105 |
+
This is the only way I can see to tell a Red Hat-patched Python.
|
| 106 |
+
"""
|
| 107 |
+
from distutils.command.install import INSTALL_SCHEMES
|
| 108 |
+
|
| 109 |
+
return all(
|
| 110 |
+
k in INSTALL_SCHEMES
|
| 111 |
+
and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k])
|
| 112 |
+
for k in ("unix_prefix", "unix_home")
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@functools.cache
|
| 117 |
+
def _looks_like_debian_scheme() -> bool:
|
| 118 |
+
"""Debian adds two additional schemes."""
|
| 119 |
+
from distutils.command.install import INSTALL_SCHEMES
|
| 120 |
+
|
| 121 |
+
return "deb_system" in INSTALL_SCHEMES and "unix_local" in INSTALL_SCHEMES
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@functools.cache
|
| 125 |
+
def _looks_like_red_hat_scheme() -> bool:
|
| 126 |
+
"""Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.
|
| 127 |
+
|
| 128 |
+
Red Hat's ``00251-change-user-install-location.patch`` changes the install
|
| 129 |
+
command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is
|
| 130 |
+
(fortunately?) done quite unconditionally, so we create a default command
|
| 131 |
+
object without any configuration to detect this.
|
| 132 |
+
"""
|
| 133 |
+
from distutils.command.install import install
|
| 134 |
+
from distutils.dist import Distribution
|
| 135 |
+
|
| 136 |
+
cmd = install(Distribution())
|
| 137 |
+
cmd.finalize_options()
|
| 138 |
+
return (
|
| 139 |
+
cmd.exec_prefix == f"{os.path.normpath(sys.exec_prefix)}/local"
|
| 140 |
+
and cmd.prefix == f"{os.path.normpath(sys.prefix)}/local"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@functools.cache
|
| 145 |
+
def _looks_like_slackware_scheme() -> bool:
|
| 146 |
+
"""Slackware patches sysconfig but fails to patch distutils and site.
|
| 147 |
+
|
| 148 |
+
Slackware changes sysconfig's user scheme to use ``"lib64"`` for the lib
|
| 149 |
+
path, but does not do the same to the site module.
|
| 150 |
+
"""
|
| 151 |
+
if user_site is None: # User-site not available.
|
| 152 |
+
return False
|
| 153 |
+
try:
|
| 154 |
+
paths = sysconfig.get_paths(scheme="posix_user", expand=False)
|
| 155 |
+
except KeyError: # User-site not available.
|
| 156 |
+
return False
|
| 157 |
+
return "/lib64/" in paths["purelib"] and "/lib64/" not in user_site
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@functools.cache
|
| 161 |
+
def _looks_like_msys2_mingw_scheme() -> bool:
|
| 162 |
+
"""MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.
|
| 163 |
+
|
| 164 |
+
However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is
|
| 165 |
+
likely going to be included in their 3.10 release, so we ignore the warning.
|
| 166 |
+
See msys2/MINGW-packages#9319.
|
| 167 |
+
|
| 168 |
+
MSYS2 MINGW's patch uses lowercase ``"lib"`` instead of the usual uppercase,
|
| 169 |
+
and is missing the final ``"site-packages"``.
|
| 170 |
+
"""
|
| 171 |
+
paths = sysconfig.get_paths("nt", expand=False)
|
| 172 |
+
return all(
|
| 173 |
+
"Lib" not in p and "lib" in p and not p.endswith("site-packages")
|
| 174 |
+
for p in (paths[key] for key in ("platlib", "purelib"))
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@functools.cache
|
| 179 |
+
def _warn_mismatched(old: pathlib.Path, new: pathlib.Path, *, key: str) -> None:
|
| 180 |
+
issue_url = "https://github.com/pypa/pip/issues/10151"
|
| 181 |
+
message = (
|
| 182 |
+
"Value for %s does not match. Please report this to <%s>"
|
| 183 |
+
"\ndistutils: %s"
|
| 184 |
+
"\nsysconfig: %s"
|
| 185 |
+
)
|
| 186 |
+
logger.log(_MISMATCH_LEVEL, message, key, issue_url, old, new)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _warn_if_mismatch(old: pathlib.Path, new: pathlib.Path, *, key: str) -> bool:
|
| 190 |
+
if old == new:
|
| 191 |
+
return False
|
| 192 |
+
_warn_mismatched(old, new, key=key)
|
| 193 |
+
return True
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@functools.cache
|
| 197 |
+
def _log_context(
|
| 198 |
+
*,
|
| 199 |
+
user: bool = False,
|
| 200 |
+
home: str | None = None,
|
| 201 |
+
root: str | None = None,
|
| 202 |
+
prefix: str | None = None,
|
| 203 |
+
) -> None:
|
| 204 |
+
parts = [
|
| 205 |
+
"Additional context:",
|
| 206 |
+
"user = %r",
|
| 207 |
+
"home = %r",
|
| 208 |
+
"root = %r",
|
| 209 |
+
"prefix = %r",
|
| 210 |
+
]
|
| 211 |
+
|
| 212 |
+
logger.log(_MISMATCH_LEVEL, "\n".join(parts), user, home, root, prefix)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def get_scheme(
|
| 216 |
+
dist_name: str,
|
| 217 |
+
user: bool = False,
|
| 218 |
+
home: str | None = None,
|
| 219 |
+
root: str | None = None,
|
| 220 |
+
isolated: bool = False,
|
| 221 |
+
prefix: str | None = None,
|
| 222 |
+
) -> Scheme:
|
| 223 |
+
new = _sysconfig.get_scheme(
|
| 224 |
+
dist_name,
|
| 225 |
+
user=user,
|
| 226 |
+
home=home,
|
| 227 |
+
root=root,
|
| 228 |
+
isolated=isolated,
|
| 229 |
+
prefix=prefix,
|
| 230 |
+
)
|
| 231 |
+
if _USE_SYSCONFIG:
|
| 232 |
+
return new
|
| 233 |
+
|
| 234 |
+
old = _distutils.get_scheme(
|
| 235 |
+
dist_name,
|
| 236 |
+
user=user,
|
| 237 |
+
home=home,
|
| 238 |
+
root=root,
|
| 239 |
+
isolated=isolated,
|
| 240 |
+
prefix=prefix,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
warning_contexts = []
|
| 244 |
+
for k in SCHEME_KEYS:
|
| 245 |
+
old_v = pathlib.Path(getattr(old, k))
|
| 246 |
+
new_v = pathlib.Path(getattr(new, k))
|
| 247 |
+
|
| 248 |
+
if old_v == new_v:
|
| 249 |
+
continue
|
| 250 |
+
|
| 251 |
+
# distutils incorrectly put PyPy packages under ``site-packages/python``
|
| 252 |
+
# in the ``posix_home`` scheme, but PyPy devs said they expect the
|
| 253 |
+
# directory name to be ``pypy`` instead. So we treat this as a bug fix
|
| 254 |
+
# and not warn about it. See bpo-43307 and python/cpython#24628.
|
| 255 |
+
skip_pypy_special_case = (
|
| 256 |
+
sys.implementation.name == "pypy"
|
| 257 |
+
and home is not None
|
| 258 |
+
and k in ("platlib", "purelib")
|
| 259 |
+
and old_v.parent == new_v.parent
|
| 260 |
+
and old_v.name.startswith("python")
|
| 261 |
+
and new_v.name.startswith("pypy")
|
| 262 |
+
)
|
| 263 |
+
if skip_pypy_special_case:
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
# sysconfig's ``osx_framework_user`` does not include ``pythonX.Y`` in
|
| 267 |
+
# the ``include`` value, but distutils's ``headers`` does. We'll let
|
| 268 |
+
# CPython decide whether this is a bug or feature. See bpo-43948.
|
| 269 |
+
skip_osx_framework_user_special_case = (
|
| 270 |
+
user
|
| 271 |
+
and is_osx_framework()
|
| 272 |
+
and k == "headers"
|
| 273 |
+
and old_v.parent.parent == new_v.parent
|
| 274 |
+
and old_v.parent.name.startswith("python")
|
| 275 |
+
)
|
| 276 |
+
if skip_osx_framework_user_special_case:
|
| 277 |
+
continue
|
| 278 |
+
|
| 279 |
+
# On Red Hat and derived Linux distributions, distutils is patched to
|
| 280 |
+
# use "lib64" instead of "lib" for platlib.
|
| 281 |
+
if k == "platlib" and _looks_like_red_hat_lib():
|
| 282 |
+
continue
|
| 283 |
+
|
| 284 |
+
# On Python 3.9+, sysconfig's posix_user scheme sets platlib against
|
| 285 |
+
# sys.platlibdir, but distutils's unix_user incorrectly continues
|
| 286 |
+
# using the same $usersite for both platlib and purelib. This creates a
|
| 287 |
+
# mismatch when sys.platlibdir is not "lib".
|
| 288 |
+
skip_bpo_44860 = (
|
| 289 |
+
user
|
| 290 |
+
and k == "platlib"
|
| 291 |
+
and not WINDOWS
|
| 292 |
+
and _PLATLIBDIR != "lib"
|
| 293 |
+
and _looks_like_bpo_44860()
|
| 294 |
+
)
|
| 295 |
+
if skip_bpo_44860:
|
| 296 |
+
continue
|
| 297 |
+
|
| 298 |
+
# Slackware incorrectly patches posix_user to use lib64 instead of lib,
|
| 299 |
+
# but not usersite to match the location.
|
| 300 |
+
skip_slackware_user_scheme = (
|
| 301 |
+
user
|
| 302 |
+
and k in ("platlib", "purelib")
|
| 303 |
+
and not WINDOWS
|
| 304 |
+
and _looks_like_slackware_scheme()
|
| 305 |
+
)
|
| 306 |
+
if skip_slackware_user_scheme:
|
| 307 |
+
continue
|
| 308 |
+
|
| 309 |
+
# Both Debian and Red Hat patch Python to place the system site under
|
| 310 |
+
# /usr/local instead of /usr. Debian also places lib in dist-packages
|
| 311 |
+
# instead of site-packages, but the /usr/local check should cover it.
|
| 312 |
+
skip_linux_system_special_case = (
|
| 313 |
+
not (user or home or prefix or running_under_virtualenv())
|
| 314 |
+
and old_v.parts[1:3] == ("usr", "local")
|
| 315 |
+
and len(new_v.parts) > 1
|
| 316 |
+
and new_v.parts[1] == "usr"
|
| 317 |
+
and (len(new_v.parts) < 3 or new_v.parts[2] != "local")
|
| 318 |
+
and (_looks_like_red_hat_scheme() or _looks_like_debian_scheme())
|
| 319 |
+
)
|
| 320 |
+
if skip_linux_system_special_case:
|
| 321 |
+
continue
|
| 322 |
+
|
| 323 |
+
# MSYS2 MINGW's sysconfig patch does not include the "site-packages"
|
| 324 |
+
# part of the path. This is incorrect and will be fixed in MSYS.
|
| 325 |
+
skip_msys2_mingw_bug = (
|
| 326 |
+
WINDOWS and k in ("platlib", "purelib") and _looks_like_msys2_mingw_scheme()
|
| 327 |
+
)
|
| 328 |
+
if skip_msys2_mingw_bug:
|
| 329 |
+
continue
|
| 330 |
+
|
| 331 |
+
# CPython's POSIX install script invokes pip (via ensurepip) against the
|
| 332 |
+
# interpreter located in the source tree, not the install site. This
|
| 333 |
+
# triggers special logic in sysconfig that's not present in distutils.
|
| 334 |
+
# https://github.com/python/cpython/blob/8c21941ddaf/Lib/sysconfig.py#L178-L194
|
| 335 |
+
skip_cpython_build = (
|
| 336 |
+
sysconfig.is_python_build(check_home=True)
|
| 337 |
+
and not WINDOWS
|
| 338 |
+
and k in ("headers", "include", "platinclude")
|
| 339 |
+
)
|
| 340 |
+
if skip_cpython_build:
|
| 341 |
+
continue
|
| 342 |
+
|
| 343 |
+
warning_contexts.append((old_v, new_v, f"scheme.{k}"))
|
| 344 |
+
|
| 345 |
+
if not warning_contexts:
|
| 346 |
+
return old
|
| 347 |
+
|
| 348 |
+
# Check if this path mismatch is caused by distutils config files. Those
|
| 349 |
+
# files will no longer work once we switch to sysconfig, so this raises a
|
| 350 |
+
# deprecation message for them.
|
| 351 |
+
default_old = _distutils.distutils_scheme(
|
| 352 |
+
dist_name,
|
| 353 |
+
user,
|
| 354 |
+
home,
|
| 355 |
+
root,
|
| 356 |
+
isolated,
|
| 357 |
+
prefix,
|
| 358 |
+
ignore_config_files=True,
|
| 359 |
+
)
|
| 360 |
+
if any(default_old[k] != getattr(old, k) for k in SCHEME_KEYS):
|
| 361 |
+
deprecated(
|
| 362 |
+
reason=(
|
| 363 |
+
"Configuring installation scheme with distutils config files "
|
| 364 |
+
"is deprecated and will no longer work in the near future. If you "
|
| 365 |
+
"are using a Homebrew or Linuxbrew Python, please see discussion "
|
| 366 |
+
"at https://github.com/Homebrew/homebrew-core/issues/76621"
|
| 367 |
+
),
|
| 368 |
+
replacement=None,
|
| 369 |
+
gone_in=None,
|
| 370 |
+
)
|
| 371 |
+
return old
|
| 372 |
+
|
| 373 |
+
# Post warnings about this mismatch so user can report them back.
|
| 374 |
+
for old_v, new_v, key in warning_contexts:
|
| 375 |
+
_warn_mismatched(old_v, new_v, key=key)
|
| 376 |
+
_log_context(user=user, home=home, root=root, prefix=prefix)
|
| 377 |
+
|
| 378 |
+
return old
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def get_bin_prefix() -> str:
|
| 382 |
+
new = _sysconfig.get_bin_prefix()
|
| 383 |
+
if _USE_SYSCONFIG:
|
| 384 |
+
return new
|
| 385 |
+
|
| 386 |
+
old = _distutils.get_bin_prefix()
|
| 387 |
+
if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="bin_prefix"):
|
| 388 |
+
_log_context()
|
| 389 |
+
return old
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def get_bin_user() -> str:
|
| 393 |
+
return _sysconfig.get_scheme("", user=True).scripts
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def _looks_like_deb_system_dist_packages(value: str) -> bool:
|
| 397 |
+
"""Check if the value is Debian's APT-controlled dist-packages.
|
| 398 |
+
|
| 399 |
+
Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the
|
| 400 |
+
default package path controlled by APT, but does not patch ``sysconfig`` to
|
| 401 |
+
do the same. This is similar to the bug worked around in ``get_scheme()``,
|
| 402 |
+
but here the default is ``deb_system`` instead of ``unix_local``. Ultimately
|
| 403 |
+
we can't do anything about this Debian bug, and this detection allows us to
|
| 404 |
+
skip the warning when needed.
|
| 405 |
+
"""
|
| 406 |
+
if not _looks_like_debian_scheme():
|
| 407 |
+
return False
|
| 408 |
+
if value == "/usr/lib/python3/dist-packages":
|
| 409 |
+
return True
|
| 410 |
+
return False
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def get_purelib() -> str:
|
| 414 |
+
"""Return the default pure-Python lib location."""
|
| 415 |
+
new = _sysconfig.get_purelib()
|
| 416 |
+
if _USE_SYSCONFIG:
|
| 417 |
+
return new
|
| 418 |
+
|
| 419 |
+
old = _distutils.get_purelib()
|
| 420 |
+
if _looks_like_deb_system_dist_packages(old):
|
| 421 |
+
return old
|
| 422 |
+
if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="purelib"):
|
| 423 |
+
_log_context()
|
| 424 |
+
return old
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def get_platlib() -> str:
|
| 428 |
+
"""Return the default platform-shared lib location."""
|
| 429 |
+
new = _sysconfig.get_platlib()
|
| 430 |
+
if _USE_SYSCONFIG:
|
| 431 |
+
return new
|
| 432 |
+
|
| 433 |
+
from . import _distutils
|
| 434 |
+
|
| 435 |
+
old = _distutils.get_platlib()
|
| 436 |
+
if _looks_like_deb_system_dist_packages(old):
|
| 437 |
+
return old
|
| 438 |
+
if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="platlib"):
|
| 439 |
+
_log_context()
|
| 440 |
+
return old
|
.venv/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Locations where we look for configs, install stuff, etc"""
|
| 2 |
+
|
| 3 |
+
# The following comment should be removed at some point in the future.
|
| 4 |
+
# mypy: strict-optional=False
|
| 5 |
+
|
| 6 |
+
# If pip's going to use distutils, it should not be using the copy that setuptools
|
| 7 |
+
# might have injected into the environment. This is done by removing the injected
|
| 8 |
+
# shim, if it's injected.
|
| 9 |
+
#
|
| 10 |
+
# See https://github.com/pypa/pip/issues/8761 for the original discussion and
|
| 11 |
+
# rationale for why this is done within pip.
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
__import__("_distutils_hack").remove_shim()
|
| 16 |
+
except (ImportError, AttributeError):
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
from distutils.cmd import Command as DistutilsCommand
|
| 23 |
+
from distutils.command.install import SCHEME_KEYS
|
| 24 |
+
from distutils.command.install import install as distutils_install_command
|
| 25 |
+
from distutils.sysconfig import get_python_lib
|
| 26 |
+
|
| 27 |
+
from pip._internal.models.scheme import Scheme
|
| 28 |
+
from pip._internal.utils.compat import WINDOWS
|
| 29 |
+
from pip._internal.utils.virtualenv import running_under_virtualenv
|
| 30 |
+
|
| 31 |
+
from .base import get_major_minor_version
|
| 32 |
+
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def distutils_scheme(
|
| 37 |
+
dist_name: str,
|
| 38 |
+
user: bool = False,
|
| 39 |
+
home: str | None = None,
|
| 40 |
+
root: str | None = None,
|
| 41 |
+
isolated: bool = False,
|
| 42 |
+
prefix: str | None = None,
|
| 43 |
+
*,
|
| 44 |
+
ignore_config_files: bool = False,
|
| 45 |
+
) -> dict[str, str]:
|
| 46 |
+
"""
|
| 47 |
+
Return a distutils install scheme
|
| 48 |
+
"""
|
| 49 |
+
from distutils.dist import Distribution
|
| 50 |
+
|
| 51 |
+
dist_args: dict[str, str | list[str]] = {"name": dist_name}
|
| 52 |
+
if isolated:
|
| 53 |
+
dist_args["script_args"] = ["--no-user-cfg"]
|
| 54 |
+
|
| 55 |
+
d = Distribution(dist_args)
|
| 56 |
+
if not ignore_config_files:
|
| 57 |
+
try:
|
| 58 |
+
d.parse_config_files()
|
| 59 |
+
except UnicodeDecodeError:
|
| 60 |
+
paths = d.find_config_files()
|
| 61 |
+
logger.warning(
|
| 62 |
+
"Ignore distutils configs in %s due to encoding errors.",
|
| 63 |
+
", ".join(os.path.basename(p) for p in paths),
|
| 64 |
+
)
|
| 65 |
+
obj: DistutilsCommand | None = None
|
| 66 |
+
obj = d.get_command_obj("install", create=True)
|
| 67 |
+
assert obj is not None
|
| 68 |
+
i: distutils_install_command = obj
|
| 69 |
+
# NOTE: setting user or home has the side-effect of creating the home dir
|
| 70 |
+
# or user base for installations during finalize_options()
|
| 71 |
+
# ideally, we'd prefer a scheme class that has no side-effects.
|
| 72 |
+
assert not (user and prefix), f"user={user} prefix={prefix}"
|
| 73 |
+
assert not (home and prefix), f"home={home} prefix={prefix}"
|
| 74 |
+
i.user = user or i.user
|
| 75 |
+
if user or home:
|
| 76 |
+
i.prefix = ""
|
| 77 |
+
i.prefix = prefix or i.prefix
|
| 78 |
+
i.home = home or i.home
|
| 79 |
+
i.root = root or i.root
|
| 80 |
+
i.finalize_options()
|
| 81 |
+
|
| 82 |
+
scheme: dict[str, str] = {}
|
| 83 |
+
for key in SCHEME_KEYS:
|
| 84 |
+
scheme[key] = getattr(i, "install_" + key)
|
| 85 |
+
|
| 86 |
+
# install_lib specified in setup.cfg should install *everything*
|
| 87 |
+
# into there (i.e. it takes precedence over both purelib and
|
| 88 |
+
# platlib). Note, i.install_lib is *always* set after
|
| 89 |
+
# finalize_options(); we only want to override here if the user
|
| 90 |
+
# has explicitly requested it hence going back to the config
|
| 91 |
+
if "install_lib" in d.get_option_dict("install"):
|
| 92 |
+
scheme.update({"purelib": i.install_lib, "platlib": i.install_lib})
|
| 93 |
+
|
| 94 |
+
if running_under_virtualenv():
|
| 95 |
+
if home:
|
| 96 |
+
prefix = home
|
| 97 |
+
elif user:
|
| 98 |
+
prefix = i.install_userbase
|
| 99 |
+
else:
|
| 100 |
+
prefix = i.prefix
|
| 101 |
+
scheme["headers"] = os.path.join(
|
| 102 |
+
prefix,
|
| 103 |
+
"include",
|
| 104 |
+
"site",
|
| 105 |
+
f"python{get_major_minor_version()}",
|
| 106 |
+
dist_name,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
if root is not None:
|
| 110 |
+
path_no_drive = os.path.splitdrive(os.path.abspath(scheme["headers"]))[1]
|
| 111 |
+
scheme["headers"] = os.path.join(root, path_no_drive[1:])
|
| 112 |
+
|
| 113 |
+
return scheme
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_scheme(
|
| 117 |
+
dist_name: str,
|
| 118 |
+
user: bool = False,
|
| 119 |
+
home: str | None = None,
|
| 120 |
+
root: str | None = None,
|
| 121 |
+
isolated: bool = False,
|
| 122 |
+
prefix: str | None = None,
|
| 123 |
+
) -> Scheme:
|
| 124 |
+
"""
|
| 125 |
+
Get the "scheme" corresponding to the input parameters. The distutils
|
| 126 |
+
documentation provides the context for the available schemes:
|
| 127 |
+
https://docs.python.org/3/install/index.html#alternate-installation
|
| 128 |
+
|
| 129 |
+
:param dist_name: the name of the package to retrieve the scheme for, used
|
| 130 |
+
in the headers scheme path
|
| 131 |
+
:param user: indicates to use the "user" scheme
|
| 132 |
+
:param home: indicates to use the "home" scheme and provides the base
|
| 133 |
+
directory for the same
|
| 134 |
+
:param root: root under which other directories are re-based
|
| 135 |
+
:param isolated: equivalent to --no-user-cfg, i.e. do not consider
|
| 136 |
+
~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for
|
| 137 |
+
scheme paths
|
| 138 |
+
:param prefix: indicates to use the "prefix" scheme and provides the
|
| 139 |
+
base directory for the same
|
| 140 |
+
"""
|
| 141 |
+
scheme = distutils_scheme(dist_name, user, home, root, isolated, prefix)
|
| 142 |
+
return Scheme(
|
| 143 |
+
platlib=scheme["platlib"],
|
| 144 |
+
purelib=scheme["purelib"],
|
| 145 |
+
headers=scheme["headers"],
|
| 146 |
+
scripts=scheme["scripts"],
|
| 147 |
+
data=scheme["data"],
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def get_bin_prefix() -> str:
|
| 152 |
+
# XXX: In old virtualenv versions, sys.prefix can contain '..' components,
|
| 153 |
+
# so we need to call normpath to eliminate them.
|
| 154 |
+
prefix = os.path.normpath(sys.prefix)
|
| 155 |
+
if WINDOWS:
|
| 156 |
+
bin_py = os.path.join(prefix, "Scripts")
|
| 157 |
+
# buildout uses 'bin' on Windows too?
|
| 158 |
+
if not os.path.exists(bin_py):
|
| 159 |
+
bin_py = os.path.join(prefix, "bin")
|
| 160 |
+
return bin_py
|
| 161 |
+
# Forcing to use /usr/local/bin for standard macOS framework installs
|
| 162 |
+
# Also log to ~/Library/Logs/ for use with the Console.app log viewer
|
| 163 |
+
if sys.platform[:6] == "darwin" and prefix[:16] == "/System/Library/":
|
| 164 |
+
return "/usr/local/bin"
|
| 165 |
+
return os.path.join(prefix, "bin")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def get_purelib() -> str:
|
| 169 |
+
return get_python_lib(plat_specific=False)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_platlib() -> str:
|
| 173 |
+
return get_python_lib(plat_specific=True)
|
.venv/lib/python3.12/site-packages/pip/_internal/locations/_sysconfig.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 9 |
+
from pip._internal.exceptions import InvalidSchemeCombination, UserInstallationInvalid
|
| 10 |
+
from pip._internal.models.scheme import SCHEME_KEYS, Scheme
|
| 11 |
+
from pip._internal.utils.virtualenv import running_under_virtualenv
|
| 12 |
+
|
| 13 |
+
from .base import change_root, get_major_minor_version, is_osx_framework
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Notes on _infer_* functions.
|
| 19 |
+
# Unfortunately ``get_default_scheme()`` didn't exist before 3.10, so there's no
|
| 20 |
+
# way to ask things like "what is the '_prefix' scheme on this platform". These
|
| 21 |
+
# functions try to answer that with some heuristics while accounting for ad-hoc
|
| 22 |
+
# platforms not covered by CPython's default sysconfig implementation. If the
|
| 23 |
+
# ad-hoc implementation does not fully implement sysconfig, we'll fall back to
|
| 24 |
+
# a POSIX scheme.
|
| 25 |
+
|
| 26 |
+
_AVAILABLE_SCHEMES = set(sysconfig.get_scheme_names())
|
| 27 |
+
|
| 28 |
+
_PREFERRED_SCHEME_API: Callable[[str], str] | None = getattr(
|
| 29 |
+
sysconfig, "get_preferred_scheme", None
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _should_use_osx_framework_prefix() -> bool:
|
| 34 |
+
"""Check for Apple's ``osx_framework_library`` scheme.
|
| 35 |
+
|
| 36 |
+
Python distributed by Apple's Command Line Tools has this special scheme
|
| 37 |
+
that's used when:
|
| 38 |
+
|
| 39 |
+
* This is a framework build.
|
| 40 |
+
* We are installing into the system prefix.
|
| 41 |
+
|
| 42 |
+
This does not account for ``pip install --prefix`` (also means we're not
|
| 43 |
+
installing to the system prefix), which should use ``posix_prefix``, but
|
| 44 |
+
logic here means ``_infer_prefix()`` outputs ``osx_framework_library``. But
|
| 45 |
+
since ``prefix`` is not available for ``sysconfig.get_default_scheme()``,
|
| 46 |
+
which is the stdlib replacement for ``_infer_prefix()``, presumably Apple
|
| 47 |
+
wouldn't be able to magically switch between ``osx_framework_library`` and
|
| 48 |
+
``posix_prefix``. ``_infer_prefix()`` returning ``osx_framework_library``
|
| 49 |
+
means its behavior is consistent whether we use the stdlib implementation
|
| 50 |
+
or our own, and we deal with this special case in ``get_scheme()`` instead.
|
| 51 |
+
"""
|
| 52 |
+
return (
|
| 53 |
+
"osx_framework_library" in _AVAILABLE_SCHEMES
|
| 54 |
+
and not running_under_virtualenv()
|
| 55 |
+
and is_osx_framework()
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _infer_prefix() -> str:
|
| 60 |
+
"""Try to find a prefix scheme for the current platform.
|
| 61 |
+
|
| 62 |
+
This tries:
|
| 63 |
+
|
| 64 |
+
* A special ``osx_framework_library`` for Python distributed by Apple's
|
| 65 |
+
Command Line Tools, when not running in a virtual environment.
|
| 66 |
+
* Implementation + OS, used by PyPy on Windows (``pypy_nt``).
|
| 67 |
+
* Implementation without OS, used by PyPy on POSIX (``pypy``).
|
| 68 |
+
* OS + "prefix", used by CPython on POSIX (``posix_prefix``).
|
| 69 |
+
* Just the OS name, used by CPython on Windows (``nt``).
|
| 70 |
+
|
| 71 |
+
If none of the above works, fall back to ``posix_prefix``.
|
| 72 |
+
"""
|
| 73 |
+
if _PREFERRED_SCHEME_API:
|
| 74 |
+
return _PREFERRED_SCHEME_API("prefix")
|
| 75 |
+
if _should_use_osx_framework_prefix():
|
| 76 |
+
return "osx_framework_library"
|
| 77 |
+
implementation_suffixed = f"{sys.implementation.name}_{os.name}"
|
| 78 |
+
if implementation_suffixed in _AVAILABLE_SCHEMES:
|
| 79 |
+
return implementation_suffixed
|
| 80 |
+
if sys.implementation.name in _AVAILABLE_SCHEMES:
|
| 81 |
+
return sys.implementation.name
|
| 82 |
+
suffixed = f"{os.name}_prefix"
|
| 83 |
+
if suffixed in _AVAILABLE_SCHEMES:
|
| 84 |
+
return suffixed
|
| 85 |
+
if os.name in _AVAILABLE_SCHEMES: # On Windows, prefx is just called "nt".
|
| 86 |
+
return os.name
|
| 87 |
+
return "posix_prefix"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _infer_user() -> str:
|
| 91 |
+
"""Try to find a user scheme for the current platform."""
|
| 92 |
+
if _PREFERRED_SCHEME_API:
|
| 93 |
+
return _PREFERRED_SCHEME_API("user")
|
| 94 |
+
if is_osx_framework() and not running_under_virtualenv():
|
| 95 |
+
suffixed = "osx_framework_user"
|
| 96 |
+
else:
|
| 97 |
+
suffixed = f"{os.name}_user"
|
| 98 |
+
if suffixed in _AVAILABLE_SCHEMES:
|
| 99 |
+
return suffixed
|
| 100 |
+
if "posix_user" not in _AVAILABLE_SCHEMES: # User scheme unavailable.
|
| 101 |
+
raise UserInstallationInvalid()
|
| 102 |
+
return "posix_user"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _infer_home() -> str:
|
| 106 |
+
"""Try to find a home for the current platform."""
|
| 107 |
+
if _PREFERRED_SCHEME_API:
|
| 108 |
+
return _PREFERRED_SCHEME_API("home")
|
| 109 |
+
suffixed = f"{os.name}_home"
|
| 110 |
+
if suffixed in _AVAILABLE_SCHEMES:
|
| 111 |
+
return suffixed
|
| 112 |
+
return "posix_home"
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# Update these keys if the user sets a custom home.
|
| 116 |
+
_HOME_KEYS = [
|
| 117 |
+
"installed_base",
|
| 118 |
+
"base",
|
| 119 |
+
"installed_platbase",
|
| 120 |
+
"platbase",
|
| 121 |
+
"prefix",
|
| 122 |
+
"exec_prefix",
|
| 123 |
+
]
|
| 124 |
+
if sysconfig.get_config_var("userbase") is not None:
|
| 125 |
+
_HOME_KEYS.append("userbase")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_scheme(
|
| 129 |
+
dist_name: str,
|
| 130 |
+
user: bool = False,
|
| 131 |
+
home: str | None = None,
|
| 132 |
+
root: str | None = None,
|
| 133 |
+
isolated: bool = False,
|
| 134 |
+
prefix: str | None = None,
|
| 135 |
+
) -> Scheme:
|
| 136 |
+
"""
|
| 137 |
+
Get the "scheme" corresponding to the input parameters.
|
| 138 |
+
|
| 139 |
+
:param dist_name: the name of the package to retrieve the scheme for, used
|
| 140 |
+
in the headers scheme path
|
| 141 |
+
:param user: indicates to use the "user" scheme
|
| 142 |
+
:param home: indicates to use the "home" scheme
|
| 143 |
+
:param root: root under which other directories are re-based
|
| 144 |
+
:param isolated: ignored, but kept for distutils compatibility (where
|
| 145 |
+
this controls whether the user-site pydistutils.cfg is honored)
|
| 146 |
+
:param prefix: indicates to use the "prefix" scheme and provides the
|
| 147 |
+
base directory for the same
|
| 148 |
+
"""
|
| 149 |
+
if user and prefix:
|
| 150 |
+
raise InvalidSchemeCombination("--user", "--prefix")
|
| 151 |
+
if home and prefix:
|
| 152 |
+
raise InvalidSchemeCombination("--home", "--prefix")
|
| 153 |
+
|
| 154 |
+
if home is not None:
|
| 155 |
+
scheme_name = _infer_home()
|
| 156 |
+
elif user:
|
| 157 |
+
scheme_name = _infer_user()
|
| 158 |
+
else:
|
| 159 |
+
scheme_name = _infer_prefix()
|
| 160 |
+
|
| 161 |
+
# Special case: When installing into a custom prefix, use posix_prefix
|
| 162 |
+
# instead of osx_framework_library. See _should_use_osx_framework_prefix()
|
| 163 |
+
# docstring for details.
|
| 164 |
+
if prefix is not None and scheme_name == "osx_framework_library":
|
| 165 |
+
scheme_name = "posix_prefix"
|
| 166 |
+
|
| 167 |
+
if home is not None:
|
| 168 |
+
variables = {k: home for k in _HOME_KEYS}
|
| 169 |
+
elif prefix is not None:
|
| 170 |
+
variables = {k: prefix for k in _HOME_KEYS}
|
| 171 |
+
else:
|
| 172 |
+
variables = {}
|
| 173 |
+
|
| 174 |
+
paths = sysconfig.get_paths(scheme=scheme_name, vars=variables)
|
| 175 |
+
|
| 176 |
+
# Logic here is very arbitrary, we're doing it for compatibility, don't ask.
|
| 177 |
+
# 1. Pip historically uses a special header path in virtual environments.
|
| 178 |
+
# 2. If the distribution name is not known, distutils uses 'UNKNOWN'. We
|
| 179 |
+
# only do the same when not running in a virtual environment because
|
| 180 |
+
# pip's historical header path logic (see point 1) did not do this.
|
| 181 |
+
if running_under_virtualenv():
|
| 182 |
+
if user:
|
| 183 |
+
base = variables.get("userbase", sys.prefix)
|
| 184 |
+
else:
|
| 185 |
+
base = variables.get("base", sys.prefix)
|
| 186 |
+
python_xy = f"python{get_major_minor_version()}"
|
| 187 |
+
paths["include"] = os.path.join(base, "include", "site", python_xy)
|
| 188 |
+
elif not dist_name:
|
| 189 |
+
dist_name = "UNKNOWN"
|
| 190 |
+
|
| 191 |
+
scheme = Scheme(
|
| 192 |
+
platlib=paths["platlib"],
|
| 193 |
+
purelib=paths["purelib"],
|
| 194 |
+
headers=os.path.join(paths["include"], dist_name),
|
| 195 |
+
scripts=paths["scripts"],
|
| 196 |
+
data=paths["data"],
|
| 197 |
+
)
|
| 198 |
+
if root is not None:
|
| 199 |
+
converted_keys = {}
|
| 200 |
+
for key in SCHEME_KEYS:
|
| 201 |
+
converted_keys[key] = change_root(root, getattr(scheme, key))
|
| 202 |
+
scheme = Scheme(**converted_keys)
|
| 203 |
+
return scheme
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def get_bin_prefix() -> str:
|
| 207 |
+
# Forcing to use /usr/local/bin for standard macOS framework installs.
|
| 208 |
+
if sys.platform[:6] == "darwin" and sys.prefix[:16] == "/System/Library/":
|
| 209 |
+
return "/usr/local/bin"
|
| 210 |
+
return sysconfig.get_paths()["scripts"]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def get_purelib() -> str:
|
| 214 |
+
return sysconfig.get_paths()["purelib"]
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def get_platlib() -> str:
|
| 218 |
+
return sysconfig.get_paths()["platlib"]
|
.venv/lib/python3.12/site-packages/pip/_internal/metadata/__init__.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 6 |
+
import sys
|
| 7 |
+
from typing import TYPE_CHECKING, Literal, Protocol, cast
|
| 8 |
+
|
| 9 |
+
from pip._internal.utils.deprecation import deprecated
|
| 10 |
+
from pip._internal.utils.misc import strtobool
|
| 11 |
+
|
| 12 |
+
from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from pip._vendor.packaging.utils import NormalizedName
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"BaseDistribution",
|
| 19 |
+
"BaseEnvironment",
|
| 20 |
+
"FilesystemWheel",
|
| 21 |
+
"MemoryWheel",
|
| 22 |
+
"Wheel",
|
| 23 |
+
"get_default_environment",
|
| 24 |
+
"get_environment",
|
| 25 |
+
"get_wheel_distribution",
|
| 26 |
+
"select_backend",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _should_use_importlib_metadata() -> bool:
|
| 31 |
+
"""Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.
|
| 32 |
+
|
| 33 |
+
By default, pip uses ``importlib.metadata`` on Python 3.11+, and
|
| 34 |
+
``pkg_resources`` otherwise. Up to Python 3.13, This can be
|
| 35 |
+
overridden by a couple of ways:
|
| 36 |
+
|
| 37 |
+
* If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it
|
| 38 |
+
dictates whether ``importlib.metadata`` is used, for Python <3.14.
|
| 39 |
+
* On Python 3.11, 3.12 and 3.13, Python distributors can patch
|
| 40 |
+
``importlib.metadata`` to add a global constant
|
| 41 |
+
``_PIP_USE_IMPORTLIB_METADATA = False``. This makes pip use
|
| 42 |
+
``pkg_resources`` (unless the user set the aforementioned environment
|
| 43 |
+
variable to *True*).
|
| 44 |
+
|
| 45 |
+
On Python 3.14+, the ``pkg_resources`` backend cannot be used.
|
| 46 |
+
"""
|
| 47 |
+
if sys.version_info >= (3, 14):
|
| 48 |
+
# On Python >=3.14 we only support importlib.metadata.
|
| 49 |
+
return True
|
| 50 |
+
with contextlib.suppress(KeyError, ValueError):
|
| 51 |
+
# On Python <3.14, if the environment variable is set, we obey what it says.
|
| 52 |
+
return bool(strtobool(os.environ["_PIP_USE_IMPORTLIB_METADATA"]))
|
| 53 |
+
if sys.version_info < (3, 11):
|
| 54 |
+
# On Python <3.11, we always use pkg_resources, unless the environment
|
| 55 |
+
# variable was set.
|
| 56 |
+
return False
|
| 57 |
+
# On Python 3.11, 3.12 and 3.13, we check if the global constant is set.
|
| 58 |
+
import importlib.metadata
|
| 59 |
+
|
| 60 |
+
return bool(getattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA", True))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _emit_pkg_resources_deprecation_if_needed() -> None:
|
| 64 |
+
if sys.version_info < (3, 11):
|
| 65 |
+
# All pip versions supporting Python<=3.11 will support pkg_resources,
|
| 66 |
+
# and pkg_resources is the default for these, so let's not bother users.
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
import importlib.metadata
|
| 70 |
+
|
| 71 |
+
if hasattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA"):
|
| 72 |
+
# The Python distributor has set the global constant, so we don't
|
| 73 |
+
# warn, since it is not a user decision.
|
| 74 |
+
return
|
| 75 |
+
|
| 76 |
+
# The user has decided to use pkg_resources, so we warn.
|
| 77 |
+
deprecated(
|
| 78 |
+
reason="Using the pkg_resources metadata backend is deprecated.",
|
| 79 |
+
replacement=(
|
| 80 |
+
"to use the default importlib.metadata backend, "
|
| 81 |
+
"by unsetting the _PIP_USE_IMPORTLIB_METADATA environment variable"
|
| 82 |
+
),
|
| 83 |
+
gone_in="26.3",
|
| 84 |
+
issue=13317,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class Backend(Protocol):
|
| 89 |
+
NAME: Literal["importlib", "pkg_resources"]
|
| 90 |
+
Distribution: type[BaseDistribution]
|
| 91 |
+
Environment: type[BaseEnvironment]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@functools.cache
|
| 95 |
+
def select_backend() -> Backend:
|
| 96 |
+
if _should_use_importlib_metadata():
|
| 97 |
+
from . import importlib
|
| 98 |
+
|
| 99 |
+
return cast(Backend, importlib)
|
| 100 |
+
|
| 101 |
+
_emit_pkg_resources_deprecation_if_needed()
|
| 102 |
+
|
| 103 |
+
from . import pkg_resources
|
| 104 |
+
|
| 105 |
+
return cast(Backend, pkg_resources)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_default_environment() -> BaseEnvironment:
|
| 109 |
+
"""Get the default representation for the current environment.
|
| 110 |
+
|
| 111 |
+
This returns an Environment instance from the chosen backend. The default
|
| 112 |
+
Environment instance should be built from ``sys.path`` and may use caching
|
| 113 |
+
to share instance state across calls.
|
| 114 |
+
"""
|
| 115 |
+
return select_backend().Environment.default()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def get_environment(paths: list[str] | None) -> BaseEnvironment:
|
| 119 |
+
"""Get a representation of the environment specified by ``paths``.
|
| 120 |
+
|
| 121 |
+
This returns an Environment instance from the chosen backend based on the
|
| 122 |
+
given import paths. The backend must build a fresh instance representing
|
| 123 |
+
the state of installed distributions when this function is called.
|
| 124 |
+
"""
|
| 125 |
+
return select_backend().Environment.from_paths(paths)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_directory_distribution(directory: str) -> BaseDistribution:
|
| 129 |
+
"""Get the distribution metadata representation in the specified directory.
|
| 130 |
+
|
| 131 |
+
This returns a Distribution instance from the chosen backend based on
|
| 132 |
+
the given on-disk ``.dist-info`` directory.
|
| 133 |
+
"""
|
| 134 |
+
return select_backend().Distribution.from_directory(directory)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def get_wheel_distribution(
|
| 138 |
+
wheel: Wheel, canonical_name: NormalizedName
|
| 139 |
+
) -> BaseDistribution:
|
| 140 |
+
"""Get the representation of the specified wheel's distribution metadata.
|
| 141 |
+
|
| 142 |
+
This returns a Distribution instance from the chosen backend based on
|
| 143 |
+
the given wheel's ``.dist-info`` directory.
|
| 144 |
+
|
| 145 |
+
:param canonical_name: Normalized project name of the given wheel.
|
| 146 |
+
"""
|
| 147 |
+
return select_backend().Distribution.from_wheel(wheel, canonical_name)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_metadata_distribution(
|
| 151 |
+
metadata_contents: bytes,
|
| 152 |
+
filename: str,
|
| 153 |
+
canonical_name: str,
|
| 154 |
+
) -> BaseDistribution:
|
| 155 |
+
"""Get the dist representation of the specified METADATA file contents.
|
| 156 |
+
|
| 157 |
+
This returns a Distribution instance from the chosen backend sourced from the data
|
| 158 |
+
in `metadata_contents`.
|
| 159 |
+
|
| 160 |
+
:param metadata_contents: Contents of a METADATA file within a dist, or one served
|
| 161 |
+
via PEP 658.
|
| 162 |
+
:param filename: Filename for the dist this metadata represents.
|
| 163 |
+
:param canonical_name: Normalized project name of the given dist.
|
| 164 |
+
"""
|
| 165 |
+
return select_backend().Distribution.from_metadata_file_contents(
|
| 166 |
+
metadata_contents,
|
| 167 |
+
filename,
|
| 168 |
+
canonical_name,
|
| 169 |
+
)
|
.venv/lib/python3.12/site-packages/pip/_internal/metadata/base.py
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
import email.message
|
| 5 |
+
import functools
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import pathlib
|
| 9 |
+
import re
|
| 10 |
+
import zipfile
|
| 11 |
+
from collections.abc import Collection, Container, Iterable, Iterator
|
| 12 |
+
from typing import (
|
| 13 |
+
IO,
|
| 14 |
+
Any,
|
| 15 |
+
NamedTuple,
|
| 16 |
+
Protocol,
|
| 17 |
+
Union,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
from pip._vendor.packaging.requirements import Requirement
|
| 21 |
+
from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
|
| 22 |
+
from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
|
| 23 |
+
from pip._vendor.packaging.version import Version
|
| 24 |
+
|
| 25 |
+
from pip._internal.exceptions import NoneMetadataError
|
| 26 |
+
from pip._internal.locations import site_packages, user_site
|
| 27 |
+
from pip._internal.models.direct_url import (
|
| 28 |
+
DIRECT_URL_METADATA_NAME,
|
| 29 |
+
DirectUrl,
|
| 30 |
+
DirectUrlValidationError,
|
| 31 |
+
)
|
| 32 |
+
from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.
|
| 33 |
+
from pip._internal.utils.egg_link import egg_link_path_from_sys_path
|
| 34 |
+
from pip._internal.utils.misc import is_local, normalize_path
|
| 35 |
+
from pip._internal.utils.urls import url_to_path
|
| 36 |
+
|
| 37 |
+
from ._json import msg_to_json
|
| 38 |
+
|
| 39 |
+
InfoPath = Union[str, pathlib.PurePath]
|
| 40 |
+
|
| 41 |
+
logger = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class BaseEntryPoint(Protocol):
|
| 45 |
+
@property
|
| 46 |
+
def name(self) -> str:
|
| 47 |
+
raise NotImplementedError()
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def value(self) -> str:
|
| 51 |
+
raise NotImplementedError()
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def group(self) -> str:
|
| 55 |
+
raise NotImplementedError()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _convert_installed_files_path(
|
| 59 |
+
entry: tuple[str, ...],
|
| 60 |
+
info: tuple[str, ...],
|
| 61 |
+
) -> str:
|
| 62 |
+
"""Convert a legacy installed-files.txt path into modern RECORD path.
|
| 63 |
+
|
| 64 |
+
The legacy format stores paths relative to the info directory, while the
|
| 65 |
+
modern format stores paths relative to the package root, e.g. the
|
| 66 |
+
site-packages directory.
|
| 67 |
+
|
| 68 |
+
:param entry: Path parts of the installed-files.txt entry.
|
| 69 |
+
:param info: Path parts of the egg-info directory relative to package root.
|
| 70 |
+
:returns: The converted entry.
|
| 71 |
+
|
| 72 |
+
For best compatibility with symlinks, this does not use ``abspath()`` or
|
| 73 |
+
``Path.resolve()``, but tries to work with path parts:
|
| 74 |
+
|
| 75 |
+
1. While ``entry`` starts with ``..``, remove the equal amounts of parts
|
| 76 |
+
from ``info``; if ``info`` is empty, start appending ``..`` instead.
|
| 77 |
+
2. Join the two directly.
|
| 78 |
+
"""
|
| 79 |
+
while entry and entry[0] == "..":
|
| 80 |
+
if not info or info[-1] == "..":
|
| 81 |
+
info += ("..",)
|
| 82 |
+
else:
|
| 83 |
+
info = info[:-1]
|
| 84 |
+
entry = entry[1:]
|
| 85 |
+
return str(pathlib.Path(*info, *entry))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class RequiresEntry(NamedTuple):
|
| 89 |
+
requirement: str
|
| 90 |
+
extra: str
|
| 91 |
+
marker: str
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class BaseDistribution(Protocol):
|
| 95 |
+
@classmethod
|
| 96 |
+
def from_directory(cls, directory: str) -> BaseDistribution:
|
| 97 |
+
"""Load the distribution from a metadata directory.
|
| 98 |
+
|
| 99 |
+
:param directory: Path to a metadata directory, e.g. ``.dist-info``.
|
| 100 |
+
"""
|
| 101 |
+
raise NotImplementedError()
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def from_metadata_file_contents(
|
| 105 |
+
cls,
|
| 106 |
+
metadata_contents: bytes,
|
| 107 |
+
filename: str,
|
| 108 |
+
project_name: str,
|
| 109 |
+
) -> BaseDistribution:
|
| 110 |
+
"""Load the distribution from the contents of a METADATA file.
|
| 111 |
+
|
| 112 |
+
This is used to implement PEP 658 by generating a "shallow" dist object that can
|
| 113 |
+
be used for resolution without downloading or building the actual dist yet.
|
| 114 |
+
|
| 115 |
+
:param metadata_contents: The contents of a METADATA file.
|
| 116 |
+
:param filename: File name for the dist with this metadata.
|
| 117 |
+
:param project_name: Name of the project this dist represents.
|
| 118 |
+
"""
|
| 119 |
+
raise NotImplementedError()
|
| 120 |
+
|
| 121 |
+
@classmethod
|
| 122 |
+
def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:
|
| 123 |
+
"""Load the distribution from a given wheel.
|
| 124 |
+
|
| 125 |
+
:param wheel: A concrete wheel definition.
|
| 126 |
+
:param name: File name of the wheel.
|
| 127 |
+
|
| 128 |
+
:raises InvalidWheel: Whenever loading of the wheel causes a
|
| 129 |
+
:py:exc:`zipfile.BadZipFile` exception to be thrown.
|
| 130 |
+
:raises UnsupportedWheel: If the wheel is a valid zip, but malformed
|
| 131 |
+
internally.
|
| 132 |
+
"""
|
| 133 |
+
raise NotImplementedError()
|
| 134 |
+
|
| 135 |
+
def __repr__(self) -> str:
|
| 136 |
+
return f"{self.raw_name} {self.raw_version} ({self.location})"
|
| 137 |
+
|
| 138 |
+
def __str__(self) -> str:
|
| 139 |
+
return f"{self.raw_name} {self.raw_version}"
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def location(self) -> str | None:
|
| 143 |
+
"""Where the distribution is loaded from.
|
| 144 |
+
|
| 145 |
+
A string value is not necessarily a filesystem path, since distributions
|
| 146 |
+
can be loaded from other sources, e.g. arbitrary zip archives. ``None``
|
| 147 |
+
means the distribution is created in-memory.
|
| 148 |
+
|
| 149 |
+
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
|
| 150 |
+
this is a symbolic link, we want to preserve the relative path between
|
| 151 |
+
it and files in the distribution.
|
| 152 |
+
"""
|
| 153 |
+
raise NotImplementedError()
|
| 154 |
+
|
| 155 |
+
@property
|
| 156 |
+
def editable_project_location(self) -> str | None:
|
| 157 |
+
"""The project location for editable distributions.
|
| 158 |
+
|
| 159 |
+
This is the directory where pyproject.toml or setup.py is located.
|
| 160 |
+
None if the distribution is not installed in editable mode.
|
| 161 |
+
"""
|
| 162 |
+
# TODO: this property is relatively costly to compute, memoize it ?
|
| 163 |
+
direct_url = self.direct_url
|
| 164 |
+
if direct_url:
|
| 165 |
+
if direct_url.is_local_editable():
|
| 166 |
+
return url_to_path(direct_url.url)
|
| 167 |
+
else:
|
| 168 |
+
# Search for an .egg-link file by walking sys.path, as it was
|
| 169 |
+
# done before by dist_is_editable().
|
| 170 |
+
egg_link_path = egg_link_path_from_sys_path(self.raw_name)
|
| 171 |
+
if egg_link_path:
|
| 172 |
+
# TODO: get project location from second line of egg_link file
|
| 173 |
+
# (https://github.com/pypa/pip/issues/10243)
|
| 174 |
+
return self.location
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
@property
|
| 178 |
+
def installed_location(self) -> str | None:
|
| 179 |
+
"""The distribution's "installed" location.
|
| 180 |
+
|
| 181 |
+
This should generally be a ``site-packages`` directory. This is
|
| 182 |
+
usually ``dist.location``, except for legacy develop-installed packages,
|
| 183 |
+
where ``dist.location`` is the source code location, and this is where
|
| 184 |
+
the ``.egg-link`` file is.
|
| 185 |
+
|
| 186 |
+
The returned location is normalized (in particular, with symlinks removed).
|
| 187 |
+
"""
|
| 188 |
+
raise NotImplementedError()
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def info_location(self) -> str | None:
|
| 192 |
+
"""Location of the .[egg|dist]-info directory or file.
|
| 193 |
+
|
| 194 |
+
Similarly to ``location``, a string value is not necessarily a
|
| 195 |
+
filesystem path. ``None`` means the distribution is created in-memory.
|
| 196 |
+
|
| 197 |
+
For a modern .dist-info installation on disk, this should be something
|
| 198 |
+
like ``{location}/{raw_name}-{version}.dist-info``.
|
| 199 |
+
|
| 200 |
+
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
|
| 201 |
+
this is a symbolic link, we want to preserve the relative path between
|
| 202 |
+
it and other files in the distribution.
|
| 203 |
+
"""
|
| 204 |
+
raise NotImplementedError()
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def installed_by_distutils(self) -> bool:
|
| 208 |
+
"""Whether this distribution is installed with legacy distutils format.
|
| 209 |
+
|
| 210 |
+
A distribution installed with "raw" distutils not patched by setuptools
|
| 211 |
+
uses one single file at ``info_location`` to store metadata. We need to
|
| 212 |
+
treat this specially on uninstallation.
|
| 213 |
+
"""
|
| 214 |
+
info_location = self.info_location
|
| 215 |
+
if not info_location:
|
| 216 |
+
return False
|
| 217 |
+
return pathlib.Path(info_location).is_file()
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def installed_as_egg(self) -> bool:
|
| 221 |
+
"""Whether this distribution is installed as an egg.
|
| 222 |
+
|
| 223 |
+
This usually indicates the distribution was installed by (older versions
|
| 224 |
+
of) easy_install.
|
| 225 |
+
"""
|
| 226 |
+
location = self.location
|
| 227 |
+
if not location:
|
| 228 |
+
return False
|
| 229 |
+
# XXX if the distribution is a zipped egg, location has a trailing /
|
| 230 |
+
# so we resort to pathlib.Path to check the suffix in a reliable way.
|
| 231 |
+
return pathlib.Path(location).suffix == ".egg"
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def installed_with_setuptools_egg_info(self) -> bool:
|
| 235 |
+
"""Whether this distribution is installed with the ``.egg-info`` format.
|
| 236 |
+
|
| 237 |
+
This usually indicates the distribution was installed with setuptools
|
| 238 |
+
with an old pip version or with ``single-version-externally-managed``.
|
| 239 |
+
|
| 240 |
+
Note that this ensure the metadata store is a directory. distutils can
|
| 241 |
+
also installs an ``.egg-info``, but as a file, not a directory. This
|
| 242 |
+
property is *False* for that case. Also see ``installed_by_distutils``.
|
| 243 |
+
"""
|
| 244 |
+
info_location = self.info_location
|
| 245 |
+
if not info_location:
|
| 246 |
+
return False
|
| 247 |
+
if not info_location.endswith(".egg-info"):
|
| 248 |
+
return False
|
| 249 |
+
return pathlib.Path(info_location).is_dir()
|
| 250 |
+
|
| 251 |
+
@property
|
| 252 |
+
def installed_with_dist_info(self) -> bool:
|
| 253 |
+
"""Whether this distribution is installed with the "modern format".
|
| 254 |
+
|
| 255 |
+
This indicates a "modern" installation, e.g. storing metadata in the
|
| 256 |
+
``.dist-info`` directory. This applies to installations made by
|
| 257 |
+
setuptools (but through pip, not directly), or anything using the
|
| 258 |
+
standardized build backend interface (PEP 517).
|
| 259 |
+
"""
|
| 260 |
+
info_location = self.info_location
|
| 261 |
+
if not info_location:
|
| 262 |
+
return False
|
| 263 |
+
if not info_location.endswith(".dist-info"):
|
| 264 |
+
return False
|
| 265 |
+
return pathlib.Path(info_location).is_dir()
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def canonical_name(self) -> NormalizedName:
|
| 269 |
+
raise NotImplementedError()
|
| 270 |
+
|
| 271 |
+
@property
|
| 272 |
+
def version(self) -> Version:
|
| 273 |
+
raise NotImplementedError()
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def raw_version(self) -> str:
|
| 277 |
+
raise NotImplementedError()
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def setuptools_filename(self) -> str:
|
| 281 |
+
"""Convert a project name to its setuptools-compatible filename.
|
| 282 |
+
|
| 283 |
+
This is a copy of ``pkg_resources.to_filename()`` for compatibility.
|
| 284 |
+
"""
|
| 285 |
+
return self.raw_name.replace("-", "_")
|
| 286 |
+
|
| 287 |
+
@property
|
| 288 |
+
def direct_url(self) -> DirectUrl | None:
|
| 289 |
+
"""Obtain a DirectUrl from this distribution.
|
| 290 |
+
|
| 291 |
+
Returns None if the distribution has no `direct_url.json` metadata,
|
| 292 |
+
or if `direct_url.json` is invalid.
|
| 293 |
+
"""
|
| 294 |
+
try:
|
| 295 |
+
content = self.read_text(DIRECT_URL_METADATA_NAME)
|
| 296 |
+
except FileNotFoundError:
|
| 297 |
+
return None
|
| 298 |
+
try:
|
| 299 |
+
return DirectUrl.from_json(content)
|
| 300 |
+
except (
|
| 301 |
+
UnicodeDecodeError,
|
| 302 |
+
json.JSONDecodeError,
|
| 303 |
+
DirectUrlValidationError,
|
| 304 |
+
) as e:
|
| 305 |
+
logger.warning(
|
| 306 |
+
"Error parsing %s for %s: %s",
|
| 307 |
+
DIRECT_URL_METADATA_NAME,
|
| 308 |
+
self.canonical_name,
|
| 309 |
+
e,
|
| 310 |
+
)
|
| 311 |
+
return None
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def installer(self) -> str:
|
| 315 |
+
try:
|
| 316 |
+
installer_text = self.read_text("INSTALLER")
|
| 317 |
+
except (OSError, ValueError, NoneMetadataError):
|
| 318 |
+
return "" # Fail silently if the installer file cannot be read.
|
| 319 |
+
for line in installer_text.splitlines():
|
| 320 |
+
cleaned_line = line.strip()
|
| 321 |
+
if cleaned_line:
|
| 322 |
+
return cleaned_line
|
| 323 |
+
return ""
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def requested(self) -> bool:
|
| 327 |
+
return self.is_file("REQUESTED")
|
| 328 |
+
|
| 329 |
+
@property
|
| 330 |
+
def editable(self) -> bool:
|
| 331 |
+
return bool(self.editable_project_location)
|
| 332 |
+
|
| 333 |
+
@property
|
| 334 |
+
def local(self) -> bool:
|
| 335 |
+
"""If distribution is installed in the current virtual environment.
|
| 336 |
+
|
| 337 |
+
Always True if we're not in a virtualenv.
|
| 338 |
+
"""
|
| 339 |
+
if self.installed_location is None:
|
| 340 |
+
return False
|
| 341 |
+
return is_local(self.installed_location)
|
| 342 |
+
|
| 343 |
+
@property
|
| 344 |
+
def in_usersite(self) -> bool:
|
| 345 |
+
if self.installed_location is None or user_site is None:
|
| 346 |
+
return False
|
| 347 |
+
return self.installed_location.startswith(normalize_path(user_site))
|
| 348 |
+
|
| 349 |
+
@property
|
| 350 |
+
def in_site_packages(self) -> bool:
|
| 351 |
+
if self.installed_location is None or site_packages is None:
|
| 352 |
+
return False
|
| 353 |
+
return self.installed_location.startswith(normalize_path(site_packages))
|
| 354 |
+
|
| 355 |
+
def is_file(self, path: InfoPath) -> bool:
|
| 356 |
+
"""Check whether an entry in the info directory is a file."""
|
| 357 |
+
raise NotImplementedError()
|
| 358 |
+
|
| 359 |
+
def iter_distutils_script_names(self) -> Iterator[str]:
|
| 360 |
+
"""Find distutils 'scripts' entries metadata.
|
| 361 |
+
|
| 362 |
+
If 'scripts' is supplied in ``setup.py``, distutils records those in the
|
| 363 |
+
installed distribution's ``scripts`` directory, a file for each script.
|
| 364 |
+
"""
|
| 365 |
+
raise NotImplementedError()
|
| 366 |
+
|
| 367 |
+
def read_text(self, path: InfoPath) -> str:
|
| 368 |
+
"""Read a file in the info directory.
|
| 369 |
+
|
| 370 |
+
:raise FileNotFoundError: If ``path`` does not exist in the directory.
|
| 371 |
+
:raise NoneMetadataError: If ``path`` exists in the info directory, but
|
| 372 |
+
cannot be read.
|
| 373 |
+
"""
|
| 374 |
+
raise NotImplementedError()
|
| 375 |
+
|
| 376 |
+
def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
|
| 377 |
+
raise NotImplementedError()
|
| 378 |
+
|
| 379 |
+
def _metadata_impl(self) -> email.message.Message:
|
| 380 |
+
raise NotImplementedError()
|
| 381 |
+
|
| 382 |
+
@functools.cached_property
|
| 383 |
+
def metadata(self) -> email.message.Message:
|
| 384 |
+
"""Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
|
| 385 |
+
|
| 386 |
+
This should return an empty message if the metadata file is unavailable.
|
| 387 |
+
|
| 388 |
+
:raises NoneMetadataError: If the metadata file is available, but does
|
| 389 |
+
not contain valid metadata.
|
| 390 |
+
"""
|
| 391 |
+
metadata = self._metadata_impl()
|
| 392 |
+
self._add_egg_info_requires(metadata)
|
| 393 |
+
return metadata
|
| 394 |
+
|
| 395 |
+
@property
|
| 396 |
+
def metadata_dict(self) -> dict[str, Any]:
|
| 397 |
+
"""PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO.
|
| 398 |
+
|
| 399 |
+
This should return an empty dict if the metadata file is unavailable.
|
| 400 |
+
|
| 401 |
+
:raises NoneMetadataError: If the metadata file is available, but does
|
| 402 |
+
not contain valid metadata.
|
| 403 |
+
"""
|
| 404 |
+
return msg_to_json(self.metadata)
|
| 405 |
+
|
| 406 |
+
@property
|
| 407 |
+
def metadata_version(self) -> str | None:
|
| 408 |
+
"""Value of "Metadata-Version:" in distribution metadata, if available."""
|
| 409 |
+
return self.metadata.get("Metadata-Version")
|
| 410 |
+
|
| 411 |
+
@property
|
| 412 |
+
def raw_name(self) -> str:
|
| 413 |
+
"""Value of "Name:" in distribution metadata."""
|
| 414 |
+
# The metadata should NEVER be missing the Name: key, but if it somehow
|
| 415 |
+
# does, fall back to the known canonical name.
|
| 416 |
+
return self.metadata.get("Name", self.canonical_name)
|
| 417 |
+
|
| 418 |
+
@property
|
| 419 |
+
def requires_python(self) -> SpecifierSet:
|
| 420 |
+
"""Value of "Requires-Python:" in distribution metadata.
|
| 421 |
+
|
| 422 |
+
If the key does not exist or contains an invalid value, an empty
|
| 423 |
+
SpecifierSet should be returned.
|
| 424 |
+
"""
|
| 425 |
+
value = self.metadata.get("Requires-Python")
|
| 426 |
+
if value is None:
|
| 427 |
+
return SpecifierSet()
|
| 428 |
+
try:
|
| 429 |
+
# Convert to str to satisfy the type checker; this can be a Header object.
|
| 430 |
+
spec = SpecifierSet(str(value))
|
| 431 |
+
except InvalidSpecifier as e:
|
| 432 |
+
message = "Package %r has an invalid Requires-Python: %s"
|
| 433 |
+
logger.warning(message, self.raw_name, e)
|
| 434 |
+
return SpecifierSet()
|
| 435 |
+
return spec
|
| 436 |
+
|
| 437 |
+
def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
|
| 438 |
+
"""Dependencies of this distribution.
|
| 439 |
+
|
| 440 |
+
For modern .dist-info distributions, this is the collection of
|
| 441 |
+
"Requires-Dist:" entries in distribution metadata.
|
| 442 |
+
"""
|
| 443 |
+
raise NotImplementedError()
|
| 444 |
+
|
| 445 |
+
def iter_raw_dependencies(self) -> Iterable[str]:
|
| 446 |
+
"""Raw Requires-Dist metadata."""
|
| 447 |
+
return self.metadata.get_all("Requires-Dist", [])
|
| 448 |
+
|
| 449 |
+
def iter_provided_extras(self) -> Iterable[NormalizedName]:
|
| 450 |
+
"""Extras provided by this distribution.
|
| 451 |
+
|
| 452 |
+
For modern .dist-info distributions, this is the collection of
|
| 453 |
+
"Provides-Extra:" entries in distribution metadata.
|
| 454 |
+
|
| 455 |
+
The return value of this function is expected to be normalised names,
|
| 456 |
+
per PEP 685, with the returned value being handled appropriately by
|
| 457 |
+
`iter_dependencies`.
|
| 458 |
+
"""
|
| 459 |
+
raise NotImplementedError()
|
| 460 |
+
|
| 461 |
+
def _iter_declared_entries_from_record(self) -> Iterator[str] | None:
|
| 462 |
+
try:
|
| 463 |
+
text = self.read_text("RECORD")
|
| 464 |
+
except FileNotFoundError:
|
| 465 |
+
return None
|
| 466 |
+
# This extra Path-str cast normalizes entries.
|
| 467 |
+
return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
|
| 468 |
+
|
| 469 |
+
def _iter_declared_entries_from_legacy(self) -> Iterator[str] | None:
|
| 470 |
+
try:
|
| 471 |
+
text = self.read_text("installed-files.txt")
|
| 472 |
+
except FileNotFoundError:
|
| 473 |
+
return None
|
| 474 |
+
paths = (p for p in text.splitlines(keepends=False) if p)
|
| 475 |
+
root = self.location
|
| 476 |
+
info = self.info_location
|
| 477 |
+
if root is None or info is None:
|
| 478 |
+
return paths
|
| 479 |
+
try:
|
| 480 |
+
info_rel = pathlib.Path(info).relative_to(root)
|
| 481 |
+
except ValueError: # info is not relative to root.
|
| 482 |
+
return paths
|
| 483 |
+
if not info_rel.parts: # info *is* root.
|
| 484 |
+
return paths
|
| 485 |
+
return (
|
| 486 |
+
_convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
|
| 487 |
+
for p in paths
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
def iter_declared_entries(self) -> Iterator[str] | None:
|
| 491 |
+
"""Iterate through file entries declared in this distribution.
|
| 492 |
+
|
| 493 |
+
For modern .dist-info distributions, this is the files listed in the
|
| 494 |
+
``RECORD`` metadata file. For legacy setuptools distributions, this
|
| 495 |
+
comes from ``installed-files.txt``, with entries normalized to be
|
| 496 |
+
compatible with the format used by ``RECORD``.
|
| 497 |
+
|
| 498 |
+
:return: An iterator for listed entries, or None if the distribution
|
| 499 |
+
contains neither ``RECORD`` nor ``installed-files.txt``.
|
| 500 |
+
"""
|
| 501 |
+
return (
|
| 502 |
+
self._iter_declared_entries_from_record()
|
| 503 |
+
or self._iter_declared_entries_from_legacy()
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]:
|
| 507 |
+
"""Parse a ``requires.txt`` in an egg-info directory.
|
| 508 |
+
|
| 509 |
+
This is an INI-ish format where an egg-info stores dependencies. A
|
| 510 |
+
section name describes extra other environment markers, while each entry
|
| 511 |
+
is an arbitrary string (not a key-value pair) representing a dependency
|
| 512 |
+
as a requirement string (no markers).
|
| 513 |
+
|
| 514 |
+
There is a construct in ``importlib.metadata`` called ``Sectioned`` that
|
| 515 |
+
does mostly the same, but the format is currently considered private.
|
| 516 |
+
"""
|
| 517 |
+
try:
|
| 518 |
+
content = self.read_text("requires.txt")
|
| 519 |
+
except FileNotFoundError:
|
| 520 |
+
return
|
| 521 |
+
extra = marker = "" # Section-less entries don't have markers.
|
| 522 |
+
for line in content.splitlines():
|
| 523 |
+
line = line.strip()
|
| 524 |
+
if not line or line.startswith("#"): # Comment; ignored.
|
| 525 |
+
continue
|
| 526 |
+
if line.startswith("[") and line.endswith("]"): # A section header.
|
| 527 |
+
extra, _, marker = line.strip("[]").partition(":")
|
| 528 |
+
continue
|
| 529 |
+
yield RequiresEntry(requirement=line, extra=extra, marker=marker)
|
| 530 |
+
|
| 531 |
+
def _iter_egg_info_extras(self) -> Iterable[str]:
|
| 532 |
+
"""Get extras from the egg-info directory."""
|
| 533 |
+
known_extras = {""}
|
| 534 |
+
for entry in self._iter_requires_txt_entries():
|
| 535 |
+
extra = canonicalize_name(entry.extra)
|
| 536 |
+
if extra in known_extras:
|
| 537 |
+
continue
|
| 538 |
+
known_extras.add(extra)
|
| 539 |
+
yield extra
|
| 540 |
+
|
| 541 |
+
def _iter_egg_info_dependencies(self) -> Iterable[str]:
|
| 542 |
+
"""Get distribution dependencies from the egg-info directory.
|
| 543 |
+
|
| 544 |
+
To ease parsing, this converts a legacy dependency entry into a PEP 508
|
| 545 |
+
requirement string. Like ``_iter_requires_txt_entries()``, there is code
|
| 546 |
+
in ``importlib.metadata`` that does mostly the same, but not do exactly
|
| 547 |
+
what we need.
|
| 548 |
+
|
| 549 |
+
Namely, ``importlib.metadata`` does not normalize the extra name before
|
| 550 |
+
putting it into the requirement string, which causes marker comparison
|
| 551 |
+
to fail because the dist-info format do normalize. This is consistent in
|
| 552 |
+
all currently available PEP 517 backends, although not standardized.
|
| 553 |
+
"""
|
| 554 |
+
for entry in self._iter_requires_txt_entries():
|
| 555 |
+
extra = canonicalize_name(entry.extra)
|
| 556 |
+
if extra and entry.marker:
|
| 557 |
+
marker = f'({entry.marker}) and extra == "{extra}"'
|
| 558 |
+
elif extra:
|
| 559 |
+
marker = f'extra == "{extra}"'
|
| 560 |
+
elif entry.marker:
|
| 561 |
+
marker = entry.marker
|
| 562 |
+
else:
|
| 563 |
+
marker = ""
|
| 564 |
+
if marker:
|
| 565 |
+
yield f"{entry.requirement} ; {marker}"
|
| 566 |
+
else:
|
| 567 |
+
yield entry.requirement
|
| 568 |
+
|
| 569 |
+
def _add_egg_info_requires(self, metadata: email.message.Message) -> None:
|
| 570 |
+
"""Add egg-info requires.txt information to the metadata."""
|
| 571 |
+
if not metadata.get_all("Requires-Dist"):
|
| 572 |
+
for dep in self._iter_egg_info_dependencies():
|
| 573 |
+
metadata["Requires-Dist"] = dep
|
| 574 |
+
if not metadata.get_all("Provides-Extra"):
|
| 575 |
+
for extra in self._iter_egg_info_extras():
|
| 576 |
+
metadata["Provides-Extra"] = extra
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
class BaseEnvironment:
|
| 580 |
+
"""An environment containing distributions to introspect."""
|
| 581 |
+
|
| 582 |
+
@classmethod
|
| 583 |
+
def default(cls) -> BaseEnvironment:
|
| 584 |
+
raise NotImplementedError()
|
| 585 |
+
|
| 586 |
+
@classmethod
|
| 587 |
+
def from_paths(cls, paths: list[str] | None) -> BaseEnvironment:
|
| 588 |
+
raise NotImplementedError()
|
| 589 |
+
|
| 590 |
+
def get_distribution(self, name: str) -> BaseDistribution | None:
|
| 591 |
+
"""Given a requirement name, return the installed distributions.
|
| 592 |
+
|
| 593 |
+
The name may not be normalized. The implementation must canonicalize
|
| 594 |
+
it for lookup.
|
| 595 |
+
"""
|
| 596 |
+
raise NotImplementedError()
|
| 597 |
+
|
| 598 |
+
def _iter_distributions(self) -> Iterator[BaseDistribution]:
|
| 599 |
+
"""Iterate through installed distributions.
|
| 600 |
+
|
| 601 |
+
This function should be implemented by subclass, but never called
|
| 602 |
+
directly. Use the public ``iter_distribution()`` instead, which
|
| 603 |
+
implements additional logic to make sure the distributions are valid.
|
| 604 |
+
"""
|
| 605 |
+
raise NotImplementedError()
|
| 606 |
+
|
| 607 |
+
def iter_all_distributions(self) -> Iterator[BaseDistribution]:
|
| 608 |
+
"""Iterate through all installed distributions without any filtering."""
|
| 609 |
+
for dist in self._iter_distributions():
|
| 610 |
+
# Make sure the distribution actually comes from a valid Python
|
| 611 |
+
# packaging distribution. Pip's AdjacentTempDirectory leaves folders
|
| 612 |
+
# e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
|
| 613 |
+
# valid project name pattern is taken from PEP 508.
|
| 614 |
+
project_name_valid = re.match(
|
| 615 |
+
r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
|
| 616 |
+
dist.canonical_name,
|
| 617 |
+
flags=re.IGNORECASE,
|
| 618 |
+
)
|
| 619 |
+
if not project_name_valid:
|
| 620 |
+
logger.warning(
|
| 621 |
+
"Ignoring invalid distribution %s (%s)",
|
| 622 |
+
dist.canonical_name,
|
| 623 |
+
dist.location,
|
| 624 |
+
)
|
| 625 |
+
continue
|
| 626 |
+
yield dist
|
| 627 |
+
|
| 628 |
+
def iter_installed_distributions(
|
| 629 |
+
self,
|
| 630 |
+
local_only: bool = True,
|
| 631 |
+
skip: Container[str] = stdlib_pkgs,
|
| 632 |
+
include_editables: bool = True,
|
| 633 |
+
editables_only: bool = False,
|
| 634 |
+
user_only: bool = False,
|
| 635 |
+
) -> Iterator[BaseDistribution]:
|
| 636 |
+
"""Return a list of installed distributions.
|
| 637 |
+
|
| 638 |
+
This is based on ``iter_all_distributions()`` with additional filtering
|
| 639 |
+
options. Note that ``iter_installed_distributions()`` without arguments
|
| 640 |
+
is *not* equal to ``iter_all_distributions()``, since some of the
|
| 641 |
+
configurations exclude packages by default.
|
| 642 |
+
|
| 643 |
+
:param local_only: If True (default), only return installations
|
| 644 |
+
local to the current virtualenv, if in a virtualenv.
|
| 645 |
+
:param skip: An iterable of canonicalized project names to ignore;
|
| 646 |
+
defaults to ``stdlib_pkgs``.
|
| 647 |
+
:param include_editables: If False, don't report editables.
|
| 648 |
+
:param editables_only: If True, only report editables.
|
| 649 |
+
:param user_only: If True, only report installations in the user
|
| 650 |
+
site directory.
|
| 651 |
+
"""
|
| 652 |
+
it = self.iter_all_distributions()
|
| 653 |
+
if local_only:
|
| 654 |
+
it = (d for d in it if d.local)
|
| 655 |
+
if not include_editables:
|
| 656 |
+
it = (d for d in it if not d.editable)
|
| 657 |
+
if editables_only:
|
| 658 |
+
it = (d for d in it if d.editable)
|
| 659 |
+
if user_only:
|
| 660 |
+
it = (d for d in it if d.in_usersite)
|
| 661 |
+
return (d for d in it if d.canonical_name not in skip)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class Wheel(Protocol):
|
| 665 |
+
location: str
|
| 666 |
+
|
| 667 |
+
def as_zipfile(self) -> zipfile.ZipFile:
|
| 668 |
+
raise NotImplementedError()
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
class FilesystemWheel(Wheel):
|
| 672 |
+
def __init__(self, location: str) -> None:
|
| 673 |
+
self.location = location
|
| 674 |
+
|
| 675 |
+
def as_zipfile(self) -> zipfile.ZipFile:
|
| 676 |
+
return zipfile.ZipFile(self.location, allowZip64=True)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
class MemoryWheel(Wheel):
|
| 680 |
+
def __init__(self, location: str, stream: IO[bytes]) -> None:
|
| 681 |
+
self.location = location
|
| 682 |
+
self.stream = stream
|
| 683 |
+
|
| 684 |
+
def as_zipfile(self) -> zipfile.ZipFile:
|
| 685 |
+
return zipfile.ZipFile(self.stream, allowZip64=True)
|
.venv/lib/python3.12/site-packages/pip/_internal/models/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""A package that contains models that represent entities."""
|
.venv/lib/python3.12/site-packages/pip/_internal/models/direct_url.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PEP 610"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
import urllib.parse
|
| 8 |
+
from collections.abc import Iterable
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Any, ClassVar, TypeVar, Union
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"DirectUrl",
|
| 14 |
+
"DirectUrlValidationError",
|
| 15 |
+
"DirInfo",
|
| 16 |
+
"ArchiveInfo",
|
| 17 |
+
"VcsInfo",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
T = TypeVar("T")
|
| 21 |
+
|
| 22 |
+
DIRECT_URL_METADATA_NAME = "direct_url.json"
|
| 23 |
+
ENV_VAR_RE = re.compile(r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DirectUrlValidationError(Exception):
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _get(
|
| 31 |
+
d: dict[str, Any], expected_type: type[T], key: str, default: T | None = None
|
| 32 |
+
) -> T | None:
|
| 33 |
+
"""Get value from dictionary and verify expected type."""
|
| 34 |
+
if key not in d:
|
| 35 |
+
return default
|
| 36 |
+
value = d[key]
|
| 37 |
+
if not isinstance(value, expected_type):
|
| 38 |
+
raise DirectUrlValidationError(
|
| 39 |
+
f"{value!r} has unexpected type for {key} (expected {expected_type})"
|
| 40 |
+
)
|
| 41 |
+
return value
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _get_required(
|
| 45 |
+
d: dict[str, Any], expected_type: type[T], key: str, default: T | None = None
|
| 46 |
+
) -> T:
|
| 47 |
+
value = _get(d, expected_type, key, default)
|
| 48 |
+
if value is None:
|
| 49 |
+
raise DirectUrlValidationError(f"{key} must have a value")
|
| 50 |
+
return value
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _exactly_one_of(infos: Iterable[InfoType | None]) -> InfoType:
|
| 54 |
+
infos = [info for info in infos if info is not None]
|
| 55 |
+
if not infos:
|
| 56 |
+
raise DirectUrlValidationError(
|
| 57 |
+
"missing one of archive_info, dir_info, vcs_info"
|
| 58 |
+
)
|
| 59 |
+
if len(infos) > 1:
|
| 60 |
+
raise DirectUrlValidationError(
|
| 61 |
+
"more than one of archive_info, dir_info, vcs_info"
|
| 62 |
+
)
|
| 63 |
+
assert infos[0] is not None
|
| 64 |
+
return infos[0]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _filter_none(**kwargs: Any) -> dict[str, Any]:
|
| 68 |
+
"""Make dict excluding None values."""
|
| 69 |
+
return {k: v for k, v in kwargs.items() if v is not None}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class VcsInfo:
|
| 74 |
+
name: ClassVar = "vcs_info"
|
| 75 |
+
|
| 76 |
+
vcs: str
|
| 77 |
+
commit_id: str
|
| 78 |
+
requested_revision: str | None = None
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def _from_dict(cls, d: dict[str, Any] | None) -> VcsInfo | None:
|
| 82 |
+
if d is None:
|
| 83 |
+
return None
|
| 84 |
+
return cls(
|
| 85 |
+
vcs=_get_required(d, str, "vcs"),
|
| 86 |
+
commit_id=_get_required(d, str, "commit_id"),
|
| 87 |
+
requested_revision=_get(d, str, "requested_revision"),
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def _to_dict(self) -> dict[str, Any]:
|
| 91 |
+
return _filter_none(
|
| 92 |
+
vcs=self.vcs,
|
| 93 |
+
requested_revision=self.requested_revision,
|
| 94 |
+
commit_id=self.commit_id,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ArchiveInfo:
|
| 99 |
+
name = "archive_info"
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
hash: str | None = None,
|
| 104 |
+
hashes: dict[str, str] | None = None,
|
| 105 |
+
) -> None:
|
| 106 |
+
# set hashes before hash, since the hash setter will further populate hashes
|
| 107 |
+
self.hashes = hashes
|
| 108 |
+
self.hash = hash
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def hash(self) -> str | None:
|
| 112 |
+
return self._hash
|
| 113 |
+
|
| 114 |
+
@hash.setter
|
| 115 |
+
def hash(self, value: str | None) -> None:
|
| 116 |
+
if value is not None:
|
| 117 |
+
# Auto-populate the hashes key to upgrade to the new format automatically.
|
| 118 |
+
# We don't back-populate the legacy hash key from hashes.
|
| 119 |
+
try:
|
| 120 |
+
hash_name, hash_value = value.split("=", 1)
|
| 121 |
+
except ValueError:
|
| 122 |
+
raise DirectUrlValidationError(
|
| 123 |
+
f"invalid archive_info.hash format: {value!r}"
|
| 124 |
+
)
|
| 125 |
+
if self.hashes is None:
|
| 126 |
+
self.hashes = {hash_name: hash_value}
|
| 127 |
+
elif hash_name not in self.hashes:
|
| 128 |
+
self.hashes = self.hashes.copy()
|
| 129 |
+
self.hashes[hash_name] = hash_value
|
| 130 |
+
self._hash = value
|
| 131 |
+
|
| 132 |
+
@classmethod
|
| 133 |
+
def _from_dict(cls, d: dict[str, Any] | None) -> ArchiveInfo | None:
|
| 134 |
+
if d is None:
|
| 135 |
+
return None
|
| 136 |
+
return cls(hash=_get(d, str, "hash"), hashes=_get(d, dict, "hashes"))
|
| 137 |
+
|
| 138 |
+
def _to_dict(self) -> dict[str, Any]:
|
| 139 |
+
return _filter_none(hash=self.hash, hashes=self.hashes)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@dataclass
|
| 143 |
+
class DirInfo:
|
| 144 |
+
name: ClassVar = "dir_info"
|
| 145 |
+
|
| 146 |
+
editable: bool = False
|
| 147 |
+
|
| 148 |
+
@classmethod
|
| 149 |
+
def _from_dict(cls, d: dict[str, Any] | None) -> DirInfo | None:
|
| 150 |
+
if d is None:
|
| 151 |
+
return None
|
| 152 |
+
return cls(editable=_get_required(d, bool, "editable", default=False))
|
| 153 |
+
|
| 154 |
+
def _to_dict(self) -> dict[str, Any]:
|
| 155 |
+
return _filter_none(editable=self.editable or None)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
InfoType = Union[ArchiveInfo, DirInfo, VcsInfo]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@dataclass
|
| 162 |
+
class DirectUrl:
|
| 163 |
+
url: str
|
| 164 |
+
info: InfoType
|
| 165 |
+
subdirectory: str | None = None
|
| 166 |
+
|
| 167 |
+
def _remove_auth_from_netloc(self, netloc: str) -> str:
|
| 168 |
+
if "@" not in netloc:
|
| 169 |
+
return netloc
|
| 170 |
+
user_pass, netloc_no_user_pass = netloc.split("@", 1)
|
| 171 |
+
if (
|
| 172 |
+
isinstance(self.info, VcsInfo)
|
| 173 |
+
and self.info.vcs == "git"
|
| 174 |
+
and user_pass == "git"
|
| 175 |
+
):
|
| 176 |
+
return netloc
|
| 177 |
+
if ENV_VAR_RE.match(user_pass):
|
| 178 |
+
return netloc
|
| 179 |
+
return netloc_no_user_pass
|
| 180 |
+
|
| 181 |
+
@property
|
| 182 |
+
def redacted_url(self) -> str:
|
| 183 |
+
"""url with user:password part removed unless it is formed with
|
| 184 |
+
environment variables as specified in PEP 610, or it is ``git``
|
| 185 |
+
in the case of a git URL.
|
| 186 |
+
"""
|
| 187 |
+
purl = urllib.parse.urlsplit(self.url)
|
| 188 |
+
netloc = self._remove_auth_from_netloc(purl.netloc)
|
| 189 |
+
surl = urllib.parse.urlunsplit(
|
| 190 |
+
(purl.scheme, netloc, purl.path, purl.query, purl.fragment)
|
| 191 |
+
)
|
| 192 |
+
return surl
|
| 193 |
+
|
| 194 |
+
def validate(self) -> None:
|
| 195 |
+
self.from_dict(self.to_dict())
|
| 196 |
+
|
| 197 |
+
@classmethod
|
| 198 |
+
def from_dict(cls, d: dict[str, Any]) -> DirectUrl:
|
| 199 |
+
return DirectUrl(
|
| 200 |
+
url=_get_required(d, str, "url"),
|
| 201 |
+
subdirectory=_get(d, str, "subdirectory"),
|
| 202 |
+
info=_exactly_one_of(
|
| 203 |
+
[
|
| 204 |
+
ArchiveInfo._from_dict(_get(d, dict, "archive_info")),
|
| 205 |
+
DirInfo._from_dict(_get(d, dict, "dir_info")),
|
| 206 |
+
VcsInfo._from_dict(_get(d, dict, "vcs_info")),
|
| 207 |
+
]
|
| 208 |
+
),
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def to_dict(self) -> dict[str, Any]:
|
| 212 |
+
res = _filter_none(
|
| 213 |
+
url=self.redacted_url,
|
| 214 |
+
subdirectory=self.subdirectory,
|
| 215 |
+
)
|
| 216 |
+
res[self.info.name] = self.info._to_dict()
|
| 217 |
+
return res
|
| 218 |
+
|
| 219 |
+
@classmethod
|
| 220 |
+
def from_json(cls, s: str) -> DirectUrl:
|
| 221 |
+
return cls.from_dict(json.loads(s))
|
| 222 |
+
|
| 223 |
+
def to_json(self) -> str:
|
| 224 |
+
return json.dumps(self.to_dict(), sort_keys=True)
|
| 225 |
+
|
| 226 |
+
def is_local_editable(self) -> bool:
|
| 227 |
+
return isinstance(self.info, DirInfo) and self.info.editable
|
.venv/lib/python3.12/site-packages/pip/_internal/models/index.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import urllib.parse
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class PackageIndex:
|
| 5 |
+
"""Represents a Package Index and provides easier access to endpoints"""
|
| 6 |
+
|
| 7 |
+
__slots__ = ["url", "netloc", "simple_url", "pypi_url", "file_storage_domain"]
|
| 8 |
+
|
| 9 |
+
def __init__(self, url: str, file_storage_domain: str) -> None:
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.url = url
|
| 12 |
+
self.netloc = urllib.parse.urlsplit(url).netloc
|
| 13 |
+
self.simple_url = self._url_for_path("simple")
|
| 14 |
+
self.pypi_url = self._url_for_path("pypi")
|
| 15 |
+
|
| 16 |
+
# This is part of a temporary hack used to block installs of PyPI
|
| 17 |
+
# packages which depend on external urls only necessary until PyPI can
|
| 18 |
+
# block such packages themselves
|
| 19 |
+
self.file_storage_domain = file_storage_domain
|
| 20 |
+
|
| 21 |
+
def _url_for_path(self, path: str) -> str:
|
| 22 |
+
return urllib.parse.urljoin(self.url, path)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
PyPI = PackageIndex("https://pypi.org/", file_storage_domain="files.pythonhosted.org")
|
| 26 |
+
TestPyPI = PackageIndex(
|
| 27 |
+
"https://test.pypi.org/", file_storage_domain="test-files.pythonhosted.org"
|
| 28 |
+
)
|
.venv/lib/python3.12/site-packages/pip/_internal/models/installation_report.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from pip._vendor.packaging.markers import default_environment
|
| 5 |
+
|
| 6 |
+
from pip import __version__
|
| 7 |
+
from pip._internal.req.req_install import InstallRequirement
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class InstallationReport:
|
| 11 |
+
def __init__(self, install_requirements: Sequence[InstallRequirement]):
|
| 12 |
+
self._install_requirements = install_requirements
|
| 13 |
+
|
| 14 |
+
@classmethod
|
| 15 |
+
def _install_req_to_dict(cls, ireq: InstallRequirement) -> dict[str, Any]:
|
| 16 |
+
assert ireq.download_info, f"No download_info for {ireq}"
|
| 17 |
+
res = {
|
| 18 |
+
# PEP 610 json for the download URL. download_info.archive_info.hashes may
|
| 19 |
+
# be absent when the requirement was installed from the wheel cache
|
| 20 |
+
# and the cache entry was populated by an older pip version that did not
|
| 21 |
+
# record origin.json.
|
| 22 |
+
"download_info": ireq.download_info.to_dict(),
|
| 23 |
+
# is_direct is true if the requirement was a direct URL reference (which
|
| 24 |
+
# includes editable requirements), and false if the requirement was
|
| 25 |
+
# downloaded from a PEP 503 index or --find-links.
|
| 26 |
+
"is_direct": ireq.is_direct,
|
| 27 |
+
# is_yanked is true if the requirement was yanked from the index, but
|
| 28 |
+
# was still selected by pip to conform to PEP 592.
|
| 29 |
+
"is_yanked": ireq.link.is_yanked if ireq.link else False,
|
| 30 |
+
# requested is true if the requirement was specified by the user (aka
|
| 31 |
+
# top level requirement), and false if it was installed as a dependency of a
|
| 32 |
+
# requirement. https://peps.python.org/pep-0376/#requested
|
| 33 |
+
"requested": ireq.user_supplied,
|
| 34 |
+
# PEP 566 json encoding for metadata
|
| 35 |
+
# https://www.python.org/dev/peps/pep-0566/#json-compatible-metadata
|
| 36 |
+
"metadata": ireq.get_dist().metadata_dict,
|
| 37 |
+
}
|
| 38 |
+
if ireq.user_supplied and ireq.extras:
|
| 39 |
+
# For top level requirements, the list of requested extras, if any.
|
| 40 |
+
res["requested_extras"] = sorted(ireq.extras)
|
| 41 |
+
return res
|
| 42 |
+
|
| 43 |
+
def to_dict(self) -> dict[str, Any]:
|
| 44 |
+
return {
|
| 45 |
+
"version": "1",
|
| 46 |
+
"pip_version": __version__,
|
| 47 |
+
"install": [
|
| 48 |
+
self._install_req_to_dict(ireq) for ireq in self._install_requirements
|
| 49 |
+
],
|
| 50 |
+
# https://peps.python.org/pep-0508/#environment-markers
|
| 51 |
+
# TODO: currently, the resolver uses the default environment to evaluate
|
| 52 |
+
# environment markers, so that is what we report here. In the future, it
|
| 53 |
+
# should also take into account options such as --python-version or
|
| 54 |
+
# --platform, perhaps under the form of an environment_override field?
|
| 55 |
+
# https://github.com/pypa/pip/issues/11198
|
| 56 |
+
"environment": default_environment(),
|
| 57 |
+
}
|
.venv/lib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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import functools
|
| 5 |
+
import itertools
|
| 6 |
+
import logging
|
| 7 |
+
import os
|
| 8 |
+
import posixpath
|
| 9 |
+
import re
|
| 10 |
+
import urllib.parse
|
| 11 |
+
import urllib.request
|
| 12 |
+
from collections.abc import Mapping
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from typing import (
|
| 15 |
+
Any,
|
| 16 |
+
NamedTuple,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
from pip._internal.exceptions import InvalidEggFragment
|
| 20 |
+
from pip._internal.utils.datetime import parse_iso_datetime
|
| 21 |
+
from pip._internal.utils.filetypes import WHEEL_EXTENSION
|
| 22 |
+
from pip._internal.utils.hashes import Hashes
|
| 23 |
+
from pip._internal.utils.misc import (
|
| 24 |
+
pairwise,
|
| 25 |
+
redact_auth_from_url,
|
| 26 |
+
split_auth_from_netloc,
|
| 27 |
+
splitext,
|
| 28 |
+
)
|
| 29 |
+
from pip._internal.utils.urls import path_to_url, url_to_path
|
| 30 |
+
|
| 31 |
+
logger = logging.getLogger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Order matters, earlier hashes have a precedence over later hashes for what
|
| 35 |
+
# we will pick to use.
|
| 36 |
+
_SUPPORTED_HASHES = ("sha512", "sha384", "sha256", "sha224", "sha1", "md5")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass(frozen=True)
|
| 40 |
+
class LinkHash:
|
| 41 |
+
"""Links to content may have embedded hash values. This class parses those.
|
| 42 |
+
|
| 43 |
+
`name` must be any member of `_SUPPORTED_HASHES`.
|
| 44 |
+
|
| 45 |
+
This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to
|
| 46 |
+
be JSON-serializable to conform to PEP 610, this class contains the logic for
|
| 47 |
+
parsing a hash name and value for correctness, and then checking whether that hash
|
| 48 |
+
conforms to a schema with `.is_hash_allowed()`."""
|
| 49 |
+
|
| 50 |
+
name: str
|
| 51 |
+
value: str
|
| 52 |
+
|
| 53 |
+
_hash_url_fragment_re = re.compile(
|
| 54 |
+
# NB: we do not validate that the second group (.*) is a valid hex
|
| 55 |
+
# digest. Instead, we simply keep that string in this class, and then check it
|
| 56 |
+
# against Hashes when hash-checking is needed. This is easier to debug than
|
| 57 |
+
# proactively discarding an invalid hex digest, as we handle incorrect hashes
|
| 58 |
+
# and malformed hashes in the same place.
|
| 59 |
+
r"[#&]({choices})=([^&]*)".format(
|
| 60 |
+
choices="|".join(re.escape(hash_name) for hash_name in _SUPPORTED_HASHES)
|
| 61 |
+
),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def __post_init__(self) -> None:
|
| 65 |
+
assert self.name in _SUPPORTED_HASHES
|
| 66 |
+
|
| 67 |
+
@classmethod
|
| 68 |
+
@functools.cache
|
| 69 |
+
def find_hash_url_fragment(cls, url: str) -> LinkHash | None:
|
| 70 |
+
"""Search a string for a checksum algorithm name and encoded output value."""
|
| 71 |
+
match = cls._hash_url_fragment_re.search(url)
|
| 72 |
+
if match is None:
|
| 73 |
+
return None
|
| 74 |
+
name, value = match.groups()
|
| 75 |
+
return cls(name=name, value=value)
|
| 76 |
+
|
| 77 |
+
def as_dict(self) -> dict[str, str]:
|
| 78 |
+
return {self.name: self.value}
|
| 79 |
+
|
| 80 |
+
def as_hashes(self) -> Hashes:
|
| 81 |
+
"""Return a Hashes instance which checks only for the current hash."""
|
| 82 |
+
return Hashes({self.name: [self.value]})
|
| 83 |
+
|
| 84 |
+
def is_hash_allowed(self, hashes: Hashes | None) -> bool:
|
| 85 |
+
"""
|
| 86 |
+
Return True if the current hash is allowed by `hashes`.
|
| 87 |
+
"""
|
| 88 |
+
if hashes is None:
|
| 89 |
+
return False
|
| 90 |
+
return hashes.is_hash_allowed(self.name, hex_digest=self.value)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@dataclass(frozen=True)
|
| 94 |
+
class MetadataFile:
|
| 95 |
+
"""Information about a core metadata file associated with a distribution."""
|
| 96 |
+
|
| 97 |
+
hashes: dict[str, str] | None
|
| 98 |
+
|
| 99 |
+
def __post_init__(self) -> None:
|
| 100 |
+
if self.hashes is not None:
|
| 101 |
+
assert all(name in _SUPPORTED_HASHES for name in self.hashes)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def supported_hashes(hashes: dict[str, str] | None) -> dict[str, str] | None:
|
| 105 |
+
# Remove any unsupported hash types from the mapping. If this leaves no
|
| 106 |
+
# supported hashes, return None
|
| 107 |
+
if hashes is None:
|
| 108 |
+
return None
|
| 109 |
+
hashes = {n: v for n, v in hashes.items() if n in _SUPPORTED_HASHES}
|
| 110 |
+
if not hashes:
|
| 111 |
+
return None
|
| 112 |
+
return hashes
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _clean_url_path_part(part: str) -> str:
|
| 116 |
+
"""
|
| 117 |
+
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
|
| 118 |
+
"""
|
| 119 |
+
# We unquote prior to quoting to make sure nothing is double quoted.
|
| 120 |
+
return urllib.parse.quote(urllib.parse.unquote(part))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _clean_file_url_path(part: str) -> str:
|
| 124 |
+
"""
|
| 125 |
+
Clean the first part of a URL path that corresponds to a local
|
| 126 |
+
filesystem path (i.e. the first part after splitting on "@" characters).
|
| 127 |
+
"""
|
| 128 |
+
# We unquote prior to quoting to make sure nothing is double quoted.
|
| 129 |
+
# Also, on Windows the path part might contain a drive letter which
|
| 130 |
+
# should not be quoted. On Linux where drive letters do not
|
| 131 |
+
# exist, the colon should be quoted. We rely on urllib.request
|
| 132 |
+
# to do the right thing here.
|
| 133 |
+
ret = urllib.request.pathname2url(urllib.request.url2pathname(part))
|
| 134 |
+
if ret.startswith("///"):
|
| 135 |
+
# Remove any URL authority section, leaving only the URL path.
|
| 136 |
+
ret = ret.removeprefix("//")
|
| 137 |
+
return ret
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# percent-encoded: /
|
| 141 |
+
_reserved_chars_re = re.compile("(@|%2F)", re.IGNORECASE)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _clean_url_path(path: str, is_local_path: bool) -> str:
|
| 145 |
+
"""
|
| 146 |
+
Clean the path portion of a URL.
|
| 147 |
+
"""
|
| 148 |
+
if is_local_path:
|
| 149 |
+
clean_func = _clean_file_url_path
|
| 150 |
+
else:
|
| 151 |
+
clean_func = _clean_url_path_part
|
| 152 |
+
|
| 153 |
+
# Split on the reserved characters prior to cleaning so that
|
| 154 |
+
# revision strings in VCS URLs are properly preserved.
|
| 155 |
+
parts = _reserved_chars_re.split(path)
|
| 156 |
+
|
| 157 |
+
cleaned_parts = []
|
| 158 |
+
for to_clean, reserved in pairwise(itertools.chain(parts, [""])):
|
| 159 |
+
cleaned_parts.append(clean_func(to_clean))
|
| 160 |
+
# Normalize %xx escapes (e.g. %2f -> %2F)
|
| 161 |
+
cleaned_parts.append(reserved.upper())
|
| 162 |
+
|
| 163 |
+
return "".join(cleaned_parts)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _ensure_quoted_url(url: str) -> str:
|
| 167 |
+
"""
|
| 168 |
+
Make sure a link is fully quoted.
|
| 169 |
+
For example, if ' ' occurs in the URL, it will be replaced with "%20",
|
| 170 |
+
and without double-quoting other characters.
|
| 171 |
+
"""
|
| 172 |
+
# Split the URL into parts according to the general structure
|
| 173 |
+
# `scheme://netloc/path?query#fragment`.
|
| 174 |
+
result = urllib.parse.urlsplit(url)
|
| 175 |
+
# If the netloc is empty, then the URL refers to a local filesystem path.
|
| 176 |
+
is_local_path = not result.netloc
|
| 177 |
+
path = _clean_url_path(result.path, is_local_path=is_local_path)
|
| 178 |
+
# Temporarily replace scheme with file to ensure the URL generated by
|
| 179 |
+
# urlunsplit() contains an empty netloc (file://) as per RFC 1738.
|
| 180 |
+
ret = urllib.parse.urlunsplit(result._replace(scheme="file", path=path))
|
| 181 |
+
ret = result.scheme + ret[4:] # Restore original scheme.
|
| 182 |
+
return ret
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _absolute_link_url(base_url: str, url: str) -> str:
|
| 186 |
+
"""
|
| 187 |
+
A faster implementation of urllib.parse.urljoin with a shortcut
|
| 188 |
+
for absolute http/https URLs.
|
| 189 |
+
"""
|
| 190 |
+
if url.startswith(("https://", "http://")):
|
| 191 |
+
return url
|
| 192 |
+
else:
|
| 193 |
+
return urllib.parse.urljoin(base_url, url)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@functools.total_ordering
|
| 197 |
+
class Link:
|
| 198 |
+
"""Represents a parsed link from a Package Index's simple URL"""
|
| 199 |
+
|
| 200 |
+
__slots__ = [
|
| 201 |
+
"_parsed_url",
|
| 202 |
+
"_url",
|
| 203 |
+
"_path",
|
| 204 |
+
"_hashes",
|
| 205 |
+
"comes_from",
|
| 206 |
+
"requires_python",
|
| 207 |
+
"yanked_reason",
|
| 208 |
+
"metadata_file_data",
|
| 209 |
+
"upload_time",
|
| 210 |
+
"cache_link_parsing",
|
| 211 |
+
"egg_fragment",
|
| 212 |
+
]
|
| 213 |
+
|
| 214 |
+
def __init__(
|
| 215 |
+
self,
|
| 216 |
+
url: str,
|
| 217 |
+
comes_from: str | None = None,
|
| 218 |
+
requires_python: str | None = None,
|
| 219 |
+
yanked_reason: str | None = None,
|
| 220 |
+
metadata_file_data: MetadataFile | None = None,
|
| 221 |
+
upload_time: datetime.datetime | None = None,
|
| 222 |
+
cache_link_parsing: bool = True,
|
| 223 |
+
hashes: Mapping[str, str] | None = None,
|
| 224 |
+
) -> None:
|
| 225 |
+
"""
|
| 226 |
+
:param url: url of the resource pointed to (href of the link)
|
| 227 |
+
:param comes_from: URL or string indicating where the link was found.
|
| 228 |
+
:param requires_python: String containing the `Requires-Python`
|
| 229 |
+
metadata field, specified in PEP 345. This may be specified by
|
| 230 |
+
a data-requires-python attribute in the HTML link tag, as
|
| 231 |
+
described in PEP 503.
|
| 232 |
+
:param yanked_reason: the reason the file has been yanked, if the
|
| 233 |
+
file has been yanked, or None if the file hasn't been yanked.
|
| 234 |
+
This is the value of the "data-yanked" attribute, if present, in
|
| 235 |
+
a simple repository HTML link. If the file has been yanked but
|
| 236 |
+
no reason was provided, this should be the empty string. See
|
| 237 |
+
PEP 592 for more information and the specification.
|
| 238 |
+
:param metadata_file_data: the metadata attached to the file, or None if
|
| 239 |
+
no such metadata is provided. This argument, if not None, indicates
|
| 240 |
+
that a separate metadata file exists, and also optionally supplies
|
| 241 |
+
hashes for that file.
|
| 242 |
+
:param upload_time: upload time of the file, or None if the information
|
| 243 |
+
is not available from the server.
|
| 244 |
+
:param cache_link_parsing: A flag that is used elsewhere to determine
|
| 245 |
+
whether resources retrieved from this link should be cached. PyPI
|
| 246 |
+
URLs should generally have this set to False, for example.
|
| 247 |
+
:param hashes: A mapping of hash names to digests to allow us to
|
| 248 |
+
determine the validity of a download.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
# The comes_from, requires_python, and metadata_file_data arguments are
|
| 252 |
+
# only used by classmethods of this class, and are not used in client
|
| 253 |
+
# code directly.
|
| 254 |
+
|
| 255 |
+
# url can be a UNC windows share
|
| 256 |
+
if url.startswith("\\\\"):
|
| 257 |
+
url = path_to_url(url)
|
| 258 |
+
|
| 259 |
+
self._parsed_url = urllib.parse.urlsplit(url)
|
| 260 |
+
# Store the url as a private attribute to prevent accidentally
|
| 261 |
+
# trying to set a new value.
|
| 262 |
+
self._url = url
|
| 263 |
+
# The .path property is hot, so calculate its value ahead of time.
|
| 264 |
+
self._path = urllib.parse.unquote(self._parsed_url.path)
|
| 265 |
+
|
| 266 |
+
link_hash = LinkHash.find_hash_url_fragment(url)
|
| 267 |
+
hashes_from_link = {} if link_hash is None else link_hash.as_dict()
|
| 268 |
+
if hashes is None:
|
| 269 |
+
self._hashes = hashes_from_link
|
| 270 |
+
else:
|
| 271 |
+
self._hashes = {**hashes, **hashes_from_link}
|
| 272 |
+
|
| 273 |
+
self.comes_from = comes_from
|
| 274 |
+
self.requires_python = requires_python if requires_python else None
|
| 275 |
+
self.yanked_reason = yanked_reason
|
| 276 |
+
self.metadata_file_data = metadata_file_data
|
| 277 |
+
self.upload_time = upload_time
|
| 278 |
+
|
| 279 |
+
self.cache_link_parsing = cache_link_parsing
|
| 280 |
+
self.egg_fragment = self._egg_fragment()
|
| 281 |
+
|
| 282 |
+
@classmethod
|
| 283 |
+
def from_json(
|
| 284 |
+
cls,
|
| 285 |
+
file_data: dict[str, Any],
|
| 286 |
+
page_url: str,
|
| 287 |
+
) -> Link | None:
|
| 288 |
+
"""
|
| 289 |
+
Convert an pypi json document from a simple repository page into a Link.
|
| 290 |
+
"""
|
| 291 |
+
file_url = file_data.get("url")
|
| 292 |
+
if file_url is None:
|
| 293 |
+
return None
|
| 294 |
+
|
| 295 |
+
url = _ensure_quoted_url(_absolute_link_url(page_url, file_url))
|
| 296 |
+
pyrequire = file_data.get("requires-python")
|
| 297 |
+
yanked_reason = file_data.get("yanked")
|
| 298 |
+
hashes = file_data.get("hashes", {})
|
| 299 |
+
|
| 300 |
+
# PEP 714: Indexes must use the name core-metadata, but
|
| 301 |
+
# clients should support the old name as a fallback for compatibility.
|
| 302 |
+
metadata_info = file_data.get("core-metadata")
|
| 303 |
+
if metadata_info is None:
|
| 304 |
+
metadata_info = file_data.get("dist-info-metadata")
|
| 305 |
+
|
| 306 |
+
if upload_time_data := file_data.get("upload-time"):
|
| 307 |
+
upload_time = parse_iso_datetime(upload_time_data)
|
| 308 |
+
else:
|
| 309 |
+
upload_time = None
|
| 310 |
+
|
| 311 |
+
# The metadata info value may be a boolean, or a dict of hashes.
|
| 312 |
+
if isinstance(metadata_info, dict):
|
| 313 |
+
# The file exists, and hashes have been supplied
|
| 314 |
+
metadata_file_data = MetadataFile(supported_hashes(metadata_info))
|
| 315 |
+
elif metadata_info:
|
| 316 |
+
# The file exists, but there are no hashes
|
| 317 |
+
metadata_file_data = MetadataFile(None)
|
| 318 |
+
else:
|
| 319 |
+
# False or not present: the file does not exist
|
| 320 |
+
metadata_file_data = None
|
| 321 |
+
|
| 322 |
+
# The Link.yanked_reason expects an empty string instead of a boolean.
|
| 323 |
+
if yanked_reason and not isinstance(yanked_reason, str):
|
| 324 |
+
yanked_reason = ""
|
| 325 |
+
# The Link.yanked_reason expects None instead of False.
|
| 326 |
+
elif not yanked_reason:
|
| 327 |
+
yanked_reason = None
|
| 328 |
+
|
| 329 |
+
return cls(
|
| 330 |
+
url,
|
| 331 |
+
comes_from=page_url,
|
| 332 |
+
requires_python=pyrequire,
|
| 333 |
+
yanked_reason=yanked_reason,
|
| 334 |
+
hashes=hashes,
|
| 335 |
+
metadata_file_data=metadata_file_data,
|
| 336 |
+
upload_time=upload_time,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
@classmethod
|
| 340 |
+
def from_element(
|
| 341 |
+
cls,
|
| 342 |
+
anchor_attribs: dict[str, str | None],
|
| 343 |
+
page_url: str,
|
| 344 |
+
base_url: str,
|
| 345 |
+
) -> Link | None:
|
| 346 |
+
"""
|
| 347 |
+
Convert an anchor element's attributes in a simple repository page to a Link.
|
| 348 |
+
"""
|
| 349 |
+
href = anchor_attribs.get("href")
|
| 350 |
+
if not href:
|
| 351 |
+
return None
|
| 352 |
+
|
| 353 |
+
url = _ensure_quoted_url(_absolute_link_url(base_url, href))
|
| 354 |
+
pyrequire = anchor_attribs.get("data-requires-python")
|
| 355 |
+
yanked_reason = anchor_attribs.get("data-yanked")
|
| 356 |
+
|
| 357 |
+
# PEP 714: Indexes must use the name data-core-metadata, but
|
| 358 |
+
# clients should support the old name as a fallback for compatibility.
|
| 359 |
+
metadata_info = anchor_attribs.get("data-core-metadata")
|
| 360 |
+
if metadata_info is None:
|
| 361 |
+
metadata_info = anchor_attribs.get("data-dist-info-metadata")
|
| 362 |
+
# The metadata info value may be the string "true", or a string of
|
| 363 |
+
# the form "hashname=hashval"
|
| 364 |
+
if metadata_info == "true":
|
| 365 |
+
# The file exists, but there are no hashes
|
| 366 |
+
metadata_file_data = MetadataFile(None)
|
| 367 |
+
elif metadata_info is None:
|
| 368 |
+
# The file does not exist
|
| 369 |
+
metadata_file_data = None
|
| 370 |
+
else:
|
| 371 |
+
# The file exists, and hashes have been supplied
|
| 372 |
+
hashname, sep, hashval = metadata_info.partition("=")
|
| 373 |
+
if sep == "=":
|
| 374 |
+
metadata_file_data = MetadataFile(supported_hashes({hashname: hashval}))
|
| 375 |
+
else:
|
| 376 |
+
# Error - data is wrong. Treat as no hashes supplied.
|
| 377 |
+
logger.debug(
|
| 378 |
+
"Index returned invalid data-dist-info-metadata value: %s",
|
| 379 |
+
metadata_info,
|
| 380 |
+
)
|
| 381 |
+
metadata_file_data = MetadataFile(None)
|
| 382 |
+
|
| 383 |
+
return cls(
|
| 384 |
+
url,
|
| 385 |
+
comes_from=page_url,
|
| 386 |
+
requires_python=pyrequire,
|
| 387 |
+
yanked_reason=yanked_reason,
|
| 388 |
+
metadata_file_data=metadata_file_data,
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
def __str__(self) -> str:
|
| 392 |
+
if self.requires_python:
|
| 393 |
+
rp = f" (requires-python:{self.requires_python})"
|
| 394 |
+
else:
|
| 395 |
+
rp = ""
|
| 396 |
+
if self.comes_from:
|
| 397 |
+
return f"{self.redacted_url} (from {self.comes_from}){rp}"
|
| 398 |
+
else:
|
| 399 |
+
return self.redacted_url
|
| 400 |
+
|
| 401 |
+
def __repr__(self) -> str:
|
| 402 |
+
return f"<Link {self}>"
|
| 403 |
+
|
| 404 |
+
def __hash__(self) -> int:
|
| 405 |
+
return hash(self.url)
|
| 406 |
+
|
| 407 |
+
def __eq__(self, other: Any) -> bool:
|
| 408 |
+
if not isinstance(other, Link):
|
| 409 |
+
return NotImplemented
|
| 410 |
+
return self.url == other.url
|
| 411 |
+
|
| 412 |
+
def __lt__(self, other: Any) -> bool:
|
| 413 |
+
if not isinstance(other, Link):
|
| 414 |
+
return NotImplemented
|
| 415 |
+
return self.url < other.url
|
| 416 |
+
|
| 417 |
+
@property
|
| 418 |
+
def url(self) -> str:
|
| 419 |
+
return self._url
|
| 420 |
+
|
| 421 |
+
@property
|
| 422 |
+
def redacted_url(self) -> str:
|
| 423 |
+
return redact_auth_from_url(self.url)
|
| 424 |
+
|
| 425 |
+
@property
|
| 426 |
+
def filename(self) -> str:
|
| 427 |
+
path = self.path.rstrip("/")
|
| 428 |
+
name = posixpath.basename(path)
|
| 429 |
+
if not name:
|
| 430 |
+
# Make sure we don't leak auth information if the netloc
|
| 431 |
+
# includes a username and password.
|
| 432 |
+
netloc, user_pass = split_auth_from_netloc(self.netloc)
|
| 433 |
+
return netloc
|
| 434 |
+
|
| 435 |
+
name = urllib.parse.unquote(name)
|
| 436 |
+
assert name, f"URL {self._url!r} produced no filename"
|
| 437 |
+
return name
|
| 438 |
+
|
| 439 |
+
@property
|
| 440 |
+
def file_path(self) -> str:
|
| 441 |
+
return url_to_path(self.url)
|
| 442 |
+
|
| 443 |
+
@property
|
| 444 |
+
def scheme(self) -> str:
|
| 445 |
+
return self._parsed_url.scheme
|
| 446 |
+
|
| 447 |
+
@property
|
| 448 |
+
def netloc(self) -> str:
|
| 449 |
+
"""
|
| 450 |
+
This can contain auth information.
|
| 451 |
+
"""
|
| 452 |
+
return self._parsed_url.netloc
|
| 453 |
+
|
| 454 |
+
@property
|
| 455 |
+
def path(self) -> str:
|
| 456 |
+
return self._path
|
| 457 |
+
|
| 458 |
+
def splitext(self) -> tuple[str, str]:
|
| 459 |
+
return splitext(posixpath.basename(self.path.rstrip("/")))
|
| 460 |
+
|
| 461 |
+
@property
|
| 462 |
+
def ext(self) -> str:
|
| 463 |
+
return self.splitext()[1]
|
| 464 |
+
|
| 465 |
+
@property
|
| 466 |
+
def url_without_fragment(self) -> str:
|
| 467 |
+
scheme, netloc, path, query, fragment = self._parsed_url
|
| 468 |
+
return urllib.parse.urlunsplit((scheme, netloc, path, query, ""))
|
| 469 |
+
|
| 470 |
+
_egg_fragment_re = re.compile(r"[#&]egg=([^&]*)")
|
| 471 |
+
|
| 472 |
+
# Per PEP 508.
|
| 473 |
+
_project_name_re = re.compile(
|
| 474 |
+
r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
def _egg_fragment(self) -> str | None:
|
| 478 |
+
match = self._egg_fragment_re.search(self._url)
|
| 479 |
+
if not match:
|
| 480 |
+
return None
|
| 481 |
+
|
| 482 |
+
# An egg fragment looks like a PEP 508 project name, along with
|
| 483 |
+
# an optional extras specifier. Anything else is invalid.
|
| 484 |
+
project_name = match.group(1)
|
| 485 |
+
if not self._project_name_re.match(project_name):
|
| 486 |
+
raise InvalidEggFragment(self, project_name)
|
| 487 |
+
|
| 488 |
+
return project_name
|
| 489 |
+
|
| 490 |
+
_subdirectory_fragment_re = re.compile(r"[#&]subdirectory=([^&]*)")
|
| 491 |
+
|
| 492 |
+
@property
|
| 493 |
+
def subdirectory_fragment(self) -> str | None:
|
| 494 |
+
match = self._subdirectory_fragment_re.search(self._url)
|
| 495 |
+
if not match:
|
| 496 |
+
return None
|
| 497 |
+
return match.group(1)
|
| 498 |
+
|
| 499 |
+
def metadata_link(self) -> Link | None:
|
| 500 |
+
"""Return a link to the associated core metadata file (if any)."""
|
| 501 |
+
if self.metadata_file_data is None:
|
| 502 |
+
return None
|
| 503 |
+
metadata_url = f"{self.url_without_fragment}.metadata"
|
| 504 |
+
if self.metadata_file_data.hashes is None:
|
| 505 |
+
return Link(metadata_url)
|
| 506 |
+
return Link(metadata_url, hashes=self.metadata_file_data.hashes)
|
| 507 |
+
|
| 508 |
+
def as_hashes(self) -> Hashes:
|
| 509 |
+
return Hashes({k: [v] for k, v in self._hashes.items()})
|
| 510 |
+
|
| 511 |
+
@property
|
| 512 |
+
def hash(self) -> str | None:
|
| 513 |
+
return next(iter(self._hashes.values()), None)
|
| 514 |
+
|
| 515 |
+
@property
|
| 516 |
+
def hash_name(self) -> str | None:
|
| 517 |
+
return next(iter(self._hashes), None)
|
| 518 |
+
|
| 519 |
+
@property
|
| 520 |
+
def show_url(self) -> str:
|
| 521 |
+
return posixpath.basename(self._url.split("#", 1)[0].split("?", 1)[0])
|
| 522 |
+
|
| 523 |
+
@property
|
| 524 |
+
def is_file(self) -> bool:
|
| 525 |
+
return self.scheme == "file"
|
| 526 |
+
|
| 527 |
+
def is_existing_dir(self) -> bool:
|
| 528 |
+
return self.is_file and os.path.isdir(self.file_path)
|
| 529 |
+
|
| 530 |
+
@property
|
| 531 |
+
def is_wheel(self) -> bool:
|
| 532 |
+
return self.ext == WHEEL_EXTENSION
|
| 533 |
+
|
| 534 |
+
@property
|
| 535 |
+
def is_vcs(self) -> bool:
|
| 536 |
+
from pip._internal.vcs import vcs
|
| 537 |
+
|
| 538 |
+
return self.scheme in vcs.all_schemes
|
| 539 |
+
|
| 540 |
+
@property
|
| 541 |
+
def is_yanked(self) -> bool:
|
| 542 |
+
return self.yanked_reason is not None
|
| 543 |
+
|
| 544 |
+
@property
|
| 545 |
+
def has_hash(self) -> bool:
|
| 546 |
+
return bool(self._hashes)
|
| 547 |
+
|
| 548 |
+
def is_hash_allowed(self, hashes: Hashes | None) -> bool:
|
| 549 |
+
"""
|
| 550 |
+
Return True if the link has a hash and it is allowed by `hashes`.
|
| 551 |
+
"""
|
| 552 |
+
if hashes is None:
|
| 553 |
+
return False
|
| 554 |
+
return any(hashes.is_hash_allowed(k, v) for k, v in self._hashes.items())
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
class _CleanResult(NamedTuple):
|
| 558 |
+
"""Convert link for equivalency check.
|
| 559 |
+
|
| 560 |
+
This is used in the resolver to check whether two URL-specified requirements
|
| 561 |
+
likely point to the same distribution and can be considered equivalent. This
|
| 562 |
+
equivalency logic avoids comparing URLs literally, which can be too strict
|
| 563 |
+
(e.g. "a=1&b=2" vs "b=2&a=1") and produce conflicts unexpecting to users.
|
| 564 |
+
|
| 565 |
+
Currently this does three things:
|
| 566 |
+
|
| 567 |
+
1. Drop the basic auth part. This is technically wrong since a server can
|
| 568 |
+
serve different content based on auth, but if it does that, it is even
|
| 569 |
+
impossible to guarantee two URLs without auth are equivalent, since
|
| 570 |
+
the user can input different auth information when prompted. So the
|
| 571 |
+
practical solution is to assume the auth doesn't affect the response.
|
| 572 |
+
2. Parse the query to avoid the ordering issue. Note that ordering under the
|
| 573 |
+
same key in the query are NOT cleaned; i.e. "a=1&a=2" and "a=2&a=1" are
|
| 574 |
+
still considered different.
|
| 575 |
+
3. Explicitly drop most of the fragment part, except ``subdirectory=`` and
|
| 576 |
+
hash values, since it should have no impact the downloaded content. Note
|
| 577 |
+
that this drops the "egg=" part historically used to denote the requested
|
| 578 |
+
project (and extras), which is wrong in the strictest sense, but too many
|
| 579 |
+
people are supplying it inconsistently to cause superfluous resolution
|
| 580 |
+
conflicts, so we choose to also ignore them.
|
| 581 |
+
"""
|
| 582 |
+
|
| 583 |
+
parsed: urllib.parse.SplitResult
|
| 584 |
+
query: dict[str, list[str]]
|
| 585 |
+
subdirectory: str
|
| 586 |
+
hashes: dict[str, str]
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def _clean_link(link: Link) -> _CleanResult:
|
| 590 |
+
parsed = link._parsed_url
|
| 591 |
+
netloc = parsed.netloc.rsplit("@", 1)[-1]
|
| 592 |
+
# According to RFC 8089, an empty host in file: means localhost.
|
| 593 |
+
if parsed.scheme == "file" and not netloc:
|
| 594 |
+
netloc = "localhost"
|
| 595 |
+
fragment = urllib.parse.parse_qs(parsed.fragment)
|
| 596 |
+
if "egg" in fragment:
|
| 597 |
+
logger.debug("Ignoring egg= fragment in %s", link)
|
| 598 |
+
try:
|
| 599 |
+
# If there are multiple subdirectory values, use the first one.
|
| 600 |
+
# This matches the behavior of Link.subdirectory_fragment.
|
| 601 |
+
subdirectory = fragment["subdirectory"][0]
|
| 602 |
+
except (IndexError, KeyError):
|
| 603 |
+
subdirectory = ""
|
| 604 |
+
# If there are multiple hash values under the same algorithm, use the
|
| 605 |
+
# first one. This matches the behavior of Link.hash_value.
|
| 606 |
+
hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment}
|
| 607 |
+
return _CleanResult(
|
| 608 |
+
parsed=parsed._replace(netloc=netloc, query="", fragment=""),
|
| 609 |
+
query=urllib.parse.parse_qs(parsed.query),
|
| 610 |
+
subdirectory=subdirectory,
|
| 611 |
+
hashes=hashes,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
@functools.cache
|
| 616 |
+
def links_equivalent(link1: Link, link2: Link) -> bool:
|
| 617 |
+
return _clean_link(link1) == _clean_link(link2)
|
.venv/lib/python3.12/site-packages/pip/_internal/models/release_control.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
|
| 5 |
+
from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
|
| 6 |
+
|
| 7 |
+
from pip._internal.exceptions import CommandError
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# TODO: add slots=True when Python 3.9 is dropped
|
| 11 |
+
@dataclass
|
| 12 |
+
class ReleaseControl:
|
| 13 |
+
"""Helper for managing which release types can be installed."""
|
| 14 |
+
|
| 15 |
+
all_releases: set[str] = field(default_factory=set)
|
| 16 |
+
only_final: set[str] = field(default_factory=set)
|
| 17 |
+
_order: list[tuple[str, str]] = field(
|
| 18 |
+
init=False, default_factory=list, compare=False, repr=False
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
def handle_mutual_excludes(
|
| 22 |
+
self, value: str, target: set[str], other: set[str], attr_name: str
|
| 23 |
+
) -> None:
|
| 24 |
+
"""Parse and apply release control option value.
|
| 25 |
+
|
| 26 |
+
Processes comma-separated package names or special values `:all:` and `:none:`.
|
| 27 |
+
|
| 28 |
+
When adding packages to target, they're removed from other to maintain mutual
|
| 29 |
+
exclusivity between all_releases and only_final. All operations are tracked in
|
| 30 |
+
order so that the original command-line argument sequence can be reconstructed
|
| 31 |
+
when passing options to build subprocesses.
|
| 32 |
+
"""
|
| 33 |
+
if value.startswith("-"):
|
| 34 |
+
raise CommandError(
|
| 35 |
+
"--all-releases / --only-final option requires 1 argument."
|
| 36 |
+
)
|
| 37 |
+
new = value.split(",")
|
| 38 |
+
while ":all:" in new:
|
| 39 |
+
other.clear()
|
| 40 |
+
target.clear()
|
| 41 |
+
target.add(":all:")
|
| 42 |
+
# Track :all: in order
|
| 43 |
+
self._order.append((attr_name, ":all:"))
|
| 44 |
+
del new[: new.index(":all:") + 1]
|
| 45 |
+
# Without a none, we want to discard everything as :all: covers it
|
| 46 |
+
if ":none:" not in new:
|
| 47 |
+
return
|
| 48 |
+
for name in new:
|
| 49 |
+
if name == ":none:":
|
| 50 |
+
target.clear()
|
| 51 |
+
# Track :none: in order
|
| 52 |
+
self._order.append((attr_name, ":none:"))
|
| 53 |
+
continue
|
| 54 |
+
name = canonicalize_name(name)
|
| 55 |
+
other.discard(name)
|
| 56 |
+
target.add(name)
|
| 57 |
+
# Track package-specific setting in order
|
| 58 |
+
self._order.append((attr_name, name))
|
| 59 |
+
|
| 60 |
+
def get_ordered_args(self) -> list[tuple[str, str]]:
|
| 61 |
+
"""
|
| 62 |
+
Get ordered list of (flag_name, value) tuples for reconstructing CLI args.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
List of tuples where each tuple is (attribute_name, value).
|
| 66 |
+
The attribute_name is either 'all_releases' or 'only_final'.
|
| 67 |
+
|
| 68 |
+
Example:
|
| 69 |
+
[("all_releases", ":all:"), ("only_final", "simple")]
|
| 70 |
+
would be reconstructed as:
|
| 71 |
+
["--all-releases", ":all:", "--only-final", "simple"]
|
| 72 |
+
"""
|
| 73 |
+
return self._order[:]
|
| 74 |
+
|
| 75 |
+
def allows_prereleases(self, canonical_name: NormalizedName) -> bool | None:
|
| 76 |
+
"""
|
| 77 |
+
Determine if pre-releases are allowed for a package.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
True: Pre-releases are allowed (package in all_releases)
|
| 81 |
+
False: Only final releases allowed (package in only_final)
|
| 82 |
+
None: No specific setting, use default behavior
|
| 83 |
+
"""
|
| 84 |
+
if canonical_name in self.all_releases:
|
| 85 |
+
return True
|
| 86 |
+
elif canonical_name in self.only_final:
|
| 87 |
+
return False
|
| 88 |
+
elif ":all:" in self.all_releases:
|
| 89 |
+
return True
|
| 90 |
+
elif ":all:" in self.only_final:
|
| 91 |
+
return False
|
| 92 |
+
return None
|
.venv/lib/python3.12/site-packages/pip/_internal/models/search_scope.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import posixpath
|
| 5 |
+
import urllib.parse
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
|
| 8 |
+
from pip._vendor.packaging.utils import canonicalize_name
|
| 9 |
+
|
| 10 |
+
from pip._internal.models.index import PyPI
|
| 11 |
+
from pip._internal.utils.compat import has_tls
|
| 12 |
+
from pip._internal.utils.misc import normalize_path, redact_auth_from_url
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True)
|
| 18 |
+
class SearchScope:
|
| 19 |
+
"""
|
| 20 |
+
Encapsulates the locations that pip is configured to search.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
__slots__ = ["find_links", "index_urls", "no_index"]
|
| 24 |
+
|
| 25 |
+
find_links: list[str]
|
| 26 |
+
index_urls: list[str]
|
| 27 |
+
no_index: bool
|
| 28 |
+
|
| 29 |
+
@classmethod
|
| 30 |
+
def create(
|
| 31 |
+
cls,
|
| 32 |
+
find_links: list[str],
|
| 33 |
+
index_urls: list[str],
|
| 34 |
+
no_index: bool,
|
| 35 |
+
) -> "SearchScope":
|
| 36 |
+
"""
|
| 37 |
+
Create a SearchScope object after normalizing the `find_links`.
|
| 38 |
+
"""
|
| 39 |
+
# Build find_links. If an argument starts with ~, it may be
|
| 40 |
+
# a local file relative to a home directory. So try normalizing
|
| 41 |
+
# it and if it exists, use the normalized version.
|
| 42 |
+
# This is deliberately conservative - it might be fine just to
|
| 43 |
+
# blindly normalize anything starting with a ~...
|
| 44 |
+
built_find_links: list[str] = []
|
| 45 |
+
for link in find_links:
|
| 46 |
+
if link.startswith("~"):
|
| 47 |
+
new_link = normalize_path(link)
|
| 48 |
+
if os.path.exists(new_link):
|
| 49 |
+
link = new_link
|
| 50 |
+
built_find_links.append(link)
|
| 51 |
+
|
| 52 |
+
# If we don't have TLS enabled, then WARN if anyplace we're looking
|
| 53 |
+
# relies on TLS.
|
| 54 |
+
if not has_tls():
|
| 55 |
+
for link in itertools.chain(index_urls, built_find_links):
|
| 56 |
+
parsed = urllib.parse.urlparse(link)
|
| 57 |
+
if parsed.scheme == "https":
|
| 58 |
+
logger.warning(
|
| 59 |
+
"pip is configured with locations that require "
|
| 60 |
+
"TLS/SSL, however the ssl module in Python is not "
|
| 61 |
+
"available."
|
| 62 |
+
)
|
| 63 |
+
break
|
| 64 |
+
|
| 65 |
+
return cls(
|
| 66 |
+
find_links=built_find_links,
|
| 67 |
+
index_urls=index_urls,
|
| 68 |
+
no_index=no_index,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def get_formatted_locations(self) -> str:
|
| 72 |
+
lines = []
|
| 73 |
+
redacted_index_urls = []
|
| 74 |
+
if self.index_urls and self.index_urls != [PyPI.simple_url]:
|
| 75 |
+
for url in self.index_urls:
|
| 76 |
+
redacted_index_url = redact_auth_from_url(url)
|
| 77 |
+
|
| 78 |
+
# Parse the URL
|
| 79 |
+
purl = urllib.parse.urlsplit(redacted_index_url)
|
| 80 |
+
|
| 81 |
+
# URL is generally invalid if scheme and netloc is missing
|
| 82 |
+
# there are issues with Python and URL parsing, so this test
|
| 83 |
+
# is a bit crude. See bpo-20271, bpo-23505. Python doesn't
|
| 84 |
+
# always parse invalid URLs correctly - it should raise
|
| 85 |
+
# exceptions for malformed URLs
|
| 86 |
+
if not purl.scheme and not purl.netloc:
|
| 87 |
+
logger.warning(
|
| 88 |
+
'The index url "%s" seems invalid, please provide a scheme.',
|
| 89 |
+
redacted_index_url,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
redacted_index_urls.append(redacted_index_url)
|
| 93 |
+
|
| 94 |
+
lines.append(
|
| 95 |
+
"Looking in indexes: {}".format(", ".join(redacted_index_urls))
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
if self.find_links:
|
| 99 |
+
lines.append(
|
| 100 |
+
"Looking in links: {}".format(
|
| 101 |
+
", ".join(redact_auth_from_url(url) for url in self.find_links)
|
| 102 |
+
)
|
| 103 |
+
)
|
| 104 |
+
return "\n".join(lines)
|
| 105 |
+
|
| 106 |
+
def get_index_urls_locations(self, project_name: str) -> list[str]:
|
| 107 |
+
"""Returns the locations found via self.index_urls
|
| 108 |
+
|
| 109 |
+
Checks the url_name on the main (first in the list) index and
|
| 110 |
+
use this url_name to produce all locations
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
def mkurl_pypi_url(url: str) -> str:
|
| 114 |
+
loc = posixpath.join(
|
| 115 |
+
url, urllib.parse.quote(canonicalize_name(project_name))
|
| 116 |
+
)
|
| 117 |
+
# For maximum compatibility with easy_install, ensure the path
|
| 118 |
+
# ends in a trailing slash. Although this isn't in the spec
|
| 119 |
+
# (and PyPI can handle it without the slash) some other index
|
| 120 |
+
# implementations might break if they relied on easy_install's
|
| 121 |
+
# behavior.
|
| 122 |
+
if not loc.endswith("/"):
|
| 123 |
+
loc = loc + "/"
|
| 124 |
+
return loc
|
| 125 |
+
|
| 126 |
+
return [mkurl_pypi_url(url) for url in self.index_urls]
|
.venv/lib/python3.12/site-packages/pip/_internal/models/selection_prefs.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pip._internal.models.format_control import FormatControl
|
| 4 |
+
from pip._internal.models.release_control import ReleaseControl
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# TODO: This needs Python 3.10's improved slots support for dataclasses
|
| 8 |
+
# to be converted into a dataclass.
|
| 9 |
+
class SelectionPreferences:
|
| 10 |
+
"""
|
| 11 |
+
Encapsulates the candidate selection preferences for downloading
|
| 12 |
+
and installing files.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
__slots__ = [
|
| 16 |
+
"allow_yanked",
|
| 17 |
+
"release_control",
|
| 18 |
+
"format_control",
|
| 19 |
+
"prefer_binary",
|
| 20 |
+
"ignore_requires_python",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
# Don't include an allow_yanked default value to make sure each call
|
| 24 |
+
# site considers whether yanked releases are allowed. This also causes
|
| 25 |
+
# that decision to be made explicit in the calling code, which helps
|
| 26 |
+
# people when reading the code.
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
allow_yanked: bool,
|
| 30 |
+
release_control: ReleaseControl | None = None,
|
| 31 |
+
format_control: FormatControl | None = None,
|
| 32 |
+
prefer_binary: bool = False,
|
| 33 |
+
ignore_requires_python: bool | None = None,
|
| 34 |
+
) -> None:
|
| 35 |
+
"""Create a SelectionPreferences object.
|
| 36 |
+
|
| 37 |
+
:param allow_yanked: Whether files marked as yanked (in the sense
|
| 38 |
+
of PEP 592) are permitted to be candidates for install.
|
| 39 |
+
:param release_control: A ReleaseControl object or None. Used to control
|
| 40 |
+
whether pre-releases are allowed for specific packages.
|
| 41 |
+
:param format_control: A FormatControl object or None. Used to control
|
| 42 |
+
the selection of source packages / binary packages when consulting
|
| 43 |
+
the index and links.
|
| 44 |
+
:param prefer_binary: Whether to prefer an old, but valid, binary
|
| 45 |
+
dist over a new source dist.
|
| 46 |
+
:param ignore_requires_python: Whether to ignore incompatible
|
| 47 |
+
"Requires-Python" values in links. Defaults to False.
|
| 48 |
+
"""
|
| 49 |
+
if ignore_requires_python is None:
|
| 50 |
+
ignore_requires_python = False
|
| 51 |
+
|
| 52 |
+
self.allow_yanked = allow_yanked
|
| 53 |
+
self.release_control = release_control
|
| 54 |
+
self.format_control = format_control
|
| 55 |
+
self.prefer_binary = prefer_binary
|
| 56 |
+
self.ignore_requires_python = ignore_requires_python
|
.venv/lib/python3.12/site-packages/pip/_internal/models/target_python.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from pip._vendor.packaging.tags import Tag
|
| 6 |
+
|
| 7 |
+
from pip._internal.utils.compatibility_tags import get_supported, version_info_to_nodot
|
| 8 |
+
from pip._internal.utils.misc import normalize_version_info
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TargetPython:
|
| 12 |
+
"""
|
| 13 |
+
Encapsulates the properties of a Python interpreter one is targeting
|
| 14 |
+
for a package install, download, etc.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
__slots__ = [
|
| 18 |
+
"_given_py_version_info",
|
| 19 |
+
"abis",
|
| 20 |
+
"implementation",
|
| 21 |
+
"platforms",
|
| 22 |
+
"py_version",
|
| 23 |
+
"py_version_info",
|
| 24 |
+
"_valid_tags",
|
| 25 |
+
"_valid_tags_set",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
platforms: list[str] | None = None,
|
| 31 |
+
py_version_info: tuple[int, ...] | None = None,
|
| 32 |
+
abis: list[str] | None = None,
|
| 33 |
+
implementation: str | None = None,
|
| 34 |
+
) -> None:
|
| 35 |
+
"""
|
| 36 |
+
:param platforms: A list of strings or None. If None, searches for
|
| 37 |
+
packages that are supported by the current system. Otherwise, will
|
| 38 |
+
find packages that can be built on the platforms passed in. These
|
| 39 |
+
packages will only be downloaded for distribution: they will
|
| 40 |
+
not be built locally.
|
| 41 |
+
:param py_version_info: An optional tuple of ints representing the
|
| 42 |
+
Python version information to use (e.g. `sys.version_info[:3]`).
|
| 43 |
+
This can have length 1, 2, or 3 when provided.
|
| 44 |
+
:param abis: A list of strings or None. This is passed to
|
| 45 |
+
compatibility_tags.py's get_supported() function as is.
|
| 46 |
+
:param implementation: A string or None. This is passed to
|
| 47 |
+
compatibility_tags.py's get_supported() function as is.
|
| 48 |
+
"""
|
| 49 |
+
# Store the given py_version_info for when we call get_supported().
|
| 50 |
+
self._given_py_version_info = py_version_info
|
| 51 |
+
|
| 52 |
+
if py_version_info is None:
|
| 53 |
+
py_version_info = sys.version_info[:3]
|
| 54 |
+
else:
|
| 55 |
+
py_version_info = normalize_version_info(py_version_info)
|
| 56 |
+
|
| 57 |
+
py_version = ".".join(map(str, py_version_info[:2]))
|
| 58 |
+
|
| 59 |
+
self.abis = abis
|
| 60 |
+
self.implementation = implementation
|
| 61 |
+
self.platforms = platforms
|
| 62 |
+
self.py_version = py_version
|
| 63 |
+
self.py_version_info = py_version_info
|
| 64 |
+
|
| 65 |
+
# This is used to cache the return value of get_(un)sorted_tags.
|
| 66 |
+
self._valid_tags: list[Tag] | None = None
|
| 67 |
+
self._valid_tags_set: set[Tag] | None = None
|
| 68 |
+
|
| 69 |
+
def format_given(self) -> str:
|
| 70 |
+
"""
|
| 71 |
+
Format the given, non-None attributes for display.
|
| 72 |
+
"""
|
| 73 |
+
display_version = None
|
| 74 |
+
if self._given_py_version_info is not None:
|
| 75 |
+
display_version = ".".join(
|
| 76 |
+
str(part) for part in self._given_py_version_info
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
key_values = [
|
| 80 |
+
("platforms", self.platforms),
|
| 81 |
+
("version_info", display_version),
|
| 82 |
+
("abis", self.abis),
|
| 83 |
+
("implementation", self.implementation),
|
| 84 |
+
]
|
| 85 |
+
return " ".join(
|
| 86 |
+
f"{key}={value!r}" for key, value in key_values if value is not None
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
def get_sorted_tags(self) -> list[Tag]:
|
| 90 |
+
"""
|
| 91 |
+
Return the supported PEP 425 tags to check wheel candidates against.
|
| 92 |
+
|
| 93 |
+
The tags are returned in order of preference (most preferred first).
|
| 94 |
+
"""
|
| 95 |
+
if self._valid_tags is None:
|
| 96 |
+
# Pass versions=None if no py_version_info was given since
|
| 97 |
+
# versions=None uses special default logic.
|
| 98 |
+
py_version_info = self._given_py_version_info
|
| 99 |
+
if py_version_info is None:
|
| 100 |
+
version = None
|
| 101 |
+
else:
|
| 102 |
+
version = version_info_to_nodot(py_version_info)
|
| 103 |
+
|
| 104 |
+
tags = get_supported(
|
| 105 |
+
version=version,
|
| 106 |
+
platforms=self.platforms,
|
| 107 |
+
abis=self.abis,
|
| 108 |
+
impl=self.implementation,
|
| 109 |
+
)
|
| 110 |
+
self._valid_tags = tags
|
| 111 |
+
|
| 112 |
+
return self._valid_tags
|
| 113 |
+
|
| 114 |
+
def get_unsorted_tags(self) -> set[Tag]:
|
| 115 |
+
"""Exactly the same as get_sorted_tags, but returns a set.
|
| 116 |
+
|
| 117 |
+
This is important for performance.
|
| 118 |
+
"""
|
| 119 |
+
if self._valid_tags_set is None:
|
| 120 |
+
self._valid_tags_set = set(self.get_sorted_tags())
|
| 121 |
+
|
| 122 |
+
return self._valid_tags_set
|
.venv/lib/python3.12/site-packages/pip/_internal/models/wheel.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Represents a wheel file and provides access to the various parts of the
|
| 2 |
+
name that have meaning.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from collections.abc import Iterable
|
| 8 |
+
|
| 9 |
+
from pip._vendor.packaging.tags import Tag
|
| 10 |
+
from pip._vendor.packaging.utils import (
|
| 11 |
+
InvalidWheelFilename as _PackagingInvalidWheelFilename,
|
| 12 |
+
)
|
| 13 |
+
from pip._vendor.packaging.utils import parse_wheel_filename
|
| 14 |
+
|
| 15 |
+
from pip._internal.exceptions import InvalidWheelFilename
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Wheel:
|
| 19 |
+
"""A wheel file"""
|
| 20 |
+
|
| 21 |
+
def __init__(self, filename: str) -> None:
|
| 22 |
+
self.filename = filename
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
wheel_info = parse_wheel_filename(filename)
|
| 26 |
+
except _PackagingInvalidWheelFilename as e:
|
| 27 |
+
raise InvalidWheelFilename(e.args[0]) from None
|
| 28 |
+
|
| 29 |
+
self.name, _version, self.build_tag, self.file_tags = wheel_info
|
| 30 |
+
self.version = str(_version)
|
| 31 |
+
|
| 32 |
+
def get_formatted_file_tags(self) -> list[str]:
|
| 33 |
+
"""Return the wheel's tags as a sorted list of strings."""
|
| 34 |
+
return sorted(str(tag) for tag in self.file_tags)
|
| 35 |
+
|
| 36 |
+
def support_index_min(self, tags: list[Tag]) -> int:
|
| 37 |
+
"""Return the lowest index that one of the wheel's file_tag combinations
|
| 38 |
+
achieves in the given list of supported tags.
|
| 39 |
+
|
| 40 |
+
For example, if there are 8 supported tags and one of the file tags
|
| 41 |
+
is first in the list, then return 0.
|
| 42 |
+
|
| 43 |
+
:param tags: the PEP 425 tags to check the wheel against, in order
|
| 44 |
+
with most preferred first.
|
| 45 |
+
|
| 46 |
+
:raises ValueError: If none of the wheel's file tags match one of
|
| 47 |
+
the supported tags.
|
| 48 |
+
"""
|
| 49 |
+
try:
|
| 50 |
+
return next(i for i, t in enumerate(tags) if t in self.file_tags)
|
| 51 |
+
except StopIteration:
|
| 52 |
+
raise ValueError()
|
| 53 |
+
|
| 54 |
+
def find_most_preferred_tag(
|
| 55 |
+
self, tags: list[Tag], tag_to_priority: dict[Tag, int]
|
| 56 |
+
) -> int:
|
| 57 |
+
"""Return the priority of the most preferred tag that one of the wheel's file
|
| 58 |
+
tag combinations achieves in the given list of supported tags using the given
|
| 59 |
+
tag_to_priority mapping, where lower priorities are more-preferred.
|
| 60 |
+
|
| 61 |
+
This is used in place of support_index_min in some cases in order to avoid
|
| 62 |
+
an expensive linear scan of a large list of tags.
|
| 63 |
+
|
| 64 |
+
:param tags: the PEP 425 tags to check the wheel against.
|
| 65 |
+
:param tag_to_priority: a mapping from tag to priority of that tag, where
|
| 66 |
+
lower is more preferred.
|
| 67 |
+
|
| 68 |
+
:raises ValueError: If none of the wheel's file tags match one of
|
| 69 |
+
the supported tags.
|
| 70 |
+
"""
|
| 71 |
+
return min(
|
| 72 |
+
tag_to_priority[tag] for tag in self.file_tags if tag in tag_to_priority
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
def supported(self, tags: Iterable[Tag]) -> bool:
|
| 76 |
+
"""Return whether the wheel is compatible with one of the given tags.
|
| 77 |
+
|
| 78 |
+
:param tags: the PEP 425 tags to check the wheel against.
|
| 79 |
+
"""
|
| 80 |
+
return not self.file_tags.isdisjoint(tags)
|
.venv/lib/python3.12/site-packages/pip/_internal/network/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Contains purely network-related utilities."""
|
.venv/lib/python3.12/site-packages/pip/_internal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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Network Authentication Helpers
|
| 2 |
+
|
| 3 |
+
Contains interface (MultiDomainBasicAuth) and associated glue code for
|
| 4 |
+
providing credentials in the context of network requests.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import logging
|
| 10 |
+
import os
|
| 11 |
+
import shutil
|
| 12 |
+
import subprocess
|
| 13 |
+
import sysconfig
|
| 14 |
+
import typing
|
| 15 |
+
import urllib.parse
|
| 16 |
+
from abc import ABC, abstractmethod
|
| 17 |
+
from functools import cache
|
| 18 |
+
from os.path import commonprefix
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any, NamedTuple
|
| 21 |
+
|
| 22 |
+
from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth
|
| 23 |
+
from pip._vendor.requests.utils import get_netrc_auth
|
| 24 |
+
|
| 25 |
+
from pip._internal.utils.logging import getLogger
|
| 26 |
+
from pip._internal.utils.misc import (
|
| 27 |
+
ask,
|
| 28 |
+
ask_input,
|
| 29 |
+
ask_password,
|
| 30 |
+
remove_auth_from_url,
|
| 31 |
+
split_auth_netloc_from_url,
|
| 32 |
+
)
|
| 33 |
+
from pip._internal.vcs.versioncontrol import AuthInfo
|
| 34 |
+
|
| 35 |
+
if typing.TYPE_CHECKING:
|
| 36 |
+
from pip._vendor.requests import PreparedRequest
|
| 37 |
+
from pip._vendor.requests.models import Response
|
| 38 |
+
|
| 39 |
+
logger = getLogger(__name__)
|
| 40 |
+
|
| 41 |
+
KEYRING_DISABLED = False
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Credentials(NamedTuple):
|
| 45 |
+
url: str
|
| 46 |
+
username: str
|
| 47 |
+
password: str
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class KeyRingBaseProvider(ABC):
|
| 51 |
+
"""Keyring base provider interface"""
|
| 52 |
+
|
| 53 |
+
has_keyring: bool
|
| 54 |
+
|
| 55 |
+
@abstractmethod
|
| 56 |
+
def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None: ...
|
| 57 |
+
|
| 58 |
+
@abstractmethod
|
| 59 |
+
def save_auth_info(self, url: str, username: str, password: str) -> None: ...
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class KeyRingNullProvider(KeyRingBaseProvider):
|
| 63 |
+
"""Keyring null provider"""
|
| 64 |
+
|
| 65 |
+
has_keyring = False
|
| 66 |
+
|
| 67 |
+
def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
def save_auth_info(self, url: str, username: str, password: str) -> None:
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class KeyRingPythonProvider(KeyRingBaseProvider):
|
| 75 |
+
"""Keyring interface which uses locally imported `keyring`"""
|
| 76 |
+
|
| 77 |
+
has_keyring = True
|
| 78 |
+
|
| 79 |
+
def __init__(self) -> None:
|
| 80 |
+
import keyring
|
| 81 |
+
|
| 82 |
+
self.keyring = keyring
|
| 83 |
+
|
| 84 |
+
def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:
|
| 85 |
+
# Support keyring's get_credential interface which supports getting
|
| 86 |
+
# credentials without a username. This is only available for
|
| 87 |
+
# keyring>=15.2.0.
|
| 88 |
+
if hasattr(self.keyring, "get_credential"):
|
| 89 |
+
logger.debug("Getting credentials from keyring for %s", url)
|
| 90 |
+
cred = self.keyring.get_credential(url, username)
|
| 91 |
+
if cred is not None:
|
| 92 |
+
return cred.username, cred.password
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
if username is not None:
|
| 96 |
+
logger.debug("Getting password from keyring for %s", url)
|
| 97 |
+
password = self.keyring.get_password(url, username)
|
| 98 |
+
if password:
|
| 99 |
+
return username, password
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
def save_auth_info(self, url: str, username: str, password: str) -> None:
|
| 103 |
+
self.keyring.set_password(url, username, password)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class KeyRingCliProvider(KeyRingBaseProvider):
|
| 107 |
+
"""Provider which uses `keyring` cli
|
| 108 |
+
|
| 109 |
+
Instead of calling the keyring package installed alongside pip
|
| 110 |
+
we call keyring on the command line which will enable pip to
|
| 111 |
+
use which ever installation of keyring is available first in
|
| 112 |
+
PATH.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
has_keyring = True
|
| 116 |
+
|
| 117 |
+
def __init__(self, cmd: str) -> None:
|
| 118 |
+
self.keyring = cmd
|
| 119 |
+
|
| 120 |
+
def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:
|
| 121 |
+
# This is the default implementation of keyring.get_credential
|
| 122 |
+
# https://github.com/jaraco/keyring/blob/97689324abcf01bd1793d49063e7ca01e03d7d07/keyring/backend.py#L134-L139
|
| 123 |
+
if username is not None:
|
| 124 |
+
password = self._get_password(url, username)
|
| 125 |
+
if password is not None:
|
| 126 |
+
return username, password
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
def save_auth_info(self, url: str, username: str, password: str) -> None:
|
| 130 |
+
return self._set_password(url, username, password)
|
| 131 |
+
|
| 132 |
+
def _get_password(self, service_name: str, username: str) -> str | None:
|
| 133 |
+
"""Mirror the implementation of keyring.get_password using cli"""
|
| 134 |
+
if self.keyring is None:
|
| 135 |
+
return None
|
| 136 |
+
|
| 137 |
+
cmd = [self.keyring, "get", service_name, username]
|
| 138 |
+
env = os.environ.copy()
|
| 139 |
+
env["PYTHONIOENCODING"] = "utf-8"
|
| 140 |
+
res = subprocess.run(
|
| 141 |
+
cmd,
|
| 142 |
+
stdin=subprocess.DEVNULL,
|
| 143 |
+
stdout=subprocess.PIPE,
|
| 144 |
+
env=env,
|
| 145 |
+
)
|
| 146 |
+
if res.returncode:
|
| 147 |
+
return None
|
| 148 |
+
return res.stdout.decode("utf-8").strip(os.linesep)
|
| 149 |
+
|
| 150 |
+
def _set_password(self, service_name: str, username: str, password: str) -> None:
|
| 151 |
+
"""Mirror the implementation of keyring.set_password using cli"""
|
| 152 |
+
if self.keyring is None:
|
| 153 |
+
return None
|
| 154 |
+
env = os.environ.copy()
|
| 155 |
+
env["PYTHONIOENCODING"] = "utf-8"
|
| 156 |
+
subprocess.run(
|
| 157 |
+
[self.keyring, "set", service_name, username],
|
| 158 |
+
input=f"{password}{os.linesep}".encode(),
|
| 159 |
+
env=env,
|
| 160 |
+
check=True,
|
| 161 |
+
)
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@cache
|
| 166 |
+
def get_keyring_provider(provider: str) -> KeyRingBaseProvider:
|
| 167 |
+
logger.verbose("Keyring provider requested: %s", provider)
|
| 168 |
+
|
| 169 |
+
# keyring has previously failed and been disabled
|
| 170 |
+
if KEYRING_DISABLED:
|
| 171 |
+
provider = "disabled"
|
| 172 |
+
if provider in ["import", "auto"]:
|
| 173 |
+
try:
|
| 174 |
+
impl = KeyRingPythonProvider()
|
| 175 |
+
logger.verbose("Keyring provider set: import")
|
| 176 |
+
return impl
|
| 177 |
+
except ImportError:
|
| 178 |
+
pass
|
| 179 |
+
except Exception as exc:
|
| 180 |
+
# In the event of an unexpected exception
|
| 181 |
+
# we should warn the user
|
| 182 |
+
msg = "Installed copy of keyring fails with exception %s"
|
| 183 |
+
if provider == "auto":
|
| 184 |
+
msg = msg + ", trying to find a keyring executable as a fallback"
|
| 185 |
+
logger.warning(msg, exc, exc_info=logger.isEnabledFor(logging.DEBUG))
|
| 186 |
+
if provider in ["subprocess", "auto"]:
|
| 187 |
+
cli = shutil.which("keyring")
|
| 188 |
+
if cli and cli.startswith(sysconfig.get_path("scripts")):
|
| 189 |
+
# all code within this function is stolen from shutil.which implementation
|
| 190 |
+
@typing.no_type_check
|
| 191 |
+
def PATH_as_shutil_which_determines_it() -> str:
|
| 192 |
+
path = os.environ.get("PATH", None)
|
| 193 |
+
if path is None:
|
| 194 |
+
try:
|
| 195 |
+
path = os.confstr("CS_PATH")
|
| 196 |
+
except (AttributeError, ValueError):
|
| 197 |
+
# os.confstr() or CS_PATH is not available
|
| 198 |
+
path = os.defpath
|
| 199 |
+
# bpo-35755: Don't use os.defpath if the PATH environment variable is
|
| 200 |
+
# set to an empty string
|
| 201 |
+
|
| 202 |
+
return path
|
| 203 |
+
|
| 204 |
+
scripts = Path(sysconfig.get_path("scripts"))
|
| 205 |
+
|
| 206 |
+
paths = []
|
| 207 |
+
for path in PATH_as_shutil_which_determines_it().split(os.pathsep):
|
| 208 |
+
p = Path(path)
|
| 209 |
+
try:
|
| 210 |
+
if not p.samefile(scripts):
|
| 211 |
+
paths.append(path)
|
| 212 |
+
except FileNotFoundError:
|
| 213 |
+
pass
|
| 214 |
+
|
| 215 |
+
path = os.pathsep.join(paths)
|
| 216 |
+
|
| 217 |
+
cli = shutil.which("keyring", path=path)
|
| 218 |
+
|
| 219 |
+
if cli:
|
| 220 |
+
logger.verbose("Keyring provider set: subprocess with executable %s", cli)
|
| 221 |
+
return KeyRingCliProvider(cli)
|
| 222 |
+
|
| 223 |
+
logger.verbose("Keyring provider set: disabled")
|
| 224 |
+
return KeyRingNullProvider()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class MultiDomainBasicAuth(AuthBase):
|
| 228 |
+
def __init__(
|
| 229 |
+
self,
|
| 230 |
+
prompting: bool = True,
|
| 231 |
+
index_urls: list[str] | None = None,
|
| 232 |
+
keyring_provider: str = "auto",
|
| 233 |
+
) -> None:
|
| 234 |
+
self.prompting = prompting
|
| 235 |
+
self.index_urls = index_urls
|
| 236 |
+
self.keyring_provider = keyring_provider
|
| 237 |
+
self.passwords: dict[str, AuthInfo] = {}
|
| 238 |
+
# When the user is prompted to enter credentials and keyring is
|
| 239 |
+
# available, we will offer to save them. If the user accepts,
|
| 240 |
+
# this value is set to the credentials they entered. After the
|
| 241 |
+
# request authenticates, the caller should call
|
| 242 |
+
# ``save_credentials`` to save these.
|
| 243 |
+
self._credentials_to_save: Credentials | None = None
|
| 244 |
+
|
| 245 |
+
@property
|
| 246 |
+
def keyring_provider(self) -> KeyRingBaseProvider:
|
| 247 |
+
return get_keyring_provider(self._keyring_provider)
|
| 248 |
+
|
| 249 |
+
@keyring_provider.setter
|
| 250 |
+
def keyring_provider(self, provider: str) -> None:
|
| 251 |
+
# The free function get_keyring_provider has been decorated with
|
| 252 |
+
# functools.cache. If an exception occurs in get_keyring_auth that
|
| 253 |
+
# cache will be cleared and keyring disabled, take that into account
|
| 254 |
+
# if you want to remove this indirection.
|
| 255 |
+
self._keyring_provider = provider
|
| 256 |
+
|
| 257 |
+
@property
|
| 258 |
+
def use_keyring(self) -> bool:
|
| 259 |
+
# We won't use keyring when --no-input is passed unless
|
| 260 |
+
# a specific provider is requested because it might require
|
| 261 |
+
# user interaction
|
| 262 |
+
return self.prompting or self._keyring_provider not in ["auto", "disabled"]
|
| 263 |
+
|
| 264 |
+
def _get_keyring_auth(
|
| 265 |
+
self,
|
| 266 |
+
url: str | None,
|
| 267 |
+
username: str | None,
|
| 268 |
+
) -> AuthInfo | None:
|
| 269 |
+
"""Return the tuple auth for a given url from keyring."""
|
| 270 |
+
# Do nothing if no url was provided
|
| 271 |
+
if not url:
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
try:
|
| 275 |
+
return self.keyring_provider.get_auth_info(url, username)
|
| 276 |
+
except Exception as exc:
|
| 277 |
+
# Log the full exception (with stacktrace) at debug, so it'll only
|
| 278 |
+
# show up when running in verbose mode.
|
| 279 |
+
logger.debug("Keyring is skipped due to an exception", exc_info=True)
|
| 280 |
+
# Always log a shortened version of the exception.
|
| 281 |
+
logger.warning(
|
| 282 |
+
"Keyring is skipped due to an exception: %s",
|
| 283 |
+
str(exc),
|
| 284 |
+
)
|
| 285 |
+
global KEYRING_DISABLED
|
| 286 |
+
KEYRING_DISABLED = True
|
| 287 |
+
get_keyring_provider.cache_clear()
|
| 288 |
+
return None
|
| 289 |
+
|
| 290 |
+
def _get_index_url(self, url: str) -> str | None:
|
| 291 |
+
"""Return the original index URL matching the requested URL.
|
| 292 |
+
|
| 293 |
+
Cached or dynamically generated credentials may work against
|
| 294 |
+
the original index URL rather than just the netloc.
|
| 295 |
+
|
| 296 |
+
The provided url should have had its username and password
|
| 297 |
+
removed already. If the original index url had credentials then
|
| 298 |
+
they will be included in the return value.
|
| 299 |
+
|
| 300 |
+
Returns None if no matching index was found, or if --no-index
|
| 301 |
+
was specified by the user.
|
| 302 |
+
"""
|
| 303 |
+
if not url or not self.index_urls:
|
| 304 |
+
return None
|
| 305 |
+
|
| 306 |
+
url = remove_auth_from_url(url).rstrip("/") + "/"
|
| 307 |
+
parsed_url = urllib.parse.urlsplit(url)
|
| 308 |
+
|
| 309 |
+
candidates = []
|
| 310 |
+
|
| 311 |
+
for index in self.index_urls:
|
| 312 |
+
index = index.rstrip("/") + "/"
|
| 313 |
+
parsed_index = urllib.parse.urlsplit(remove_auth_from_url(index))
|
| 314 |
+
if parsed_url == parsed_index:
|
| 315 |
+
return index
|
| 316 |
+
|
| 317 |
+
if parsed_url.netloc != parsed_index.netloc:
|
| 318 |
+
continue
|
| 319 |
+
|
| 320 |
+
candidate = urllib.parse.urlsplit(index)
|
| 321 |
+
candidates.append(candidate)
|
| 322 |
+
|
| 323 |
+
if not candidates:
|
| 324 |
+
return None
|
| 325 |
+
|
| 326 |
+
candidates.sort(
|
| 327 |
+
reverse=True,
|
| 328 |
+
key=lambda candidate: commonprefix(
|
| 329 |
+
[
|
| 330 |
+
parsed_url.path,
|
| 331 |
+
candidate.path,
|
| 332 |
+
]
|
| 333 |
+
).rfind("/"),
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
return urllib.parse.urlunsplit(candidates[0])
|
| 337 |
+
|
| 338 |
+
def _get_new_credentials(
|
| 339 |
+
self,
|
| 340 |
+
original_url: str,
|
| 341 |
+
*,
|
| 342 |
+
allow_netrc: bool = True,
|
| 343 |
+
allow_keyring: bool = False,
|
| 344 |
+
) -> AuthInfo:
|
| 345 |
+
"""Find and return credentials for the specified URL."""
|
| 346 |
+
# Split the credentials and netloc from the url.
|
| 347 |
+
url, netloc, url_user_password = split_auth_netloc_from_url(
|
| 348 |
+
original_url,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# Start with the credentials embedded in the url
|
| 352 |
+
username, password = url_user_password
|
| 353 |
+
if username is not None and password is not None:
|
| 354 |
+
logger.debug("Found credentials in url for %s", netloc)
|
| 355 |
+
return url_user_password
|
| 356 |
+
|
| 357 |
+
# Find a matching index url for this request
|
| 358 |
+
index_url = self._get_index_url(url)
|
| 359 |
+
if index_url:
|
| 360 |
+
# Split the credentials from the url.
|
| 361 |
+
index_info = split_auth_netloc_from_url(index_url)
|
| 362 |
+
if index_info:
|
| 363 |
+
index_url, _, index_url_user_password = index_info
|
| 364 |
+
logger.debug("Found index url %s", index_url)
|
| 365 |
+
|
| 366 |
+
# If an index URL was found, try its embedded credentials
|
| 367 |
+
if index_url and index_url_user_password[0] is not None:
|
| 368 |
+
username, password = index_url_user_password
|
| 369 |
+
if username is not None and password is not None:
|
| 370 |
+
logger.debug("Found credentials in index url for %s", netloc)
|
| 371 |
+
return index_url_user_password
|
| 372 |
+
|
| 373 |
+
# Get creds from netrc if we still don't have them
|
| 374 |
+
if allow_netrc:
|
| 375 |
+
netrc_auth = get_netrc_auth(original_url)
|
| 376 |
+
if netrc_auth:
|
| 377 |
+
logger.debug("Found credentials in netrc for %s", netloc)
|
| 378 |
+
return netrc_auth
|
| 379 |
+
|
| 380 |
+
# If we don't have a password and keyring is available, use it.
|
| 381 |
+
if allow_keyring:
|
| 382 |
+
# The index url is more specific than the netloc, so try it first
|
| 383 |
+
# fmt: off
|
| 384 |
+
kr_auth = (
|
| 385 |
+
self._get_keyring_auth(index_url, username) or
|
| 386 |
+
self._get_keyring_auth(netloc, username)
|
| 387 |
+
)
|
| 388 |
+
# fmt: on
|
| 389 |
+
if kr_auth:
|
| 390 |
+
logger.debug("Found credentials in keyring for %s", netloc)
|
| 391 |
+
return kr_auth
|
| 392 |
+
|
| 393 |
+
return username, password
|
| 394 |
+
|
| 395 |
+
def _get_url_and_credentials(
|
| 396 |
+
self, original_url: str
|
| 397 |
+
) -> tuple[str, str | None, str | None]:
|
| 398 |
+
"""Return the credentials to use for the provided URL.
|
| 399 |
+
|
| 400 |
+
If allowed, netrc and keyring may be used to obtain the
|
| 401 |
+
correct credentials.
|
| 402 |
+
|
| 403 |
+
Returns (url_without_credentials, username, password). Note
|
| 404 |
+
that even if the original URL contains credentials, this
|
| 405 |
+
function may return a different username and password.
|
| 406 |
+
"""
|
| 407 |
+
url, netloc, _ = split_auth_netloc_from_url(original_url)
|
| 408 |
+
|
| 409 |
+
# Try to get credentials from original url
|
| 410 |
+
username, password = self._get_new_credentials(original_url)
|
| 411 |
+
|
| 412 |
+
# If credentials not found, use any stored credentials for this netloc.
|
| 413 |
+
# Do this if either the username or the password is missing.
|
| 414 |
+
# This accounts for the situation in which the user has specified
|
| 415 |
+
# the username in the index url, but the password comes from keyring.
|
| 416 |
+
if (username is None or password is None) and netloc in self.passwords:
|
| 417 |
+
un, pw = self.passwords[netloc]
|
| 418 |
+
# It is possible that the cached credentials are for a different username,
|
| 419 |
+
# in which case the cache should be ignored.
|
| 420 |
+
if username is None or username == un:
|
| 421 |
+
username, password = un, pw
|
| 422 |
+
|
| 423 |
+
if username is not None or password is not None:
|
| 424 |
+
# Convert the username and password if they're None, so that
|
| 425 |
+
# this netloc will show up as "cached" in the conditional above.
|
| 426 |
+
# Further, HTTPBasicAuth doesn't accept None, so it makes sense to
|
| 427 |
+
# cache the value that is going to be used.
|
| 428 |
+
username = username or ""
|
| 429 |
+
password = password or ""
|
| 430 |
+
|
| 431 |
+
# Store any acquired credentials.
|
| 432 |
+
self.passwords[netloc] = (username, password)
|
| 433 |
+
|
| 434 |
+
assert (
|
| 435 |
+
# Credentials were found
|
| 436 |
+
(username is not None and password is not None)
|
| 437 |
+
# Credentials were not found
|
| 438 |
+
or (username is None and password is None)
|
| 439 |
+
), f"Could not load credentials from url: {original_url}"
|
| 440 |
+
|
| 441 |
+
return url, username, password
|
| 442 |
+
|
| 443 |
+
def __call__(self, req: PreparedRequest) -> PreparedRequest:
|
| 444 |
+
# Get credentials for this request
|
| 445 |
+
assert req.url is not None
|
| 446 |
+
url, username, password = self._get_url_and_credentials(req.url)
|
| 447 |
+
|
| 448 |
+
# Set the url of the request to the url without any credentials
|
| 449 |
+
req.url = url
|
| 450 |
+
|
| 451 |
+
if username is not None and password is not None:
|
| 452 |
+
# Send the basic auth with this request
|
| 453 |
+
req = HTTPBasicAuth(username, password)(req)
|
| 454 |
+
|
| 455 |
+
# Attach a hook to handle 401 responses
|
| 456 |
+
req.register_hook("response", self.handle_401)
|
| 457 |
+
|
| 458 |
+
return req
|
| 459 |
+
|
| 460 |
+
# Factored out to allow for easy patching in tests
|
| 461 |
+
def _prompt_for_password(self, netloc: str) -> tuple[str | None, str | None, bool]:
|
| 462 |
+
username = ask_input(f"User for {netloc}: ") if self.prompting else None
|
| 463 |
+
if not username:
|
| 464 |
+
return None, None, False
|
| 465 |
+
if self.use_keyring:
|
| 466 |
+
auth = self._get_keyring_auth(netloc, username)
|
| 467 |
+
if auth and auth[0] is not None and auth[1] is not None:
|
| 468 |
+
return auth[0], auth[1], False
|
| 469 |
+
password = ask_password("Password: ")
|
| 470 |
+
return username, password, True
|
| 471 |
+
|
| 472 |
+
# Factored out to allow for easy patching in tests
|
| 473 |
+
def _should_save_password_to_keyring(self) -> bool:
|
| 474 |
+
if (
|
| 475 |
+
not self.prompting
|
| 476 |
+
or not self.use_keyring
|
| 477 |
+
or not self.keyring_provider.has_keyring
|
| 478 |
+
):
|
| 479 |
+
return False
|
| 480 |
+
return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y"
|
| 481 |
+
|
| 482 |
+
def handle_401(self, resp: Response, **kwargs: Any) -> Response:
|
| 483 |
+
# We only care about 401 responses, anything else we want to just
|
| 484 |
+
# pass through the actual response
|
| 485 |
+
if resp.status_code != 401:
|
| 486 |
+
return resp
|
| 487 |
+
|
| 488 |
+
username, password = None, None
|
| 489 |
+
|
| 490 |
+
# Query the keyring for credentials:
|
| 491 |
+
if self.use_keyring:
|
| 492 |
+
username, password = self._get_new_credentials(
|
| 493 |
+
resp.url,
|
| 494 |
+
allow_netrc=False,
|
| 495 |
+
allow_keyring=True,
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
# We are not able to prompt the user so simply return the response
|
| 499 |
+
if not self.prompting and not username and not password:
|
| 500 |
+
return resp
|
| 501 |
+
|
| 502 |
+
parsed = urllib.parse.urlparse(resp.url)
|
| 503 |
+
|
| 504 |
+
# Prompt the user for a new username and password
|
| 505 |
+
save = False
|
| 506 |
+
if not username and not password:
|
| 507 |
+
username, password, save = self._prompt_for_password(parsed.netloc)
|
| 508 |
+
|
| 509 |
+
# Store the new username and password to use for future requests
|
| 510 |
+
self._credentials_to_save = None
|
| 511 |
+
if username is not None and password is not None:
|
| 512 |
+
self.passwords[parsed.netloc] = (username, password)
|
| 513 |
+
|
| 514 |
+
# Prompt to save the password to keyring
|
| 515 |
+
if save and self._should_save_password_to_keyring():
|
| 516 |
+
self._credentials_to_save = Credentials(
|
| 517 |
+
url=parsed.netloc,
|
| 518 |
+
username=username,
|
| 519 |
+
password=password,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# Consume content and release the original connection to allow our new
|
| 523 |
+
# request to reuse the same one.
|
| 524 |
+
# The result of the assignment isn't used, it's just needed to consume
|
| 525 |
+
# the content.
|
| 526 |
+
_ = resp.content
|
| 527 |
+
resp.raw.release_conn()
|
| 528 |
+
|
| 529 |
+
# Add our new username and password to the request
|
| 530 |
+
req = HTTPBasicAuth(username or "", password or "")(resp.request)
|
| 531 |
+
req.register_hook("response", self.warn_on_401)
|
| 532 |
+
|
| 533 |
+
# On successful request, save the credentials that were used to
|
| 534 |
+
# keyring. (Note that if the user responded "no" above, this member
|
| 535 |
+
# is not set and nothing will be saved.)
|
| 536 |
+
if self._credentials_to_save:
|
| 537 |
+
req.register_hook("response", self.save_credentials)
|
| 538 |
+
|
| 539 |
+
# Send our new request
|
| 540 |
+
new_resp = resp.connection.send(req, **kwargs)
|
| 541 |
+
new_resp.history.append(resp)
|
| 542 |
+
|
| 543 |
+
return new_resp
|
| 544 |
+
|
| 545 |
+
def warn_on_401(self, resp: Response, **kwargs: Any) -> None:
|
| 546 |
+
"""Response callback to warn about incorrect credentials."""
|
| 547 |
+
if resp.status_code == 401:
|
| 548 |
+
logger.warning(
|
| 549 |
+
"401 Error, Credentials not correct for %s",
|
| 550 |
+
resp.request.url,
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
def save_credentials(self, resp: Response, **kwargs: Any) -> None:
|
| 554 |
+
"""Response callback to save credentials on success."""
|
| 555 |
+
assert (
|
| 556 |
+
self.keyring_provider.has_keyring
|
| 557 |
+
), "should never reach here without keyring"
|
| 558 |
+
|
| 559 |
+
creds = self._credentials_to_save
|
| 560 |
+
self._credentials_to_save = None
|
| 561 |
+
if creds and resp.status_code < 400:
|
| 562 |
+
try:
|
| 563 |
+
logger.info("Saving credentials to keyring")
|
| 564 |
+
self.keyring_provider.save_auth_info(
|
| 565 |
+
creds.url, creds.username, creds.password
|
| 566 |
+
)
|
| 567 |
+
except Exception:
|
| 568 |
+
logger.exception("Failed to save credentials")
|
.venv/lib/python3.12/site-packages/pip/_internal/network/cache.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HTTP cache implementation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
from collections.abc import Generator
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from typing import Any, BinaryIO, Callable
|
| 11 |
+
|
| 12 |
+
from pip._vendor.cachecontrol.cache import SeparateBodyBaseCache
|
| 13 |
+
from pip._vendor.cachecontrol.caches import SeparateBodyFileCache
|
| 14 |
+
from pip._vendor.requests.models import Response
|
| 15 |
+
|
| 16 |
+
from pip._internal.utils.filesystem import (
|
| 17 |
+
adjacent_tmp_file,
|
| 18 |
+
copy_directory_permissions,
|
| 19 |
+
replace,
|
| 20 |
+
)
|
| 21 |
+
from pip._internal.utils.misc import ensure_dir
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def is_from_cache(response: Response) -> bool:
|
| 25 |
+
return getattr(response, "from_cache", False)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@contextmanager
|
| 29 |
+
def suppressed_cache_errors() -> Generator[None, None, None]:
|
| 30 |
+
"""If we can't access the cache then we can just skip caching and process
|
| 31 |
+
requests as if caching wasn't enabled.
|
| 32 |
+
"""
|
| 33 |
+
try:
|
| 34 |
+
yield
|
| 35 |
+
except OSError:
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class SafeFileCache(SeparateBodyBaseCache):
|
| 40 |
+
"""
|
| 41 |
+
A file based cache which is safe to use even when the target directory may
|
| 42 |
+
not be accessible or writable.
|
| 43 |
+
|
| 44 |
+
There is a race condition when two processes try to write and/or read the
|
| 45 |
+
same entry at the same time, since each entry consists of two separate
|
| 46 |
+
files (https://github.com/psf/cachecontrol/issues/324). We therefore have
|
| 47 |
+
additional logic that makes sure that both files to be present before
|
| 48 |
+
returning an entry; this fixes the read side of the race condition.
|
| 49 |
+
|
| 50 |
+
For the write side, we assume that the server will only ever return the
|
| 51 |
+
same data for the same URL, which ought to be the case for files pip is
|
| 52 |
+
downloading. PyPI does not have a mechanism to swap out a wheel for
|
| 53 |
+
another wheel, for example. If this assumption is not true, the
|
| 54 |
+
CacheControl issue will need to be fixed.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(self, directory: str) -> None:
|
| 58 |
+
assert directory is not None, "Cache directory must not be None."
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.directory = directory
|
| 61 |
+
|
| 62 |
+
def _get_cache_path(self, name: str) -> str:
|
| 63 |
+
# From cachecontrol.caches.file_cache.FileCache._fn, brought into our
|
| 64 |
+
# class for backwards-compatibility and to avoid using a non-public
|
| 65 |
+
# method.
|
| 66 |
+
hashed = SeparateBodyFileCache.encode(name)
|
| 67 |
+
parts = list(hashed[:5]) + [hashed]
|
| 68 |
+
return os.path.join(self.directory, *parts)
|
| 69 |
+
|
| 70 |
+
def get(self, key: str) -> bytes | None:
|
| 71 |
+
# The cache entry is only valid if both metadata and body exist.
|
| 72 |
+
metadata_path = self._get_cache_path(key)
|
| 73 |
+
body_path = metadata_path + ".body"
|
| 74 |
+
if not (os.path.exists(metadata_path) and os.path.exists(body_path)):
|
| 75 |
+
return None
|
| 76 |
+
with suppressed_cache_errors():
|
| 77 |
+
with open(metadata_path, "rb") as f:
|
| 78 |
+
return f.read()
|
| 79 |
+
|
| 80 |
+
def _write_to_file(self, path: str, writer_func: Callable[[BinaryIO], Any]) -> None:
|
| 81 |
+
"""Common file writing logic with proper permissions and atomic replacement."""
|
| 82 |
+
with suppressed_cache_errors():
|
| 83 |
+
ensure_dir(os.path.dirname(path))
|
| 84 |
+
|
| 85 |
+
with adjacent_tmp_file(path) as f:
|
| 86 |
+
writer_func(f)
|
| 87 |
+
# Inherit the read/write permissions of the cache directory
|
| 88 |
+
# to enable multi-user cache use-cases.
|
| 89 |
+
copy_directory_permissions(self.directory, f)
|
| 90 |
+
|
| 91 |
+
replace(f.name, path)
|
| 92 |
+
|
| 93 |
+
def _write(self, path: str, data: bytes) -> None:
|
| 94 |
+
self._write_to_file(path, lambda f: f.write(data))
|
| 95 |
+
|
| 96 |
+
def _write_from_io(self, path: str, source_file: BinaryIO) -> None:
|
| 97 |
+
self._write_to_file(path, lambda f: shutil.copyfileobj(source_file, f))
|
| 98 |
+
|
| 99 |
+
def set(
|
| 100 |
+
self, key: str, value: bytes, expires: int | datetime | None = None
|
| 101 |
+
) -> None:
|
| 102 |
+
path = self._get_cache_path(key)
|
| 103 |
+
self._write(path, value)
|
| 104 |
+
|
| 105 |
+
def delete(self, key: str) -> None:
|
| 106 |
+
path = self._get_cache_path(key)
|
| 107 |
+
with suppressed_cache_errors():
|
| 108 |
+
os.remove(path)
|
| 109 |
+
with suppressed_cache_errors():
|
| 110 |
+
os.remove(path + ".body")
|
| 111 |
+
|
| 112 |
+
def get_body(self, key: str) -> BinaryIO | None:
|
| 113 |
+
# The cache entry is only valid if both metadata and body exist.
|
| 114 |
+
metadata_path = self._get_cache_path(key)
|
| 115 |
+
body_path = metadata_path + ".body"
|
| 116 |
+
if not (os.path.exists(metadata_path) and os.path.exists(body_path)):
|
| 117 |
+
return None
|
| 118 |
+
with suppressed_cache_errors():
|
| 119 |
+
return open(body_path, "rb")
|
| 120 |
+
|
| 121 |
+
def set_body(self, key: str, body: bytes) -> None:
|
| 122 |
+
path = self._get_cache_path(key) + ".body"
|
| 123 |
+
self._write(path, body)
|
| 124 |
+
|
| 125 |
+
def set_body_from_io(self, key: str, body_file: BinaryIO) -> None:
|
| 126 |
+
"""Set the body of the cache entry from a file object."""
|
| 127 |
+
path = self._get_cache_path(key) + ".body"
|
| 128 |
+
self._write_from_io(path, body_file)
|
.venv/lib/python3.12/site-packages/pip/_internal/network/download.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download files with progress indicators."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import email.message
|
| 6 |
+
import logging
|
| 7 |
+
import mimetypes
|
| 8 |
+
import os
|
| 9 |
+
from collections.abc import Iterable, Mapping
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from http import HTTPStatus
|
| 12 |
+
from typing import BinaryIO
|
| 13 |
+
|
| 14 |
+
from pip._vendor.requests import PreparedRequest
|
| 15 |
+
from pip._vendor.requests.models import Response
|
| 16 |
+
from pip._vendor.urllib3 import HTTPResponse as URLlib3Response
|
| 17 |
+
from pip._vendor.urllib3._collections import HTTPHeaderDict
|
| 18 |
+
from pip._vendor.urllib3.exceptions import ReadTimeoutError
|
| 19 |
+
|
| 20 |
+
from pip._internal.cli.progress_bars import BarType, get_download_progress_renderer
|
| 21 |
+
from pip._internal.exceptions import IncompleteDownloadError, NetworkConnectionError
|
| 22 |
+
from pip._internal.models.index import PyPI
|
| 23 |
+
from pip._internal.models.link import Link
|
| 24 |
+
from pip._internal.network.cache import SafeFileCache, is_from_cache
|
| 25 |
+
from pip._internal.network.session import CacheControlAdapter, PipSession
|
| 26 |
+
from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
|
| 27 |
+
from pip._internal.utils.misc import format_size, redact_auth_from_url, splitext
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _get_http_response_size(resp: Response) -> int | None:
|
| 33 |
+
try:
|
| 34 |
+
return int(resp.headers["content-length"])
|
| 35 |
+
except (ValueError, KeyError, TypeError):
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _get_http_response_etag_or_last_modified(resp: Response) -> str | None:
|
| 40 |
+
"""
|
| 41 |
+
Return either the ETag or Last-Modified header (or None if neither exists).
|
| 42 |
+
The return value can be used in an If-Range header.
|
| 43 |
+
"""
|
| 44 |
+
return resp.headers.get("etag", resp.headers.get("last-modified"))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _log_download(
|
| 48 |
+
resp: Response,
|
| 49 |
+
link: Link,
|
| 50 |
+
progress_bar: BarType,
|
| 51 |
+
total_length: int | None,
|
| 52 |
+
range_start: int | None = 0,
|
| 53 |
+
) -> Iterable[bytes]:
|
| 54 |
+
if link.netloc == PyPI.file_storage_domain:
|
| 55 |
+
url = link.show_url
|
| 56 |
+
else:
|
| 57 |
+
url = link.url_without_fragment
|
| 58 |
+
|
| 59 |
+
logged_url = redact_auth_from_url(url)
|
| 60 |
+
|
| 61 |
+
if total_length:
|
| 62 |
+
if range_start:
|
| 63 |
+
logged_url = (
|
| 64 |
+
f"{logged_url} ({format_size(range_start)}/{format_size(total_length)})"
|
| 65 |
+
)
|
| 66 |
+
else:
|
| 67 |
+
logged_url = f"{logged_url} ({format_size(total_length)})"
|
| 68 |
+
|
| 69 |
+
if is_from_cache(resp):
|
| 70 |
+
logger.info("Using cached %s", logged_url)
|
| 71 |
+
elif range_start:
|
| 72 |
+
logger.info("Resuming download %s", logged_url)
|
| 73 |
+
else:
|
| 74 |
+
logger.info("Downloading %s", logged_url)
|
| 75 |
+
|
| 76 |
+
if logger.getEffectiveLevel() > logging.INFO:
|
| 77 |
+
show_progress = False
|
| 78 |
+
elif is_from_cache(resp):
|
| 79 |
+
show_progress = False
|
| 80 |
+
elif not total_length:
|
| 81 |
+
show_progress = True
|
| 82 |
+
elif total_length > (512 * 1024):
|
| 83 |
+
show_progress = True
|
| 84 |
+
else:
|
| 85 |
+
show_progress = False
|
| 86 |
+
|
| 87 |
+
chunks = response_chunks(resp)
|
| 88 |
+
|
| 89 |
+
if not show_progress:
|
| 90 |
+
return chunks
|
| 91 |
+
|
| 92 |
+
renderer = get_download_progress_renderer(
|
| 93 |
+
bar_type=progress_bar, size=total_length, initial_progress=range_start
|
| 94 |
+
)
|
| 95 |
+
return renderer(chunks)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def sanitize_content_filename(filename: str) -> str:
|
| 99 |
+
"""
|
| 100 |
+
Sanitize the "filename" value from a Content-Disposition header.
|
| 101 |
+
"""
|
| 102 |
+
return os.path.basename(filename)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def parse_content_disposition(content_disposition: str, default_filename: str) -> str:
|
| 106 |
+
"""
|
| 107 |
+
Parse the "filename" value from a Content-Disposition header, and
|
| 108 |
+
return the default filename if the result is empty.
|
| 109 |
+
"""
|
| 110 |
+
m = email.message.Message()
|
| 111 |
+
m["content-type"] = content_disposition
|
| 112 |
+
filename = m.get_param("filename")
|
| 113 |
+
if filename:
|
| 114 |
+
# We need to sanitize the filename to prevent directory traversal
|
| 115 |
+
# in case the filename contains ".." path parts.
|
| 116 |
+
filename = sanitize_content_filename(str(filename))
|
| 117 |
+
return filename or default_filename
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _get_http_response_filename(resp: Response, link: Link) -> str:
|
| 121 |
+
"""Get an ideal filename from the given HTTP response, falling back to
|
| 122 |
+
the link filename if not provided.
|
| 123 |
+
"""
|
| 124 |
+
filename = link.filename # fallback
|
| 125 |
+
# Have a look at the Content-Disposition header for a better guess
|
| 126 |
+
content_disposition = resp.headers.get("content-disposition")
|
| 127 |
+
if content_disposition:
|
| 128 |
+
filename = parse_content_disposition(content_disposition, filename)
|
| 129 |
+
ext: str | None = splitext(filename)[1]
|
| 130 |
+
if not ext:
|
| 131 |
+
ext = mimetypes.guess_extension(resp.headers.get("content-type", ""))
|
| 132 |
+
if ext:
|
| 133 |
+
filename += ext
|
| 134 |
+
if not ext and link.url != resp.url:
|
| 135 |
+
ext = os.path.splitext(resp.url)[1]
|
| 136 |
+
if ext:
|
| 137 |
+
filename += ext
|
| 138 |
+
return filename
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@dataclass
|
| 142 |
+
class _FileDownload:
|
| 143 |
+
"""Stores the state of a single link download."""
|
| 144 |
+
|
| 145 |
+
link: Link
|
| 146 |
+
output_file: BinaryIO
|
| 147 |
+
size: int | None
|
| 148 |
+
bytes_received: int = 0
|
| 149 |
+
reattempts: int = 0
|
| 150 |
+
|
| 151 |
+
def is_incomplete(self) -> bool:
|
| 152 |
+
return bool(self.size is not None and self.bytes_received < self.size)
|
| 153 |
+
|
| 154 |
+
def write_chunk(self, data: bytes) -> None:
|
| 155 |
+
self.bytes_received += len(data)
|
| 156 |
+
self.output_file.write(data)
|
| 157 |
+
|
| 158 |
+
def reset_file(self) -> None:
|
| 159 |
+
"""Delete any saved data and reset progress to zero."""
|
| 160 |
+
self.output_file.seek(0)
|
| 161 |
+
self.output_file.truncate()
|
| 162 |
+
self.bytes_received = 0
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class Downloader:
|
| 166 |
+
def __init__(
|
| 167 |
+
self,
|
| 168 |
+
session: PipSession,
|
| 169 |
+
progress_bar: BarType,
|
| 170 |
+
) -> None:
|
| 171 |
+
self._session = session
|
| 172 |
+
self._progress_bar = progress_bar
|
| 173 |
+
self._resume_retries = session.resume_retries
|
| 174 |
+
assert (
|
| 175 |
+
self._resume_retries >= 0
|
| 176 |
+
), "Number of max resume retries must be bigger or equal to zero"
|
| 177 |
+
|
| 178 |
+
def batch(
|
| 179 |
+
self, links: Iterable[Link], location: str
|
| 180 |
+
) -> Iterable[tuple[Link, tuple[str, str]]]:
|
| 181 |
+
"""Convenience method to download multiple links."""
|
| 182 |
+
for link in links:
|
| 183 |
+
filepath, content_type = self(link, location)
|
| 184 |
+
yield link, (filepath, content_type)
|
| 185 |
+
|
| 186 |
+
def __call__(self, link: Link, location: str) -> tuple[str, str]:
|
| 187 |
+
"""Download a link and save it under location."""
|
| 188 |
+
resp = self._http_get(link)
|
| 189 |
+
download_size = _get_http_response_size(resp)
|
| 190 |
+
|
| 191 |
+
filepath = os.path.join(location, _get_http_response_filename(resp, link))
|
| 192 |
+
with open(filepath, "wb") as content_file:
|
| 193 |
+
download = _FileDownload(link, content_file, download_size)
|
| 194 |
+
self._process_response(download, resp)
|
| 195 |
+
if download.is_incomplete():
|
| 196 |
+
self._attempt_resumes_or_redownloads(download, resp)
|
| 197 |
+
|
| 198 |
+
content_type = resp.headers.get("Content-Type", "")
|
| 199 |
+
return filepath, content_type
|
| 200 |
+
|
| 201 |
+
def _process_response(self, download: _FileDownload, resp: Response) -> None:
|
| 202 |
+
"""Download and save chunks from a response."""
|
| 203 |
+
chunks = _log_download(
|
| 204 |
+
resp,
|
| 205 |
+
download.link,
|
| 206 |
+
self._progress_bar,
|
| 207 |
+
download.size,
|
| 208 |
+
range_start=download.bytes_received,
|
| 209 |
+
)
|
| 210 |
+
try:
|
| 211 |
+
for chunk in chunks:
|
| 212 |
+
download.write_chunk(chunk)
|
| 213 |
+
except ReadTimeoutError as e:
|
| 214 |
+
# If the download size is not known, then give up downloading the file.
|
| 215 |
+
if download.size is None:
|
| 216 |
+
raise e
|
| 217 |
+
|
| 218 |
+
logger.warning("Connection timed out while downloading.")
|
| 219 |
+
|
| 220 |
+
def _attempt_resumes_or_redownloads(
|
| 221 |
+
self, download: _FileDownload, first_resp: Response
|
| 222 |
+
) -> None:
|
| 223 |
+
"""Attempt to resume/restart the download if connection was dropped."""
|
| 224 |
+
|
| 225 |
+
while download.reattempts < self._resume_retries and download.is_incomplete():
|
| 226 |
+
assert download.size is not None
|
| 227 |
+
download.reattempts += 1
|
| 228 |
+
logger.warning(
|
| 229 |
+
"Attempting to resume incomplete download (%s/%s, attempt %d)",
|
| 230 |
+
format_size(download.bytes_received),
|
| 231 |
+
format_size(download.size),
|
| 232 |
+
download.reattempts,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
try:
|
| 236 |
+
resume_resp = self._http_get_resume(download, should_match=first_resp)
|
| 237 |
+
# Fallback: if the server responded with 200 (i.e., the file has
|
| 238 |
+
# since been modified or range requests are unsupported) or any
|
| 239 |
+
# other unexpected status, restart the download from the beginning.
|
| 240 |
+
must_restart = resume_resp.status_code != HTTPStatus.PARTIAL_CONTENT
|
| 241 |
+
if must_restart:
|
| 242 |
+
download.reset_file()
|
| 243 |
+
download.size = _get_http_response_size(resume_resp)
|
| 244 |
+
first_resp = resume_resp
|
| 245 |
+
|
| 246 |
+
self._process_response(download, resume_resp)
|
| 247 |
+
except (ConnectionError, ReadTimeoutError, OSError):
|
| 248 |
+
continue
|
| 249 |
+
|
| 250 |
+
# No more resume attempts. Raise an error if the download is still incomplete.
|
| 251 |
+
if download.is_incomplete():
|
| 252 |
+
os.remove(download.output_file.name)
|
| 253 |
+
raise IncompleteDownloadError(download)
|
| 254 |
+
|
| 255 |
+
# If we successfully completed the download via resume, manually cache it
|
| 256 |
+
# as a complete response to enable future caching
|
| 257 |
+
if download.reattempts > 0:
|
| 258 |
+
self._cache_resumed_download(download, first_resp)
|
| 259 |
+
|
| 260 |
+
def _cache_resumed_download(
|
| 261 |
+
self, download: _FileDownload, original_response: Response
|
| 262 |
+
) -> None:
|
| 263 |
+
"""
|
| 264 |
+
Manually cache a file that was successfully downloaded via resume retries.
|
| 265 |
+
|
| 266 |
+
cachecontrol doesn't cache 206 (Partial Content) responses, since they
|
| 267 |
+
are not complete files. This method manually adds the final file to the
|
| 268 |
+
cache as though it was downloaded in a single request, so that future
|
| 269 |
+
requests can use the cache.
|
| 270 |
+
"""
|
| 271 |
+
url = download.link.url_without_fragment
|
| 272 |
+
adapter = self._session.get_adapter(url)
|
| 273 |
+
|
| 274 |
+
# Check if the adapter is the CacheControlAdapter (i.e. caching is enabled)
|
| 275 |
+
if not isinstance(adapter, CacheControlAdapter):
|
| 276 |
+
logger.debug(
|
| 277 |
+
"Skipping resume download caching: no cache controller for %s", url
|
| 278 |
+
)
|
| 279 |
+
return
|
| 280 |
+
|
| 281 |
+
# Check SafeFileCache is being used
|
| 282 |
+
assert isinstance(
|
| 283 |
+
adapter.cache, SafeFileCache
|
| 284 |
+
), "separate body cache not in use!"
|
| 285 |
+
|
| 286 |
+
synthetic_request = PreparedRequest()
|
| 287 |
+
synthetic_request.prepare(method="GET", url=url, headers={})
|
| 288 |
+
|
| 289 |
+
synthetic_response_headers = HTTPHeaderDict()
|
| 290 |
+
for key, value in original_response.headers.items():
|
| 291 |
+
if key.lower() not in ["content-range", "content-length"]:
|
| 292 |
+
synthetic_response_headers[key] = value
|
| 293 |
+
synthetic_response_headers["content-length"] = str(download.size)
|
| 294 |
+
|
| 295 |
+
synthetic_response = URLlib3Response(
|
| 296 |
+
body="",
|
| 297 |
+
headers=synthetic_response_headers,
|
| 298 |
+
status=200,
|
| 299 |
+
preload_content=False,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
# Save metadata and then stream the file contents to cache.
|
| 303 |
+
cache_url = adapter.controller.cache_url(url)
|
| 304 |
+
metadata_blob = adapter.controller.serializer.dumps(
|
| 305 |
+
synthetic_request, synthetic_response, b""
|
| 306 |
+
)
|
| 307 |
+
adapter.cache.set(cache_url, metadata_blob)
|
| 308 |
+
download.output_file.flush()
|
| 309 |
+
with open(download.output_file.name, "rb") as f:
|
| 310 |
+
adapter.cache.set_body_from_io(cache_url, f)
|
| 311 |
+
|
| 312 |
+
logger.debug(
|
| 313 |
+
"Cached resumed download as complete response for future use: %s", url
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
def _http_get_resume(
|
| 317 |
+
self, download: _FileDownload, should_match: Response
|
| 318 |
+
) -> Response:
|
| 319 |
+
"""Issue a HTTP range request to resume the download."""
|
| 320 |
+
# To better understand the download resumption logic, see the mdn web docs:
|
| 321 |
+
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Range_requests
|
| 322 |
+
headers = HEADERS.copy()
|
| 323 |
+
headers["Range"] = f"bytes={download.bytes_received}-"
|
| 324 |
+
# If possible, use a conditional range request to avoid corrupted
|
| 325 |
+
# downloads caused by the remote file changing in-between.
|
| 326 |
+
if identifier := _get_http_response_etag_or_last_modified(should_match):
|
| 327 |
+
headers["If-Range"] = identifier
|
| 328 |
+
return self._http_get(download.link, headers)
|
| 329 |
+
|
| 330 |
+
def _http_get(self, link: Link, headers: Mapping[str, str] = HEADERS) -> Response:
|
| 331 |
+
target_url = link.url_without_fragment
|
| 332 |
+
try:
|
| 333 |
+
resp = self._session.get(target_url, headers=headers, stream=True)
|
| 334 |
+
raise_for_status(resp)
|
| 335 |
+
except NetworkConnectionError as e:
|
| 336 |
+
assert e.response is not None
|
| 337 |
+
logger.critical(
|
| 338 |
+
"HTTP error %s while getting %s", e.response.status_code, link
|
| 339 |
+
)
|
| 340 |
+
raise
|
| 341 |
+
return resp
|