plucksquire commited on
Commit
03e0734
·
verified ·
1 Parent(s): 34ef17a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/Lib/site-packages/_virtualenv.py +102 -0
  2. .venv/Lib/site-packages/pip-23.2.1.virtualenv +0 -0
  3. .venv/Lib/site-packages/pip/__init__.py +13 -0
  4. .venv/Lib/site-packages/pip/__main__.py +24 -0
  5. .venv/Lib/site-packages/pip/_internal/metadata/__init__.py +127 -0
  6. .venv/Lib/site-packages/pip/_internal/metadata/_json.py +84 -0
  7. .venv/Lib/site-packages/pip/_internal/metadata/importlib/_compat.py +55 -0
  8. .venv/Lib/site-packages/pip/_internal/metadata/importlib/_dists.py +224 -0
  9. .venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py +188 -0
  10. .venv/Lib/site-packages/pip/_internal/metadata/pkg_resources.py +270 -0
  11. .venv/Lib/site-packages/pip/_internal/models/__init__.py +2 -0
  12. .venv/Lib/site-packages/pip/_internal/models/target_python.py +110 -0
  13. .venv/Lib/site-packages/pip/_internal/models/wheel.py +92 -0
  14. .venv/Lib/site-packages/pip/_internal/network/__init__.py +2 -0
  15. .venv/Lib/site-packages/pip/_internal/network/auth.py +561 -0
  16. .venv/Lib/site-packages/pip/_internal/network/cache.py +69 -0
  17. .venv/Lib/site-packages/pip/_internal/network/download.py +186 -0
  18. .venv/Lib/site-packages/pip/_internal/network/lazy_wheel.py +210 -0
  19. .venv/Lib/site-packages/pip/_internal/network/session.py +519 -0
  20. .venv/Lib/site-packages/pip/_internal/network/utils.py +96 -0
  21. .venv/Lib/site-packages/pip/_internal/network/xmlrpc.py +60 -0
  22. .venv/Lib/site-packages/pip/_internal/operations/__init__.py +0 -0
  23. .venv/Lib/site-packages/pip/_internal/operations/build/__init__.py +0 -0
  24. .venv/Lib/site-packages/pip/_internal/operations/build/build_tracker.py +124 -0
  25. .venv/Lib/site-packages/pip/_internal/operations/build/metadata.py +39 -0
  26. .venv/Lib/site-packages/pip/_internal/operations/build/metadata_editable.py +41 -0
  27. .venv/Lib/site-packages/pip/_internal/operations/build/metadata_legacy.py +74 -0
  28. .venv/Lib/site-packages/pip/_internal/operations/build/wheel.py +37 -0
  29. .venv/Lib/site-packages/pip/_internal/operations/build/wheel_editable.py +46 -0
  30. .venv/Lib/site-packages/pip/_internal/operations/build/wheel_legacy.py +102 -0
  31. .venv/Lib/site-packages/pip/_internal/operations/check.py +187 -0
  32. .venv/Lib/site-packages/pip/_internal/operations/freeze.py +255 -0
  33. .venv/Lib/site-packages/pip/_internal/operations/install/__init__.py +2 -0
  34. .venv/Lib/site-packages/pip/_internal/operations/install/editable_legacy.py +46 -0
  35. .venv/Lib/site-packages/pip/_internal/operations/install/wheel.py +740 -0
  36. .venv/Lib/site-packages/pip/_internal/operations/prepare.py +743 -0
  37. .venv/Lib/site-packages/pip/_internal/req/__init__.py +92 -0
  38. .venv/Lib/site-packages/pip/_internal/req/constructors.py +506 -0
  39. .venv/Lib/site-packages/pip/_internal/req/req_file.py +552 -0
  40. .venv/Lib/site-packages/pip/_internal/req/req_install.py +874 -0
  41. .venv/Lib/site-packages/pip/_internal/req/req_set.py +119 -0
  42. .venv/Lib/site-packages/pip/_internal/req/req_uninstall.py +650 -0
  43. .venv/Lib/site-packages/pip/_internal/resolution/__init__.py +0 -0
  44. .venv/Lib/site-packages/pip/_internal/resolution/base.py +20 -0
  45. .venv/Lib/site-packages/pip/_internal/resolution/legacy/__init__.py +0 -0
  46. .venv/Lib/site-packages/pip/_internal/resolution/legacy/resolver.py +600 -0
  47. .venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__init__.py +0 -0
  48. .venv/Lib/site-packages/pip/_internal/resolution/resolvelib/base.py +141 -0
  49. .venv/Lib/site-packages/pip/_internal/resolution/resolvelib/candidates.py +555 -0
  50. .venv/Lib/site-packages/pip/_internal/resolution/resolvelib/factory.py +730 -0
.venv/Lib/site-packages/_virtualenv.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Patches that are applied at runtime to the virtual environment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from contextlib import suppress
8
+
9
+ VIRTUALENV_PATCH_FILE = os.path.join(__file__)
10
+
11
+
12
+ def patch_dist(dist):
13
+ """
14
+ Distutils allows user to configure some arguments via a configuration file:
15
+ https://docs.python.org/3/install/index.html#distutils-configuration-files.
16
+
17
+ Some of this arguments though don't make sense in context of the virtual environment files, let's fix them up.
18
+ """ # noqa: D205
19
+ # we cannot allow some install config as that would get packages installed outside of the virtual environment
20
+ old_parse_config_files = dist.Distribution.parse_config_files
21
+
22
+ def parse_config_files(self, *args, **kwargs):
23
+ result = old_parse_config_files(self, *args, **kwargs)
24
+ install = self.get_option_dict("install")
25
+
26
+ if "prefix" in install: # the prefix governs where to install the libraries
27
+ install["prefix"] = VIRTUALENV_PATCH_FILE, os.path.abspath(sys.prefix)
28
+ for base in ("purelib", "platlib", "headers", "scripts", "data"):
29
+ key = f"install_{base}"
30
+ if key in install: # do not allow global configs to hijack venv paths
31
+ install.pop(key, None)
32
+ return result
33
+
34
+ dist.Distribution.parse_config_files = parse_config_files
35
+
36
+
37
+ # Import hook that patches some modules to ignore configuration values that break package installation in case
38
+ # of virtual environments.
39
+ _DISTUTILS_PATCH = "distutils.dist", "setuptools.dist"
40
+ # https://docs.python.org/3/library/importlib.html#setting-up-an-importer
41
+
42
+
43
+ class _Finder:
44
+ """A meta path finder that allows patching the imported distutils modules."""
45
+
46
+ fullname = None
47
+
48
+ # lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup,
49
+ # because there are gevent-based applications that need to be first to import threading by themselves.
50
+ # See https://github.com/pypa/virtualenv/issues/1895 for details.
51
+ lock = [] # noqa: RUF012
52
+
53
+ def find_spec(self, fullname, path, target=None): # noqa: ARG002
54
+ if fullname in _DISTUTILS_PATCH and self.fullname is None:
55
+ # initialize lock[0] lazily
56
+ if len(self.lock) == 0:
57
+ import threading
58
+
59
+ lock = threading.Lock()
60
+ # there is possibility that two threads T1 and T2 are simultaneously running into find_spec,
61
+ # observing .lock as empty, and further going into hereby initialization. However due to the GIL,
62
+ # list.append() operation is atomic and this way only one of the threads will "win" to put the lock
63
+ # - that every thread will use - into .lock[0].
64
+ # https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe
65
+ self.lock.append(lock)
66
+
67
+ from functools import partial
68
+ from importlib.util import find_spec
69
+
70
+ with self.lock[0]:
71
+ self.fullname = fullname
72
+ try:
73
+ spec = find_spec(fullname, path)
74
+ if spec is not None:
75
+ # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work
76
+ is_new_api = hasattr(spec.loader, "exec_module")
77
+ func_name = "exec_module" if is_new_api else "load_module"
78
+ old = getattr(spec.loader, func_name)
79
+ func = self.exec_module if is_new_api else self.load_module
80
+ if old is not func:
81
+ with suppress(AttributeError): # C-Extension loaders are r/o such as zipimporter with <3.7
82
+ setattr(spec.loader, func_name, partial(func, old))
83
+ return spec
84
+ finally:
85
+ self.fullname = None
86
+ return None
87
+
88
+ @staticmethod
89
+ def exec_module(old, module):
90
+ old(module)
91
+ if module.__name__ in _DISTUTILS_PATCH:
92
+ patch_dist(module)
93
+
94
+ @staticmethod
95
+ def load_module(old, name):
96
+ module = old(name)
97
+ if module.__name__ in _DISTUTILS_PATCH:
98
+ patch_dist(module)
99
+ return module
100
+
101
+
102
+ sys.meta_path.insert(0, _Finder())
.venv/Lib/site-packages/pip-23.2.1.virtualenv ADDED
File without changes
.venv/Lib/site-packages/pip/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ __version__ = "23.2.1"
4
+
5
+
6
+ def main(args: Optional[List[str]] = None) -> int:
7
+ """This is an internal API only meant for use by pip's own console scripts.
8
+
9
+ For additional details, see https://github.com/pypa/pip/issues/7498.
10
+ """
11
+ from pip._internal.utils.entrypoints import _wrapper
12
+
13
+ return _wrapper(args)
.venv/Lib/site-packages/pip/__main__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ # Remove '' and current working directory from the first entry
5
+ # of sys.path, if present to avoid using current directory
6
+ # in pip commands check, freeze, install, list and show,
7
+ # when invoked as python -m pip <command>
8
+ if sys.path[0] in ("", os.getcwd()):
9
+ sys.path.pop(0)
10
+
11
+ # If we are running from a wheel, add the wheel to sys.path
12
+ # This allows the usage python pip-*.whl/pip install pip-*.whl
13
+ if __package__ == "":
14
+ # __file__ is pip-*.whl/pip/__main__.py
15
+ # first dirname call strips of '/__main__.py', second strips off '/pip'
16
+ # Resulting path is the name of the wheel itself
17
+ # Add that to sys.path so we can import pip
18
+ path = os.path.dirname(os.path.dirname(__file__))
19
+ sys.path.insert(0, path)
20
+
21
+ if __name__ == "__main__":
22
+ from pip._internal.cli.main import main as _main
23
+
24
+ sys.exit(_main())
.venv/Lib/site-packages/pip/_internal/metadata/__init__.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import functools
3
+ import os
4
+ import sys
5
+ from typing import TYPE_CHECKING, List, Optional, Type, cast
6
+
7
+ from pip._internal.utils.misc import strtobool
8
+
9
+ from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
10
+
11
+ if TYPE_CHECKING:
12
+ from typing import Protocol
13
+ else:
14
+ Protocol = object
15
+
16
+ __all__ = [
17
+ "BaseDistribution",
18
+ "BaseEnvironment",
19
+ "FilesystemWheel",
20
+ "MemoryWheel",
21
+ "Wheel",
22
+ "get_default_environment",
23
+ "get_environment",
24
+ "get_wheel_distribution",
25
+ "select_backend",
26
+ ]
27
+
28
+
29
+ def _should_use_importlib_metadata() -> bool:
30
+ """Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.
31
+
32
+ By default, pip uses ``importlib.metadata`` on Python 3.11+, and
33
+ ``pkg_resourcess`` otherwise. This can be overridden by a couple of ways:
34
+
35
+ * If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it
36
+ dictates whether ``importlib.metadata`` is used, regardless of Python
37
+ version.
38
+ * On Python 3.11+, Python distributors can patch ``importlib.metadata``
39
+ to add a global constant ``_PIP_USE_IMPORTLIB_METADATA = False``. This
40
+ makes pip use ``pkg_resources`` (unless the user set the aforementioned
41
+ environment variable to *True*).
42
+ """
43
+ with contextlib.suppress(KeyError, ValueError):
44
+ return bool(strtobool(os.environ["_PIP_USE_IMPORTLIB_METADATA"]))
45
+ if sys.version_info < (3, 11):
46
+ return False
47
+ import importlib.metadata
48
+
49
+ return bool(getattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA", True))
50
+
51
+
52
+ class Backend(Protocol):
53
+ Distribution: Type[BaseDistribution]
54
+ Environment: Type[BaseEnvironment]
55
+
56
+
57
+ @functools.lru_cache(maxsize=None)
58
+ def select_backend() -> Backend:
59
+ if _should_use_importlib_metadata():
60
+ from . import importlib
61
+
62
+ return cast(Backend, importlib)
63
+ from . import pkg_resources
64
+
65
+ return cast(Backend, pkg_resources)
66
+
67
+
68
+ def get_default_environment() -> BaseEnvironment:
69
+ """Get the default representation for the current environment.
70
+
71
+ This returns an Environment instance from the chosen backend. The default
72
+ Environment instance should be built from ``sys.path`` and may use caching
73
+ to share instance state accorss calls.
74
+ """
75
+ return select_backend().Environment.default()
76
+
77
+
78
+ def get_environment(paths: Optional[List[str]]) -> BaseEnvironment:
79
+ """Get a representation of the environment specified by ``paths``.
80
+
81
+ This returns an Environment instance from the chosen backend based on the
82
+ given import paths. The backend must build a fresh instance representing
83
+ the state of installed distributions when this function is called.
84
+ """
85
+ return select_backend().Environment.from_paths(paths)
86
+
87
+
88
+ def get_directory_distribution(directory: str) -> BaseDistribution:
89
+ """Get the distribution metadata representation in the specified directory.
90
+
91
+ This returns a Distribution instance from the chosen backend based on
92
+ the given on-disk ``.dist-info`` directory.
93
+ """
94
+ return select_backend().Distribution.from_directory(directory)
95
+
96
+
97
+ def get_wheel_distribution(wheel: Wheel, canonical_name: str) -> BaseDistribution:
98
+ """Get the representation of the specified wheel's distribution metadata.
99
+
100
+ This returns a Distribution instance from the chosen backend based on
101
+ the given wheel's ``.dist-info`` directory.
102
+
103
+ :param canonical_name: Normalized project name of the given wheel.
104
+ """
105
+ return select_backend().Distribution.from_wheel(wheel, canonical_name)
106
+
107
+
108
+ def get_metadata_distribution(
109
+ metadata_contents: bytes,
110
+ filename: str,
111
+ canonical_name: str,
112
+ ) -> BaseDistribution:
113
+ """Get the dist representation of the specified METADATA file contents.
114
+
115
+ This returns a Distribution instance from the chosen backend sourced from the data
116
+ in `metadata_contents`.
117
+
118
+ :param metadata_contents: Contents of a METADATA file within a dist, or one served
119
+ via PEP 658.
120
+ :param filename: Filename for the dist this metadata represents.
121
+ :param canonical_name: Normalized project name of the given dist.
122
+ """
123
+ return select_backend().Distribution.from_metadata_file_contents(
124
+ metadata_contents,
125
+ filename,
126
+ canonical_name,
127
+ )
.venv/Lib/site-packages/pip/_internal/metadata/_json.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Extracted from https://github.com/pfmoore/pkg_metadata
2
+
3
+ from email.header import Header, decode_header, make_header
4
+ from email.message import Message
5
+ from typing import Any, Dict, List, Union
6
+
7
+ METADATA_FIELDS = [
8
+ # Name, Multiple-Use
9
+ ("Metadata-Version", False),
10
+ ("Name", False),
11
+ ("Version", False),
12
+ ("Dynamic", True),
13
+ ("Platform", True),
14
+ ("Supported-Platform", True),
15
+ ("Summary", False),
16
+ ("Description", False),
17
+ ("Description-Content-Type", False),
18
+ ("Keywords", False),
19
+ ("Home-page", False),
20
+ ("Download-URL", False),
21
+ ("Author", False),
22
+ ("Author-email", False),
23
+ ("Maintainer", False),
24
+ ("Maintainer-email", False),
25
+ ("License", False),
26
+ ("Classifier", True),
27
+ ("Requires-Dist", True),
28
+ ("Requires-Python", False),
29
+ ("Requires-External", True),
30
+ ("Project-URL", True),
31
+ ("Provides-Extra", True),
32
+ ("Provides-Dist", True),
33
+ ("Obsoletes-Dist", True),
34
+ ]
35
+
36
+
37
+ def json_name(field: str) -> str:
38
+ return field.lower().replace("-", "_")
39
+
40
+
41
+ def msg_to_json(msg: Message) -> Dict[str, Any]:
42
+ """Convert a Message object into a JSON-compatible dictionary."""
43
+
44
+ def sanitise_header(h: Union[Header, str]) -> str:
45
+ if isinstance(h, Header):
46
+ chunks = []
47
+ for bytes, encoding in decode_header(h):
48
+ if encoding == "unknown-8bit":
49
+ try:
50
+ # See if UTF-8 works
51
+ bytes.decode("utf-8")
52
+ encoding = "utf-8"
53
+ except UnicodeDecodeError:
54
+ # If not, latin1 at least won't fail
55
+ encoding = "latin1"
56
+ chunks.append((bytes, encoding))
57
+ return str(make_header(chunks))
58
+ return str(h)
59
+
60
+ result = {}
61
+ for field, multi in METADATA_FIELDS:
62
+ if field not in msg:
63
+ continue
64
+ key = json_name(field)
65
+ if multi:
66
+ value: Union[str, List[str]] = [
67
+ sanitise_header(v) for v in msg.get_all(field)
68
+ ]
69
+ else:
70
+ value = sanitise_header(msg.get(field))
71
+ if key == "keywords":
72
+ # Accept both comma-separated and space-separated
73
+ # forms, for better compatibility with old data.
74
+ if "," in value:
75
+ value = [v.strip() for v in value.split(",")]
76
+ else:
77
+ value = value.split()
78
+ result[key] = value
79
+
80
+ payload = msg.get_payload()
81
+ if payload:
82
+ result["description"] = payload
83
+
84
+ return result
.venv/Lib/site-packages/pip/_internal/metadata/importlib/_compat.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ from typing import Any, Optional, Protocol, cast
3
+
4
+
5
+ class BadMetadata(ValueError):
6
+ def __init__(self, dist: importlib.metadata.Distribution, *, reason: str) -> None:
7
+ self.dist = dist
8
+ self.reason = reason
9
+
10
+ def __str__(self) -> str:
11
+ return f"Bad metadata in {self.dist} ({self.reason})"
12
+
13
+
14
+ class BasePath(Protocol):
15
+ """A protocol that various path objects conform.
16
+
17
+ This exists because importlib.metadata uses both ``pathlib.Path`` and
18
+ ``zipfile.Path``, and we need a common base for type hints (Union does not
19
+ work well since ``zipfile.Path`` is too new for our linter setup).
20
+
21
+ This does not mean to be exhaustive, but only contains things that present
22
+ in both classes *that we need*.
23
+ """
24
+
25
+ @property
26
+ def name(self) -> str:
27
+ raise NotImplementedError()
28
+
29
+ @property
30
+ def parent(self) -> "BasePath":
31
+ raise NotImplementedError()
32
+
33
+
34
+ def get_info_location(d: importlib.metadata.Distribution) -> Optional[BasePath]:
35
+ """Find the path to the distribution's metadata directory.
36
+
37
+ HACK: This relies on importlib.metadata's private ``_path`` attribute. Not
38
+ all distributions exist on disk, so importlib.metadata is correct to not
39
+ expose the attribute as public. But pip's code base is old and not as clean,
40
+ so we do this to avoid having to rewrite too many things. Hopefully we can
41
+ eliminate this some day.
42
+ """
43
+ return getattr(d, "_path", None)
44
+
45
+
46
+ def get_dist_name(dist: importlib.metadata.Distribution) -> str:
47
+ """Get the distribution's project name.
48
+
49
+ The ``name`` attribute is only available in Python 3.10 or later. We are
50
+ targeting exactly that, but Mypy does not know this.
51
+ """
52
+ name = cast(Any, dist).name
53
+ if not isinstance(name, str):
54
+ raise BadMetadata(dist, reason="invalid metadata entry 'name'")
55
+ return name
.venv/Lib/site-packages/pip/_internal/metadata/importlib/_dists.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import email.message
2
+ import importlib.metadata
3
+ import os
4
+ import pathlib
5
+ import zipfile
6
+ from typing import (
7
+ Collection,
8
+ Dict,
9
+ Iterable,
10
+ Iterator,
11
+ Mapping,
12
+ Optional,
13
+ Sequence,
14
+ cast,
15
+ )
16
+
17
+ from pip._vendor.packaging.requirements import Requirement
18
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
19
+ from pip._vendor.packaging.version import parse as parse_version
20
+
21
+ from pip._internal.exceptions import InvalidWheel, UnsupportedWheel
22
+ from pip._internal.metadata.base import (
23
+ BaseDistribution,
24
+ BaseEntryPoint,
25
+ DistributionVersion,
26
+ InfoPath,
27
+ Wheel,
28
+ )
29
+ from pip._internal.utils.misc import normalize_path
30
+ from pip._internal.utils.packaging import safe_extra
31
+ from pip._internal.utils.temp_dir import TempDirectory
32
+ from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file
33
+
34
+ from ._compat import BasePath, get_dist_name
35
+
36
+
37
+ class WheelDistribution(importlib.metadata.Distribution):
38
+ """An ``importlib.metadata.Distribution`` read from a wheel.
39
+
40
+ Although ``importlib.metadata.PathDistribution`` accepts ``zipfile.Path``,
41
+ its implementation is too "lazy" for pip's needs (we can't keep the ZipFile
42
+ handle open for the entire lifetime of the distribution object).
43
+
44
+ This implementation eagerly reads the entire metadata directory into the
45
+ memory instead, and operates from that.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ files: Mapping[pathlib.PurePosixPath, bytes],
51
+ info_location: pathlib.PurePosixPath,
52
+ ) -> None:
53
+ self._files = files
54
+ self.info_location = info_location
55
+
56
+ @classmethod
57
+ def from_zipfile(
58
+ cls,
59
+ zf: zipfile.ZipFile,
60
+ name: str,
61
+ location: str,
62
+ ) -> "WheelDistribution":
63
+ info_dir, _ = parse_wheel(zf, name)
64
+ paths = (
65
+ (name, pathlib.PurePosixPath(name.split("/", 1)[-1]))
66
+ for name in zf.namelist()
67
+ if name.startswith(f"{info_dir}/")
68
+ )
69
+ files = {
70
+ relpath: read_wheel_metadata_file(zf, fullpath)
71
+ for fullpath, relpath in paths
72
+ }
73
+ info_location = pathlib.PurePosixPath(location, info_dir)
74
+ return cls(files, info_location)
75
+
76
+ def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
77
+ # Only allow iterating through the metadata directory.
78
+ if pathlib.PurePosixPath(str(path)) in self._files:
79
+ return iter(self._files)
80
+ raise FileNotFoundError(path)
81
+
82
+ def read_text(self, filename: str) -> Optional[str]:
83
+ try:
84
+ data = self._files[pathlib.PurePosixPath(filename)]
85
+ except KeyError:
86
+ return None
87
+ try:
88
+ text = data.decode("utf-8")
89
+ except UnicodeDecodeError as e:
90
+ wheel = self.info_location.parent
91
+ error = f"Error decoding metadata for {wheel}: {e} in {filename} file"
92
+ raise UnsupportedWheel(error)
93
+ return text
94
+
95
+
96
+ class Distribution(BaseDistribution):
97
+ def __init__(
98
+ self,
99
+ dist: importlib.metadata.Distribution,
100
+ info_location: Optional[BasePath],
101
+ installed_location: Optional[BasePath],
102
+ ) -> None:
103
+ self._dist = dist
104
+ self._info_location = info_location
105
+ self._installed_location = installed_location
106
+
107
+ @classmethod
108
+ def from_directory(cls, directory: str) -> BaseDistribution:
109
+ info_location = pathlib.Path(directory)
110
+ dist = importlib.metadata.Distribution.at(info_location)
111
+ return cls(dist, info_location, info_location.parent)
112
+
113
+ @classmethod
114
+ def from_metadata_file_contents(
115
+ cls,
116
+ metadata_contents: bytes,
117
+ filename: str,
118
+ project_name: str,
119
+ ) -> BaseDistribution:
120
+ # Generate temp dir to contain the metadata file, and write the file contents.
121
+ temp_dir = pathlib.Path(
122
+ TempDirectory(kind="metadata", globally_managed=True).path
123
+ )
124
+ metadata_path = temp_dir / "METADATA"
125
+ metadata_path.write_bytes(metadata_contents)
126
+ # Construct dist pointing to the newly created directory.
127
+ dist = importlib.metadata.Distribution.at(metadata_path.parent)
128
+ return cls(dist, metadata_path.parent, None)
129
+
130
+ @classmethod
131
+ def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:
132
+ try:
133
+ with wheel.as_zipfile() as zf:
134
+ dist = WheelDistribution.from_zipfile(zf, name, wheel.location)
135
+ except zipfile.BadZipFile as e:
136
+ raise InvalidWheel(wheel.location, name) from e
137
+ except UnsupportedWheel as e:
138
+ raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
139
+ return cls(dist, dist.info_location, pathlib.PurePosixPath(wheel.location))
140
+
141
+ @property
142
+ def location(self) -> Optional[str]:
143
+ if self._info_location is None:
144
+ return None
145
+ return str(self._info_location.parent)
146
+
147
+ @property
148
+ def info_location(self) -> Optional[str]:
149
+ if self._info_location is None:
150
+ return None
151
+ return str(self._info_location)
152
+
153
+ @property
154
+ def installed_location(self) -> Optional[str]:
155
+ if self._installed_location is None:
156
+ return None
157
+ return normalize_path(str(self._installed_location))
158
+
159
+ def _get_dist_name_from_location(self) -> Optional[str]:
160
+ """Try to get the name from the metadata directory name.
161
+
162
+ This is much faster than reading metadata.
163
+ """
164
+ if self._info_location is None:
165
+ return None
166
+ stem, suffix = os.path.splitext(self._info_location.name)
167
+ if suffix not in (".dist-info", ".egg-info"):
168
+ return None
169
+ return stem.split("-", 1)[0]
170
+
171
+ @property
172
+ def canonical_name(self) -> NormalizedName:
173
+ name = self._get_dist_name_from_location() or get_dist_name(self._dist)
174
+ return canonicalize_name(name)
175
+
176
+ @property
177
+ def version(self) -> DistributionVersion:
178
+ return parse_version(self._dist.version)
179
+
180
+ def is_file(self, path: InfoPath) -> bool:
181
+ return self._dist.read_text(str(path)) is not None
182
+
183
+ def iter_distutils_script_names(self) -> Iterator[str]:
184
+ # A distutils installation is always "flat" (not in e.g. egg form), so
185
+ # if this distribution's info location is NOT a pathlib.Path (but e.g.
186
+ # zipfile.Path), it can never contain any distutils scripts.
187
+ if not isinstance(self._info_location, pathlib.Path):
188
+ return
189
+ for child in self._info_location.joinpath("scripts").iterdir():
190
+ yield child.name
191
+
192
+ def read_text(self, path: InfoPath) -> str:
193
+ content = self._dist.read_text(str(path))
194
+ if content is None:
195
+ raise FileNotFoundError(path)
196
+ return content
197
+
198
+ def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
199
+ # importlib.metadata's EntryPoint structure sasitfies BaseEntryPoint.
200
+ return self._dist.entry_points
201
+
202
+ def _metadata_impl(self) -> email.message.Message:
203
+ # From Python 3.10+, importlib.metadata declares PackageMetadata as the
204
+ # return type. This protocol is unfortunately a disaster now and misses
205
+ # a ton of fields that we need, including get() and get_payload(). We
206
+ # rely on the implementation that the object is actually a Message now,
207
+ # until upstream can improve the protocol. (python/cpython#94952)
208
+ return cast(email.message.Message, self._dist.metadata)
209
+
210
+ def iter_provided_extras(self) -> Iterable[str]:
211
+ return (
212
+ safe_extra(extra) for extra in self.metadata.get_all("Provides-Extra", [])
213
+ )
214
+
215
+ def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
216
+ contexts: Sequence[Dict[str, str]] = [{"extra": safe_extra(e)} for e in extras]
217
+ for req_string in self.metadata.get_all("Requires-Dist", []):
218
+ req = Requirement(req_string)
219
+ if not req.marker:
220
+ yield req
221
+ elif not extras and req.marker.evaluate({"extra": ""}):
222
+ yield req
223
+ elif any(req.marker.evaluate(context) for context in contexts):
224
+ yield req
.venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import importlib.metadata
3
+ import logging
4
+ import os
5
+ import pathlib
6
+ import sys
7
+ import zipfile
8
+ import zipimport
9
+ from typing import Iterator, List, Optional, Sequence, Set, Tuple
10
+
11
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
12
+
13
+ from pip._internal.metadata.base import BaseDistribution, BaseEnvironment
14
+ from pip._internal.models.wheel import Wheel
15
+ from pip._internal.utils.deprecation import deprecated
16
+ from pip._internal.utils.filetypes import WHEEL_EXTENSION
17
+
18
+ from ._compat import BadMetadata, BasePath, get_dist_name, get_info_location
19
+ from ._dists import Distribution
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def _looks_like_wheel(location: str) -> bool:
25
+ if not location.endswith(WHEEL_EXTENSION):
26
+ return False
27
+ if not os.path.isfile(location):
28
+ return False
29
+ if not Wheel.wheel_file_re.match(os.path.basename(location)):
30
+ return False
31
+ return zipfile.is_zipfile(location)
32
+
33
+
34
+ class _DistributionFinder:
35
+ """Finder to locate distributions.
36
+
37
+ The main purpose of this class is to memoize found distributions' names, so
38
+ only one distribution is returned for each package name. At lot of pip code
39
+ assumes this (because it is setuptools's behavior), and not doing the same
40
+ can potentially cause a distribution in lower precedence path to override a
41
+ higher precedence one if the caller is not careful.
42
+
43
+ Eventually we probably want to make it possible to see lower precedence
44
+ installations as well. It's useful feature, after all.
45
+ """
46
+
47
+ FoundResult = Tuple[importlib.metadata.Distribution, Optional[BasePath]]
48
+
49
+ def __init__(self) -> None:
50
+ self._found_names: Set[NormalizedName] = set()
51
+
52
+ def _find_impl(self, location: str) -> Iterator[FoundResult]:
53
+ """Find distributions in a location."""
54
+ # Skip looking inside a wheel. Since a package inside a wheel is not
55
+ # always valid (due to .data directories etc.), its .dist-info entry
56
+ # should not be considered an installed distribution.
57
+ if _looks_like_wheel(location):
58
+ return
59
+ # To know exactly where we find a distribution, we have to feed in the
60
+ # paths one by one, instead of dumping the list to importlib.metadata.
61
+ for dist in importlib.metadata.distributions(path=[location]):
62
+ info_location = get_info_location(dist)
63
+ try:
64
+ raw_name = get_dist_name(dist)
65
+ except BadMetadata as e:
66
+ logger.warning("Skipping %s due to %s", info_location, e.reason)
67
+ continue
68
+ normalized_name = canonicalize_name(raw_name)
69
+ if normalized_name in self._found_names:
70
+ continue
71
+ self._found_names.add(normalized_name)
72
+ yield dist, info_location
73
+
74
+ def find(self, location: str) -> Iterator[BaseDistribution]:
75
+ """Find distributions in a location.
76
+
77
+ The path can be either a directory, or a ZIP archive.
78
+ """
79
+ for dist, info_location in self._find_impl(location):
80
+ if info_location is None:
81
+ installed_location: Optional[BasePath] = None
82
+ else:
83
+ installed_location = info_location.parent
84
+ yield Distribution(dist, info_location, installed_location)
85
+
86
+ def find_linked(self, location: str) -> Iterator[BaseDistribution]:
87
+ """Read location in egg-link files and return distributions in there.
88
+
89
+ The path should be a directory; otherwise this returns nothing. This
90
+ follows how setuptools does this for compatibility. The first non-empty
91
+ line in the egg-link is read as a path (resolved against the egg-link's
92
+ containing directory if relative). Distributions found at that linked
93
+ location are returned.
94
+ """
95
+ path = pathlib.Path(location)
96
+ if not path.is_dir():
97
+ return
98
+ for child in path.iterdir():
99
+ if child.suffix != ".egg-link":
100
+ continue
101
+ with child.open() as f:
102
+ lines = (line.strip() for line in f)
103
+ target_rel = next((line for line in lines if line), "")
104
+ if not target_rel:
105
+ continue
106
+ target_location = str(path.joinpath(target_rel))
107
+ for dist, info_location in self._find_impl(target_location):
108
+ yield Distribution(dist, info_location, path)
109
+
110
+ def _find_eggs_in_dir(self, location: str) -> Iterator[BaseDistribution]:
111
+ from pip._vendor.pkg_resources import find_distributions
112
+
113
+ from pip._internal.metadata import pkg_resources as legacy
114
+
115
+ with os.scandir(location) as it:
116
+ for entry in it:
117
+ if not entry.name.endswith(".egg"):
118
+ continue
119
+ for dist in find_distributions(entry.path):
120
+ yield legacy.Distribution(dist)
121
+
122
+ def _find_eggs_in_zip(self, location: str) -> Iterator[BaseDistribution]:
123
+ from pip._vendor.pkg_resources import find_eggs_in_zip
124
+
125
+ from pip._internal.metadata import pkg_resources as legacy
126
+
127
+ try:
128
+ importer = zipimport.zipimporter(location)
129
+ except zipimport.ZipImportError:
130
+ return
131
+ for dist in find_eggs_in_zip(importer, location):
132
+ yield legacy.Distribution(dist)
133
+
134
+ def find_eggs(self, location: str) -> Iterator[BaseDistribution]:
135
+ """Find eggs in a location.
136
+
137
+ This actually uses the old *pkg_resources* backend. We likely want to
138
+ deprecate this so we can eventually remove the *pkg_resources*
139
+ dependency entirely. Before that, this should first emit a deprecation
140
+ warning for some versions when using the fallback since importing
141
+ *pkg_resources* is slow for those who don't need it.
142
+ """
143
+ if os.path.isdir(location):
144
+ yield from self._find_eggs_in_dir(location)
145
+ if zipfile.is_zipfile(location):
146
+ yield from self._find_eggs_in_zip(location)
147
+
148
+
149
+ @functools.lru_cache(maxsize=None) # Warn a distribution exactly once.
150
+ def _emit_egg_deprecation(location: Optional[str]) -> None:
151
+ deprecated(
152
+ reason=f"Loading egg at {location} is deprecated.",
153
+ replacement="to use pip for package installation.",
154
+ gone_in="23.3",
155
+ )
156
+
157
+
158
+ class Environment(BaseEnvironment):
159
+ def __init__(self, paths: Sequence[str]) -> None:
160
+ self._paths = paths
161
+
162
+ @classmethod
163
+ def default(cls) -> BaseEnvironment:
164
+ return cls(sys.path)
165
+
166
+ @classmethod
167
+ def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:
168
+ if paths is None:
169
+ return cls(sys.path)
170
+ return cls(paths)
171
+
172
+ def _iter_distributions(self) -> Iterator[BaseDistribution]:
173
+ finder = _DistributionFinder()
174
+ for location in self._paths:
175
+ yield from finder.find(location)
176
+ for dist in finder.find_eggs(location):
177
+ _emit_egg_deprecation(dist.location)
178
+ yield dist
179
+ # This must go last because that's how pkg_resources tie-breaks.
180
+ yield from finder.find_linked(location)
181
+
182
+ def get_distribution(self, name: str) -> Optional[BaseDistribution]:
183
+ matches = (
184
+ distribution
185
+ for distribution in self.iter_all_distributions()
186
+ if distribution.canonical_name == canonicalize_name(name)
187
+ )
188
+ return next(matches, None)
.venv/Lib/site-packages/pip/_internal/metadata/pkg_resources.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import email.message
2
+ import email.parser
3
+ import logging
4
+ import os
5
+ import zipfile
6
+ from typing import Collection, Iterable, Iterator, List, Mapping, NamedTuple, Optional
7
+
8
+ from pip._vendor import pkg_resources
9
+ from pip._vendor.packaging.requirements import Requirement
10
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
11
+ from pip._vendor.packaging.version import parse as parse_version
12
+
13
+ from pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel
14
+ from pip._internal.utils.egg_link import egg_link_path_from_location
15
+ from pip._internal.utils.misc import display_path, normalize_path
16
+ from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file
17
+
18
+ from .base import (
19
+ BaseDistribution,
20
+ BaseEntryPoint,
21
+ BaseEnvironment,
22
+ DistributionVersion,
23
+ InfoPath,
24
+ Wheel,
25
+ )
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ class EntryPoint(NamedTuple):
31
+ name: str
32
+ value: str
33
+ group: str
34
+
35
+
36
+ class InMemoryMetadata:
37
+ """IMetadataProvider that reads metadata files from a dictionary.
38
+
39
+ This also maps metadata decoding exceptions to our internal exception type.
40
+ """
41
+
42
+ def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:
43
+ self._metadata = metadata
44
+ self._wheel_name = wheel_name
45
+
46
+ def has_metadata(self, name: str) -> bool:
47
+ return name in self._metadata
48
+
49
+ def get_metadata(self, name: str) -> str:
50
+ try:
51
+ return self._metadata[name].decode()
52
+ except UnicodeDecodeError as e:
53
+ # Augment the default error with the origin of the file.
54
+ raise UnsupportedWheel(
55
+ f"Error decoding metadata for {self._wheel_name}: {e} in {name} file"
56
+ )
57
+
58
+ def get_metadata_lines(self, name: str) -> Iterable[str]:
59
+ return pkg_resources.yield_lines(self.get_metadata(name))
60
+
61
+ def metadata_isdir(self, name: str) -> bool:
62
+ return False
63
+
64
+ def metadata_listdir(self, name: str) -> List[str]:
65
+ return []
66
+
67
+ def run_script(self, script_name: str, namespace: str) -> None:
68
+ pass
69
+
70
+
71
+ class Distribution(BaseDistribution):
72
+ def __init__(self, dist: pkg_resources.Distribution) -> None:
73
+ self._dist = dist
74
+
75
+ @classmethod
76
+ def from_directory(cls, directory: str) -> BaseDistribution:
77
+ dist_dir = directory.rstrip(os.sep)
78
+
79
+ # Build a PathMetadata object, from path to metadata. :wink:
80
+ base_dir, dist_dir_name = os.path.split(dist_dir)
81
+ metadata = pkg_resources.PathMetadata(base_dir, dist_dir)
82
+
83
+ # Determine the correct Distribution object type.
84
+ if dist_dir.endswith(".egg-info"):
85
+ dist_cls = pkg_resources.Distribution
86
+ dist_name = os.path.splitext(dist_dir_name)[0]
87
+ else:
88
+ assert dist_dir.endswith(".dist-info")
89
+ dist_cls = pkg_resources.DistInfoDistribution
90
+ dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0]
91
+
92
+ dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata)
93
+ return cls(dist)
94
+
95
+ @classmethod
96
+ def from_metadata_file_contents(
97
+ cls,
98
+ metadata_contents: bytes,
99
+ filename: str,
100
+ project_name: str,
101
+ ) -> BaseDistribution:
102
+ metadata_dict = {
103
+ "METADATA": metadata_contents,
104
+ }
105
+ dist = pkg_resources.DistInfoDistribution(
106
+ location=filename,
107
+ metadata=InMemoryMetadata(metadata_dict, filename),
108
+ project_name=project_name,
109
+ )
110
+ return cls(dist)
111
+
112
+ @classmethod
113
+ def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:
114
+ try:
115
+ with wheel.as_zipfile() as zf:
116
+ info_dir, _ = parse_wheel(zf, name)
117
+ metadata_dict = {
118
+ path.split("/", 1)[-1]: read_wheel_metadata_file(zf, path)
119
+ for path in zf.namelist()
120
+ if path.startswith(f"{info_dir}/")
121
+ }
122
+ except zipfile.BadZipFile as e:
123
+ raise InvalidWheel(wheel.location, name) from e
124
+ except UnsupportedWheel as e:
125
+ raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
126
+ dist = pkg_resources.DistInfoDistribution(
127
+ location=wheel.location,
128
+ metadata=InMemoryMetadata(metadata_dict, wheel.location),
129
+ project_name=name,
130
+ )
131
+ return cls(dist)
132
+
133
+ @property
134
+ def location(self) -> Optional[str]:
135
+ return self._dist.location
136
+
137
+ @property
138
+ def installed_location(self) -> Optional[str]:
139
+ egg_link = egg_link_path_from_location(self.raw_name)
140
+ if egg_link:
141
+ location = egg_link
142
+ elif self.location:
143
+ location = self.location
144
+ else:
145
+ return None
146
+ return normalize_path(location)
147
+
148
+ @property
149
+ def info_location(self) -> Optional[str]:
150
+ return self._dist.egg_info
151
+
152
+ @property
153
+ def installed_by_distutils(self) -> bool:
154
+ # A distutils-installed distribution is provided by FileMetadata. This
155
+ # provider has a "path" attribute not present anywhere else. Not the
156
+ # best introspection logic, but pip has been doing this for a long time.
157
+ try:
158
+ return bool(self._dist._provider.path)
159
+ except AttributeError:
160
+ return False
161
+
162
+ @property
163
+ def canonical_name(self) -> NormalizedName:
164
+ return canonicalize_name(self._dist.project_name)
165
+
166
+ @property
167
+ def version(self) -> DistributionVersion:
168
+ return parse_version(self._dist.version)
169
+
170
+ def is_file(self, path: InfoPath) -> bool:
171
+ return self._dist.has_metadata(str(path))
172
+
173
+ def iter_distutils_script_names(self) -> Iterator[str]:
174
+ yield from self._dist.metadata_listdir("scripts")
175
+
176
+ def read_text(self, path: InfoPath) -> str:
177
+ name = str(path)
178
+ if not self._dist.has_metadata(name):
179
+ raise FileNotFoundError(name)
180
+ content = self._dist.get_metadata(name)
181
+ if content is None:
182
+ raise NoneMetadataError(self, name)
183
+ return content
184
+
185
+ def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
186
+ for group, entries in self._dist.get_entry_map().items():
187
+ for name, entry_point in entries.items():
188
+ name, _, value = str(entry_point).partition("=")
189
+ yield EntryPoint(name=name.strip(), value=value.strip(), group=group)
190
+
191
+ def _metadata_impl(self) -> email.message.Message:
192
+ """
193
+ :raises NoneMetadataError: if the distribution reports `has_metadata()`
194
+ True but `get_metadata()` returns None.
195
+ """
196
+ if isinstance(self._dist, pkg_resources.DistInfoDistribution):
197
+ metadata_name = "METADATA"
198
+ else:
199
+ metadata_name = "PKG-INFO"
200
+ try:
201
+ metadata = self.read_text(metadata_name)
202
+ except FileNotFoundError:
203
+ if self.location:
204
+ displaying_path = display_path(self.location)
205
+ else:
206
+ displaying_path = repr(self.location)
207
+ logger.warning("No metadata found in %s", displaying_path)
208
+ metadata = ""
209
+ feed_parser = email.parser.FeedParser()
210
+ feed_parser.feed(metadata)
211
+ return feed_parser.close()
212
+
213
+ def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
214
+ if extras: # pkg_resources raises on invalid extras, so we sanitize.
215
+ extras = frozenset(extras).intersection(self._dist.extras)
216
+ return self._dist.requires(extras)
217
+
218
+ def iter_provided_extras(self) -> Iterable[str]:
219
+ return self._dist.extras
220
+
221
+
222
+ class Environment(BaseEnvironment):
223
+ def __init__(self, ws: pkg_resources.WorkingSet) -> None:
224
+ self._ws = ws
225
+
226
+ @classmethod
227
+ def default(cls) -> BaseEnvironment:
228
+ return cls(pkg_resources.working_set)
229
+
230
+ @classmethod
231
+ def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:
232
+ return cls(pkg_resources.WorkingSet(paths))
233
+
234
+ def _iter_distributions(self) -> Iterator[BaseDistribution]:
235
+ for dist in self._ws:
236
+ yield Distribution(dist)
237
+
238
+ def _search_distribution(self, name: str) -> Optional[BaseDistribution]:
239
+ """Find a distribution matching the ``name`` in the environment.
240
+
241
+ This searches from *all* distributions available in the environment, to
242
+ match the behavior of ``pkg_resources.get_distribution()``.
243
+ """
244
+ canonical_name = canonicalize_name(name)
245
+ for dist in self.iter_all_distributions():
246
+ if dist.canonical_name == canonical_name:
247
+ return dist
248
+ return None
249
+
250
+ def get_distribution(self, name: str) -> Optional[BaseDistribution]:
251
+ # Search the distribution by looking through the working set.
252
+ dist = self._search_distribution(name)
253
+ if dist:
254
+ return dist
255
+
256
+ # If distribution could not be found, call working_set.require to
257
+ # update the working set, and try to find the distribution again.
258
+ # This might happen for e.g. when you install a package twice, once
259
+ # using setup.py develop and again using setup.py install. Now when
260
+ # running pip uninstall twice, the package gets removed from the
261
+ # working set in the first uninstall, so we have to populate the
262
+ # working set again so that pip knows about it and the packages gets
263
+ # picked up and is successfully uninstalled the second time too.
264
+ try:
265
+ # We didn't pass in any version specifiers, so this can never
266
+ # raise pkg_resources.VersionConflict.
267
+ self._ws.require(name)
268
+ except pkg_resources.DistributionNotFound:
269
+ return None
270
+ return self._search_distribution(name)
.venv/Lib/site-packages/pip/_internal/models/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """A package that contains models that represent entities.
2
+ """
.venv/Lib/site-packages/pip/_internal/models/target_python.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import List, Optional, Tuple
3
+
4
+ from pip._vendor.packaging.tags import Tag
5
+
6
+ from pip._internal.utils.compatibility_tags import get_supported, version_info_to_nodot
7
+ from pip._internal.utils.misc import normalize_version_info
8
+
9
+
10
+ class TargetPython:
11
+
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
+ ]
26
+
27
+ def __init__(
28
+ self,
29
+ platforms: Optional[List[str]] = None,
30
+ py_version_info: Optional[Tuple[int, ...]] = None,
31
+ abis: Optional[List[str]] = None,
32
+ implementation: Optional[str] = None,
33
+ ) -> None:
34
+ """
35
+ :param platforms: A list of strings or None. If None, searches for
36
+ packages that are supported by the current system. Otherwise, will
37
+ find packages that can be built on the platforms passed in. These
38
+ packages will only be downloaded for distribution: they will
39
+ not be built locally.
40
+ :param py_version_info: An optional tuple of ints representing the
41
+ Python version information to use (e.g. `sys.version_info[:3]`).
42
+ This can have length 1, 2, or 3 when provided.
43
+ :param abis: A list of strings or None. This is passed to
44
+ compatibility_tags.py's get_supported() function as is.
45
+ :param implementation: A string or None. This is passed to
46
+ compatibility_tags.py's get_supported() function as is.
47
+ """
48
+ # Store the given py_version_info for when we call get_supported().
49
+ self._given_py_version_info = py_version_info
50
+
51
+ if py_version_info is None:
52
+ py_version_info = sys.version_info[:3]
53
+ else:
54
+ py_version_info = normalize_version_info(py_version_info)
55
+
56
+ py_version = ".".join(map(str, py_version_info[:2]))
57
+
58
+ self.abis = abis
59
+ self.implementation = implementation
60
+ self.platforms = platforms
61
+ self.py_version = py_version
62
+ self.py_version_info = py_version_info
63
+
64
+ # This is used to cache the return value of get_tags().
65
+ self._valid_tags: Optional[List[Tag]] = None
66
+
67
+ def format_given(self) -> str:
68
+ """
69
+ Format the given, non-None attributes for display.
70
+ """
71
+ display_version = None
72
+ if self._given_py_version_info is not None:
73
+ display_version = ".".join(
74
+ str(part) for part in self._given_py_version_info
75
+ )
76
+
77
+ key_values = [
78
+ ("platforms", self.platforms),
79
+ ("version_info", display_version),
80
+ ("abis", self.abis),
81
+ ("implementation", self.implementation),
82
+ ]
83
+ return " ".join(
84
+ f"{key}={value!r}" for key, value in key_values if value is not None
85
+ )
86
+
87
+ def get_tags(self) -> List[Tag]:
88
+ """
89
+ Return the supported PEP 425 tags to check wheel candidates against.
90
+
91
+ The tags are returned in order of preference (most preferred first).
92
+ """
93
+ if self._valid_tags is None:
94
+ # Pass versions=None if no py_version_info was given since
95
+ # versions=None uses special default logic.
96
+ py_version_info = self._given_py_version_info
97
+ if py_version_info is None:
98
+ version = None
99
+ else:
100
+ version = version_info_to_nodot(py_version_info)
101
+
102
+ tags = get_supported(
103
+ version=version,
104
+ platforms=self.platforms,
105
+ abis=self.abis,
106
+ impl=self.implementation,
107
+ )
108
+ self._valid_tags = tags
109
+
110
+ return self._valid_tags
.venv/Lib/site-packages/pip/_internal/models/wheel.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Represents a wheel file and provides access to the various parts of the
2
+ name that have meaning.
3
+ """
4
+ import re
5
+ from typing import Dict, Iterable, List
6
+
7
+ from pip._vendor.packaging.tags import Tag
8
+
9
+ from pip._internal.exceptions import InvalidWheelFilename
10
+
11
+
12
+ class Wheel:
13
+ """A wheel file"""
14
+
15
+ wheel_file_re = re.compile(
16
+ r"""^(?P<namever>(?P<name>[^\s-]+?)-(?P<ver>[^\s-]*?))
17
+ ((-(?P<build>\d[^-]*?))?-(?P<pyver>[^\s-]+?)-(?P<abi>[^\s-]+?)-(?P<plat>[^\s-]+?)
18
+ \.whl|\.dist-info)$""",
19
+ re.VERBOSE,
20
+ )
21
+
22
+ def __init__(self, filename: str) -> None:
23
+ """
24
+ :raises InvalidWheelFilename: when the filename is invalid for a wheel
25
+ """
26
+ wheel_info = self.wheel_file_re.match(filename)
27
+ if not wheel_info:
28
+ raise InvalidWheelFilename(f"{filename} is not a valid wheel filename.")
29
+ self.filename = filename
30
+ self.name = wheel_info.group("name").replace("_", "-")
31
+ # we'll assume "_" means "-" due to wheel naming scheme
32
+ # (https://github.com/pypa/pip/issues/1150)
33
+ self.version = wheel_info.group("ver").replace("_", "-")
34
+ self.build_tag = wheel_info.group("build")
35
+ self.pyversions = wheel_info.group("pyver").split(".")
36
+ self.abis = wheel_info.group("abi").split(".")
37
+ self.plats = wheel_info.group("plat").split(".")
38
+
39
+ # All the tag combinations from this file
40
+ self.file_tags = {
41
+ Tag(x, y, z) for x in self.pyversions for y in self.abis for z in self.plats
42
+ }
43
+
44
+ def get_formatted_file_tags(self) -> List[str]:
45
+ """Return the wheel's tags as a sorted list of strings."""
46
+ return sorted(str(tag) for tag in self.file_tags)
47
+
48
+ def support_index_min(self, tags: List[Tag]) -> int:
49
+ """Return the lowest index that one of the wheel's file_tag combinations
50
+ achieves in the given list of supported tags.
51
+
52
+ For example, if there are 8 supported tags and one of the file tags
53
+ is first in the list, then return 0.
54
+
55
+ :param tags: the PEP 425 tags to check the wheel against, in order
56
+ with most preferred first.
57
+
58
+ :raises ValueError: If none of the wheel's file tags match one of
59
+ the supported tags.
60
+ """
61
+ try:
62
+ return next(i for i, t in enumerate(tags) if t in self.file_tags)
63
+ except StopIteration:
64
+ raise ValueError()
65
+
66
+ def find_most_preferred_tag(
67
+ self, tags: List[Tag], tag_to_priority: Dict[Tag, int]
68
+ ) -> int:
69
+ """Return the priority of the most preferred tag that one of the wheel's file
70
+ tag combinations achieves in the given list of supported tags using the given
71
+ tag_to_priority mapping, where lower priorities are more-preferred.
72
+
73
+ This is used in place of support_index_min in some cases in order to avoid
74
+ an expensive linear scan of a large list of tags.
75
+
76
+ :param tags: the PEP 425 tags to check the wheel against.
77
+ :param tag_to_priority: a mapping from tag to priority of that tag, where
78
+ lower is more preferred.
79
+
80
+ :raises ValueError: If none of the wheel's file tags match one of
81
+ the supported tags.
82
+ """
83
+ return min(
84
+ tag_to_priority[tag] for tag in self.file_tags if tag in tag_to_priority
85
+ )
86
+
87
+ def supported(self, tags: Iterable[Tag]) -> bool:
88
+ """Return whether the wheel is compatible with one of the given tags.
89
+
90
+ :param tags: the PEP 425 tags to check the wheel against.
91
+ """
92
+ return not self.file_tags.isdisjoint(tags)
.venv/Lib/site-packages/pip/_internal/network/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Contains purely network-related utilities.
2
+ """
.venv/Lib/site-packages/pip/_internal/network/auth.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import logging
7
+ import os
8
+ import shutil
9
+ import subprocess
10
+ import sysconfig
11
+ import typing
12
+ import urllib.parse
13
+ from abc import ABC, abstractmethod
14
+ from functools import lru_cache
15
+ from os.path import commonprefix
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, NamedTuple, Optional, Tuple
18
+
19
+ from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth
20
+ from pip._vendor.requests.models import Request, Response
21
+ from pip._vendor.requests.utils import get_netrc_auth
22
+
23
+ from pip._internal.utils.logging import getLogger
24
+ from pip._internal.utils.misc import (
25
+ ask,
26
+ ask_input,
27
+ ask_password,
28
+ remove_auth_from_url,
29
+ split_auth_netloc_from_url,
30
+ )
31
+ from pip._internal.vcs.versioncontrol import AuthInfo
32
+
33
+ logger = getLogger(__name__)
34
+
35
+ KEYRING_DISABLED = False
36
+
37
+
38
+ class Credentials(NamedTuple):
39
+ url: str
40
+ username: str
41
+ password: str
42
+
43
+
44
+ class KeyRingBaseProvider(ABC):
45
+ """Keyring base provider interface"""
46
+
47
+ has_keyring: bool
48
+
49
+ @abstractmethod
50
+ def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]:
51
+ ...
52
+
53
+ @abstractmethod
54
+ def save_auth_info(self, url: str, username: str, password: str) -> None:
55
+ ...
56
+
57
+
58
+ class KeyRingNullProvider(KeyRingBaseProvider):
59
+ """Keyring null provider"""
60
+
61
+ has_keyring = False
62
+
63
+ def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]:
64
+ return None
65
+
66
+ def save_auth_info(self, url: str, username: str, password: str) -> None:
67
+ return None
68
+
69
+
70
+ class KeyRingPythonProvider(KeyRingBaseProvider):
71
+ """Keyring interface which uses locally imported `keyring`"""
72
+
73
+ has_keyring = True
74
+
75
+ def __init__(self) -> None:
76
+ import keyring
77
+
78
+ self.keyring = keyring
79
+
80
+ def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]:
81
+ # Support keyring's get_credential interface which supports getting
82
+ # credentials without a username. This is only available for
83
+ # keyring>=15.2.0.
84
+ if hasattr(self.keyring, "get_credential"):
85
+ logger.debug("Getting credentials from keyring for %s", url)
86
+ cred = self.keyring.get_credential(url, username)
87
+ if cred is not None:
88
+ return cred.username, cred.password
89
+ return None
90
+
91
+ if username is not None:
92
+ logger.debug("Getting password from keyring for %s", url)
93
+ password = self.keyring.get_password(url, username)
94
+ if password:
95
+ return username, password
96
+ return None
97
+
98
+ def save_auth_info(self, url: str, username: str, password: str) -> None:
99
+ self.keyring.set_password(url, username, password)
100
+
101
+
102
+ class KeyRingCliProvider(KeyRingBaseProvider):
103
+ """Provider which uses `keyring` cli
104
+
105
+ Instead of calling the keyring package installed alongside pip
106
+ we call keyring on the command line which will enable pip to
107
+ use which ever installation of keyring is available first in
108
+ PATH.
109
+ """
110
+
111
+ has_keyring = True
112
+
113
+ def __init__(self, cmd: str) -> None:
114
+ self.keyring = cmd
115
+
116
+ def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]:
117
+ # This is the default implementation of keyring.get_credential
118
+ # https://github.com/jaraco/keyring/blob/97689324abcf01bd1793d49063e7ca01e03d7d07/keyring/backend.py#L134-L139
119
+ if username is not None:
120
+ password = self._get_password(url, username)
121
+ if password is not None:
122
+ return username, password
123
+ return None
124
+
125
+ def save_auth_info(self, url: str, username: str, password: str) -> None:
126
+ return self._set_password(url, username, password)
127
+
128
+ def _get_password(self, service_name: str, username: str) -> Optional[str]:
129
+ """Mirror the implementation of keyring.get_password using cli"""
130
+ if self.keyring is None:
131
+ return None
132
+
133
+ cmd = [self.keyring, "get", service_name, username]
134
+ env = os.environ.copy()
135
+ env["PYTHONIOENCODING"] = "utf-8"
136
+ res = subprocess.run(
137
+ cmd,
138
+ stdin=subprocess.DEVNULL,
139
+ stdout=subprocess.PIPE,
140
+ env=env,
141
+ )
142
+ if res.returncode:
143
+ return None
144
+ return res.stdout.decode("utf-8").strip(os.linesep)
145
+
146
+ def _set_password(self, service_name: str, username: str, password: str) -> None:
147
+ """Mirror the implementation of keyring.set_password using cli"""
148
+ if self.keyring is None:
149
+ return None
150
+ env = os.environ.copy()
151
+ env["PYTHONIOENCODING"] = "utf-8"
152
+ subprocess.run(
153
+ [self.keyring, "set", service_name, username],
154
+ input=f"{password}{os.linesep}".encode("utf-8"),
155
+ env=env,
156
+ check=True,
157
+ )
158
+ return None
159
+
160
+
161
+ @lru_cache(maxsize=None)
162
+ def get_keyring_provider(provider: str) -> KeyRingBaseProvider:
163
+ logger.verbose("Keyring provider requested: %s", provider)
164
+
165
+ # keyring has previously failed and been disabled
166
+ if KEYRING_DISABLED:
167
+ provider = "disabled"
168
+ if provider in ["import", "auto"]:
169
+ try:
170
+ impl = KeyRingPythonProvider()
171
+ logger.verbose("Keyring provider set: import")
172
+ return impl
173
+ except ImportError:
174
+ pass
175
+ except Exception as exc:
176
+ # In the event of an unexpected exception
177
+ # we should warn the user
178
+ msg = "Installed copy of keyring fails with exception %s"
179
+ if provider == "auto":
180
+ msg = msg + ", trying to find a keyring executable as a fallback"
181
+ logger.warning(msg, exc, exc_info=logger.isEnabledFor(logging.DEBUG))
182
+ if provider in ["subprocess", "auto"]:
183
+ cli = shutil.which("keyring")
184
+ if cli and cli.startswith(sysconfig.get_path("scripts")):
185
+ # all code within this function is stolen from shutil.which implementation
186
+ @typing.no_type_check
187
+ def PATH_as_shutil_which_determines_it() -> str:
188
+ path = os.environ.get("PATH", None)
189
+ if path is None:
190
+ try:
191
+ path = os.confstr("CS_PATH")
192
+ except (AttributeError, ValueError):
193
+ # os.confstr() or CS_PATH is not available
194
+ path = os.defpath
195
+ # bpo-35755: Don't use os.defpath if the PATH environment variable is
196
+ # set to an empty string
197
+
198
+ return path
199
+
200
+ scripts = Path(sysconfig.get_path("scripts"))
201
+
202
+ paths = []
203
+ for path in PATH_as_shutil_which_determines_it().split(os.pathsep):
204
+ p = Path(path)
205
+ try:
206
+ if not p.samefile(scripts):
207
+ paths.append(path)
208
+ except FileNotFoundError:
209
+ pass
210
+
211
+ path = os.pathsep.join(paths)
212
+
213
+ cli = shutil.which("keyring", path=path)
214
+
215
+ if cli:
216
+ logger.verbose("Keyring provider set: subprocess with executable %s", cli)
217
+ return KeyRingCliProvider(cli)
218
+
219
+ logger.verbose("Keyring provider set: disabled")
220
+ return KeyRingNullProvider()
221
+
222
+
223
+ class MultiDomainBasicAuth(AuthBase):
224
+ def __init__(
225
+ self,
226
+ prompting: bool = True,
227
+ index_urls: Optional[List[str]] = None,
228
+ keyring_provider: str = "auto",
229
+ ) -> None:
230
+ self.prompting = prompting
231
+ self.index_urls = index_urls
232
+ self.keyring_provider = keyring_provider # type: ignore[assignment]
233
+ self.passwords: Dict[str, AuthInfo] = {}
234
+ # When the user is prompted to enter credentials and keyring is
235
+ # available, we will offer to save them. If the user accepts,
236
+ # this value is set to the credentials they entered. After the
237
+ # request authenticates, the caller should call
238
+ # ``save_credentials`` to save these.
239
+ self._credentials_to_save: Optional[Credentials] = None
240
+
241
+ @property
242
+ def keyring_provider(self) -> KeyRingBaseProvider:
243
+ return get_keyring_provider(self._keyring_provider)
244
+
245
+ @keyring_provider.setter
246
+ def keyring_provider(self, provider: str) -> None:
247
+ # The free function get_keyring_provider has been decorated with
248
+ # functools.cache. If an exception occurs in get_keyring_auth that
249
+ # cache will be cleared and keyring disabled, take that into account
250
+ # if you want to remove this indirection.
251
+ self._keyring_provider = provider
252
+
253
+ @property
254
+ def use_keyring(self) -> bool:
255
+ # We won't use keyring when --no-input is passed unless
256
+ # a specific provider is requested because it might require
257
+ # user interaction
258
+ return self.prompting or self._keyring_provider not in ["auto", "disabled"]
259
+
260
+ def _get_keyring_auth(
261
+ self,
262
+ url: Optional[str],
263
+ username: Optional[str],
264
+ ) -> Optional[AuthInfo]:
265
+ """Return the tuple auth for a given url from keyring."""
266
+ # Do nothing if no url was provided
267
+ if not url:
268
+ return None
269
+
270
+ try:
271
+ return self.keyring_provider.get_auth_info(url, username)
272
+ except Exception as exc:
273
+ logger.warning(
274
+ "Keyring is skipped due to an exception: %s",
275
+ str(exc),
276
+ )
277
+ global KEYRING_DISABLED
278
+ KEYRING_DISABLED = True
279
+ get_keyring_provider.cache_clear()
280
+ return None
281
+
282
+ def _get_index_url(self, url: str) -> Optional[str]:
283
+ """Return the original index URL matching the requested URL.
284
+
285
+ Cached or dynamically generated credentials may work against
286
+ the original index URL rather than just the netloc.
287
+
288
+ The provided url should have had its username and password
289
+ removed already. If the original index url had credentials then
290
+ they will be included in the return value.
291
+
292
+ Returns None if no matching index was found, or if --no-index
293
+ was specified by the user.
294
+ """
295
+ if not url or not self.index_urls:
296
+ return None
297
+
298
+ url = remove_auth_from_url(url).rstrip("/") + "/"
299
+ parsed_url = urllib.parse.urlsplit(url)
300
+
301
+ candidates = []
302
+
303
+ for index in self.index_urls:
304
+ index = index.rstrip("/") + "/"
305
+ parsed_index = urllib.parse.urlsplit(remove_auth_from_url(index))
306
+ if parsed_url == parsed_index:
307
+ return index
308
+
309
+ if parsed_url.netloc != parsed_index.netloc:
310
+ continue
311
+
312
+ candidate = urllib.parse.urlsplit(index)
313
+ candidates.append(candidate)
314
+
315
+ if not candidates:
316
+ return None
317
+
318
+ candidates.sort(
319
+ reverse=True,
320
+ key=lambda candidate: commonprefix(
321
+ [
322
+ parsed_url.path,
323
+ candidate.path,
324
+ ]
325
+ ).rfind("/"),
326
+ )
327
+
328
+ return urllib.parse.urlunsplit(candidates[0])
329
+
330
+ def _get_new_credentials(
331
+ self,
332
+ original_url: str,
333
+ *,
334
+ allow_netrc: bool = True,
335
+ allow_keyring: bool = False,
336
+ ) -> AuthInfo:
337
+ """Find and return credentials for the specified URL."""
338
+ # Split the credentials and netloc from the url.
339
+ url, netloc, url_user_password = split_auth_netloc_from_url(
340
+ original_url,
341
+ )
342
+
343
+ # Start with the credentials embedded in the url
344
+ username, password = url_user_password
345
+ if username is not None and password is not None:
346
+ logger.debug("Found credentials in url for %s", netloc)
347
+ return url_user_password
348
+
349
+ # Find a matching index url for this request
350
+ index_url = self._get_index_url(url)
351
+ if index_url:
352
+ # Split the credentials from the url.
353
+ index_info = split_auth_netloc_from_url(index_url)
354
+ if index_info:
355
+ index_url, _, index_url_user_password = index_info
356
+ logger.debug("Found index url %s", index_url)
357
+
358
+ # If an index URL was found, try its embedded credentials
359
+ if index_url and index_url_user_password[0] is not None:
360
+ username, password = index_url_user_password
361
+ if username is not None and password is not None:
362
+ logger.debug("Found credentials in index url for %s", netloc)
363
+ return index_url_user_password
364
+
365
+ # Get creds from netrc if we still don't have them
366
+ if allow_netrc:
367
+ netrc_auth = get_netrc_auth(original_url)
368
+ if netrc_auth:
369
+ logger.debug("Found credentials in netrc for %s", netloc)
370
+ return netrc_auth
371
+
372
+ # If we don't have a password and keyring is available, use it.
373
+ if allow_keyring:
374
+ # The index url is more specific than the netloc, so try it first
375
+ # fmt: off
376
+ kr_auth = (
377
+ self._get_keyring_auth(index_url, username) or
378
+ self._get_keyring_auth(netloc, username)
379
+ )
380
+ # fmt: on
381
+ if kr_auth:
382
+ logger.debug("Found credentials in keyring for %s", netloc)
383
+ return kr_auth
384
+
385
+ return username, password
386
+
387
+ def _get_url_and_credentials(
388
+ self, original_url: str
389
+ ) -> Tuple[str, Optional[str], Optional[str]]:
390
+ """Return the credentials to use for the provided URL.
391
+
392
+ If allowed, netrc and keyring may be used to obtain the
393
+ correct credentials.
394
+
395
+ Returns (url_without_credentials, username, password). Note
396
+ that even if the original URL contains credentials, this
397
+ function may return a different username and password.
398
+ """
399
+ url, netloc, _ = split_auth_netloc_from_url(original_url)
400
+
401
+ # Try to get credentials from original url
402
+ username, password = self._get_new_credentials(original_url)
403
+
404
+ # If credentials not found, use any stored credentials for this netloc.
405
+ # Do this if either the username or the password is missing.
406
+ # This accounts for the situation in which the user has specified
407
+ # the username in the index url, but the password comes from keyring.
408
+ if (username is None or password is None) and netloc in self.passwords:
409
+ un, pw = self.passwords[netloc]
410
+ # It is possible that the cached credentials are for a different username,
411
+ # in which case the cache should be ignored.
412
+ if username is None or username == un:
413
+ username, password = un, pw
414
+
415
+ if username is not None or password is not None:
416
+ # Convert the username and password if they're None, so that
417
+ # this netloc will show up as "cached" in the conditional above.
418
+ # Further, HTTPBasicAuth doesn't accept None, so it makes sense to
419
+ # cache the value that is going to be used.
420
+ username = username or ""
421
+ password = password or ""
422
+
423
+ # Store any acquired credentials.
424
+ self.passwords[netloc] = (username, password)
425
+
426
+ assert (
427
+ # Credentials were found
428
+ (username is not None and password is not None)
429
+ # Credentials were not found
430
+ or (username is None and password is None)
431
+ ), f"Could not load credentials from url: {original_url}"
432
+
433
+ return url, username, password
434
+
435
+ def __call__(self, req: Request) -> Request:
436
+ # Get credentials for this request
437
+ url, username, password = self._get_url_and_credentials(req.url)
438
+
439
+ # Set the url of the request to the url without any credentials
440
+ req.url = url
441
+
442
+ if username is not None and password is not None:
443
+ # Send the basic auth with this request
444
+ req = HTTPBasicAuth(username, password)(req)
445
+
446
+ # Attach a hook to handle 401 responses
447
+ req.register_hook("response", self.handle_401)
448
+
449
+ return req
450
+
451
+ # Factored out to allow for easy patching in tests
452
+ def _prompt_for_password(
453
+ self, netloc: str
454
+ ) -> Tuple[Optional[str], Optional[str], bool]:
455
+ username = ask_input(f"User for {netloc}: ") if self.prompting else None
456
+ if not username:
457
+ return None, None, False
458
+ if self.use_keyring:
459
+ auth = self._get_keyring_auth(netloc, username)
460
+ if auth and auth[0] is not None and auth[1] is not None:
461
+ return auth[0], auth[1], False
462
+ password = ask_password("Password: ")
463
+ return username, password, True
464
+
465
+ # Factored out to allow for easy patching in tests
466
+ def _should_save_password_to_keyring(self) -> bool:
467
+ if (
468
+ not self.prompting
469
+ or not self.use_keyring
470
+ or not self.keyring_provider.has_keyring
471
+ ):
472
+ return False
473
+ return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y"
474
+
475
+ def handle_401(self, resp: Response, **kwargs: Any) -> Response:
476
+ # We only care about 401 responses, anything else we want to just
477
+ # pass through the actual response
478
+ if resp.status_code != 401:
479
+ return resp
480
+
481
+ username, password = None, None
482
+
483
+ # Query the keyring for credentials:
484
+ if self.use_keyring:
485
+ username, password = self._get_new_credentials(
486
+ resp.url,
487
+ allow_netrc=False,
488
+ allow_keyring=True,
489
+ )
490
+
491
+ # We are not able to prompt the user so simply return the response
492
+ if not self.prompting and not username and not password:
493
+ return resp
494
+
495
+ parsed = urllib.parse.urlparse(resp.url)
496
+
497
+ # Prompt the user for a new username and password
498
+ save = False
499
+ if not username and not password:
500
+ username, password, save = self._prompt_for_password(parsed.netloc)
501
+
502
+ # Store the new username and password to use for future requests
503
+ self._credentials_to_save = None
504
+ if username is not None and password is not None:
505
+ self.passwords[parsed.netloc] = (username, password)
506
+
507
+ # Prompt to save the password to keyring
508
+ if save and self._should_save_password_to_keyring():
509
+ self._credentials_to_save = Credentials(
510
+ url=parsed.netloc,
511
+ username=username,
512
+ password=password,
513
+ )
514
+
515
+ # Consume content and release the original connection to allow our new
516
+ # request to reuse the same one.
517
+ # The result of the assignment isn't used, it's just needed to consume
518
+ # the content.
519
+ _ = resp.content
520
+ resp.raw.release_conn()
521
+
522
+ # Add our new username and password to the request
523
+ req = HTTPBasicAuth(username or "", password or "")(resp.request)
524
+ req.register_hook("response", self.warn_on_401)
525
+
526
+ # On successful request, save the credentials that were used to
527
+ # keyring. (Note that if the user responded "no" above, this member
528
+ # is not set and nothing will be saved.)
529
+ if self._credentials_to_save:
530
+ req.register_hook("response", self.save_credentials)
531
+
532
+ # Send our new request
533
+ new_resp = resp.connection.send(req, **kwargs)
534
+ new_resp.history.append(resp)
535
+
536
+ return new_resp
537
+
538
+ def warn_on_401(self, resp: Response, **kwargs: Any) -> None:
539
+ """Response callback to warn about incorrect credentials."""
540
+ if resp.status_code == 401:
541
+ logger.warning(
542
+ "401 Error, Credentials not correct for %s",
543
+ resp.request.url,
544
+ )
545
+
546
+ def save_credentials(self, resp: Response, **kwargs: Any) -> None:
547
+ """Response callback to save credentials on success."""
548
+ assert (
549
+ self.keyring_provider.has_keyring
550
+ ), "should never reach here without keyring"
551
+
552
+ creds = self._credentials_to_save
553
+ self._credentials_to_save = None
554
+ if creds and resp.status_code < 400:
555
+ try:
556
+ logger.info("Saving credentials to keyring")
557
+ self.keyring_provider.save_auth_info(
558
+ creds.url, creds.username, creds.password
559
+ )
560
+ except Exception:
561
+ logger.exception("Failed to save credentials")
.venv/Lib/site-packages/pip/_internal/network/cache.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP cache implementation.
2
+ """
3
+
4
+ import os
5
+ from contextlib import contextmanager
6
+ from typing import Generator, Optional
7
+
8
+ from pip._vendor.cachecontrol.cache import BaseCache
9
+ from pip._vendor.cachecontrol.caches import FileCache
10
+ from pip._vendor.requests.models import Response
11
+
12
+ from pip._internal.utils.filesystem import adjacent_tmp_file, replace
13
+ from pip._internal.utils.misc import ensure_dir
14
+
15
+
16
+ def is_from_cache(response: Response) -> bool:
17
+ return getattr(response, "from_cache", False)
18
+
19
+
20
+ @contextmanager
21
+ def suppressed_cache_errors() -> Generator[None, None, None]:
22
+ """If we can't access the cache then we can just skip caching and process
23
+ requests as if caching wasn't enabled.
24
+ """
25
+ try:
26
+ yield
27
+ except OSError:
28
+ pass
29
+
30
+
31
+ class SafeFileCache(BaseCache):
32
+ """
33
+ A file based cache which is safe to use even when the target directory may
34
+ not be accessible or writable.
35
+ """
36
+
37
+ def __init__(self, directory: str) -> None:
38
+ assert directory is not None, "Cache directory must not be None."
39
+ super().__init__()
40
+ self.directory = directory
41
+
42
+ def _get_cache_path(self, name: str) -> str:
43
+ # From cachecontrol.caches.file_cache.FileCache._fn, brought into our
44
+ # class for backwards-compatibility and to avoid using a non-public
45
+ # method.
46
+ hashed = FileCache.encode(name)
47
+ parts = list(hashed[:5]) + [hashed]
48
+ return os.path.join(self.directory, *parts)
49
+
50
+ def get(self, key: str) -> Optional[bytes]:
51
+ path = self._get_cache_path(key)
52
+ with suppressed_cache_errors():
53
+ with open(path, "rb") as f:
54
+ return f.read()
55
+
56
+ def set(self, key: str, value: bytes, expires: Optional[int] = None) -> None:
57
+ path = self._get_cache_path(key)
58
+ with suppressed_cache_errors():
59
+ ensure_dir(os.path.dirname(path))
60
+
61
+ with adjacent_tmp_file(path) as f:
62
+ f.write(value)
63
+
64
+ replace(f.name, path)
65
+
66
+ def delete(self, key: str) -> None:
67
+ path = self._get_cache_path(key)
68
+ with suppressed_cache_errors():
69
+ os.remove(path)
.venv/Lib/site-packages/pip/_internal/network/download.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download files with progress indicators.
2
+ """
3
+ import email.message
4
+ import logging
5
+ import mimetypes
6
+ import os
7
+ from typing import Iterable, Optional, Tuple
8
+
9
+ from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
10
+
11
+ from pip._internal.cli.progress_bars import get_download_progress_renderer
12
+ from pip._internal.exceptions import NetworkConnectionError
13
+ from pip._internal.models.index import PyPI
14
+ from pip._internal.models.link import Link
15
+ from pip._internal.network.cache import is_from_cache
16
+ from pip._internal.network.session import PipSession
17
+ from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
18
+ from pip._internal.utils.misc import format_size, redact_auth_from_url, splitext
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def _get_http_response_size(resp: Response) -> Optional[int]:
24
+ try:
25
+ return int(resp.headers["content-length"])
26
+ except (ValueError, KeyError, TypeError):
27
+ return None
28
+
29
+
30
+ def _prepare_download(
31
+ resp: Response,
32
+ link: Link,
33
+ progress_bar: str,
34
+ ) -> Iterable[bytes]:
35
+ total_length = _get_http_response_size(resp)
36
+
37
+ if link.netloc == PyPI.file_storage_domain:
38
+ url = link.show_url
39
+ else:
40
+ url = link.url_without_fragment
41
+
42
+ logged_url = redact_auth_from_url(url)
43
+
44
+ if total_length:
45
+ logged_url = "{} ({})".format(logged_url, format_size(total_length))
46
+
47
+ if is_from_cache(resp):
48
+ logger.info("Using cached %s", logged_url)
49
+ else:
50
+ logger.info("Downloading %s", logged_url)
51
+
52
+ if logger.getEffectiveLevel() > logging.INFO:
53
+ show_progress = False
54
+ elif is_from_cache(resp):
55
+ show_progress = False
56
+ elif not total_length:
57
+ show_progress = True
58
+ elif total_length > (40 * 1000):
59
+ show_progress = True
60
+ else:
61
+ show_progress = False
62
+
63
+ chunks = response_chunks(resp, CONTENT_CHUNK_SIZE)
64
+
65
+ if not show_progress:
66
+ return chunks
67
+
68
+ renderer = get_download_progress_renderer(bar_type=progress_bar, size=total_length)
69
+ return renderer(chunks)
70
+
71
+
72
+ def sanitize_content_filename(filename: str) -> str:
73
+ """
74
+ Sanitize the "filename" value from a Content-Disposition header.
75
+ """
76
+ return os.path.basename(filename)
77
+
78
+
79
+ def parse_content_disposition(content_disposition: str, default_filename: str) -> str:
80
+ """
81
+ Parse the "filename" value from a Content-Disposition header, and
82
+ return the default filename if the result is empty.
83
+ """
84
+ m = email.message.Message()
85
+ m["content-type"] = content_disposition
86
+ filename = m.get_param("filename")
87
+ if filename:
88
+ # We need to sanitize the filename to prevent directory traversal
89
+ # in case the filename contains ".." path parts.
90
+ filename = sanitize_content_filename(str(filename))
91
+ return filename or default_filename
92
+
93
+
94
+ def _get_http_response_filename(resp: Response, link: Link) -> str:
95
+ """Get an ideal filename from the given HTTP response, falling back to
96
+ the link filename if not provided.
97
+ """
98
+ filename = link.filename # fallback
99
+ # Have a look at the Content-Disposition header for a better guess
100
+ content_disposition = resp.headers.get("content-disposition")
101
+ if content_disposition:
102
+ filename = parse_content_disposition(content_disposition, filename)
103
+ ext: Optional[str] = splitext(filename)[1]
104
+ if not ext:
105
+ ext = mimetypes.guess_extension(resp.headers.get("content-type", ""))
106
+ if ext:
107
+ filename += ext
108
+ if not ext and link.url != resp.url:
109
+ ext = os.path.splitext(resp.url)[1]
110
+ if ext:
111
+ filename += ext
112
+ return filename
113
+
114
+
115
+ def _http_get_download(session: PipSession, link: Link) -> Response:
116
+ target_url = link.url.split("#", 1)[0]
117
+ resp = session.get(target_url, headers=HEADERS, stream=True)
118
+ raise_for_status(resp)
119
+ return resp
120
+
121
+
122
+ class Downloader:
123
+ def __init__(
124
+ self,
125
+ session: PipSession,
126
+ progress_bar: str,
127
+ ) -> None:
128
+ self._session = session
129
+ self._progress_bar = progress_bar
130
+
131
+ def __call__(self, link: Link, location: str) -> Tuple[str, str]:
132
+ """Download the file given by link into location."""
133
+ try:
134
+ resp = _http_get_download(self._session, link)
135
+ except NetworkConnectionError as e:
136
+ assert e.response is not None
137
+ logger.critical(
138
+ "HTTP error %s while getting %s", e.response.status_code, link
139
+ )
140
+ raise
141
+
142
+ filename = _get_http_response_filename(resp, link)
143
+ filepath = os.path.join(location, filename)
144
+
145
+ chunks = _prepare_download(resp, link, self._progress_bar)
146
+ with open(filepath, "wb") as content_file:
147
+ for chunk in chunks:
148
+ content_file.write(chunk)
149
+ content_type = resp.headers.get("Content-Type", "")
150
+ return filepath, content_type
151
+
152
+
153
+ class BatchDownloader:
154
+ def __init__(
155
+ self,
156
+ session: PipSession,
157
+ progress_bar: str,
158
+ ) -> None:
159
+ self._session = session
160
+ self._progress_bar = progress_bar
161
+
162
+ def __call__(
163
+ self, links: Iterable[Link], location: str
164
+ ) -> Iterable[Tuple[Link, Tuple[str, str]]]:
165
+ """Download the files given by links into location."""
166
+ for link in links:
167
+ try:
168
+ resp = _http_get_download(self._session, link)
169
+ except NetworkConnectionError as e:
170
+ assert e.response is not None
171
+ logger.critical(
172
+ "HTTP error %s while getting %s",
173
+ e.response.status_code,
174
+ link,
175
+ )
176
+ raise
177
+
178
+ filename = _get_http_response_filename(resp, link)
179
+ filepath = os.path.join(location, filename)
180
+
181
+ chunks = _prepare_download(resp, link, self._progress_bar)
182
+ with open(filepath, "wb") as content_file:
183
+ for chunk in chunks:
184
+ content_file.write(chunk)
185
+ content_type = resp.headers.get("Content-Type", "")
186
+ yield link, (filepath, content_type)
.venv/Lib/site-packages/pip/_internal/network/lazy_wheel.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lazy ZIP over HTTP"""
2
+
3
+ __all__ = ["HTTPRangeRequestUnsupported", "dist_from_wheel_url"]
4
+
5
+ from bisect import bisect_left, bisect_right
6
+ from contextlib import contextmanager
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import Any, Dict, Generator, List, Optional, Tuple
9
+ from zipfile import BadZipFile, ZipFile
10
+
11
+ from pip._vendor.packaging.utils import canonicalize_name
12
+ from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
13
+
14
+ from pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution
15
+ from pip._internal.network.session import PipSession
16
+ from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
17
+
18
+
19
+ class HTTPRangeRequestUnsupported(Exception):
20
+ pass
21
+
22
+
23
+ def dist_from_wheel_url(name: str, url: str, session: PipSession) -> BaseDistribution:
24
+ """Return a distribution object from the given wheel URL.
25
+
26
+ This uses HTTP range requests to only fetch the portion of the wheel
27
+ containing metadata, just enough for the object to be constructed.
28
+ If such requests are not supported, HTTPRangeRequestUnsupported
29
+ is raised.
30
+ """
31
+ with LazyZipOverHTTP(url, session) as zf:
32
+ # For read-only ZIP files, ZipFile only needs methods read,
33
+ # seek, seekable and tell, not the whole IO protocol.
34
+ wheel = MemoryWheel(zf.name, zf) # type: ignore
35
+ # After context manager exit, wheel.name
36
+ # is an invalid file by intention.
37
+ return get_wheel_distribution(wheel, canonicalize_name(name))
38
+
39
+
40
+ class LazyZipOverHTTP:
41
+ """File-like object mapped to a ZIP file over HTTP.
42
+
43
+ This uses HTTP range requests to lazily fetch the file's content,
44
+ which is supposed to be fed to ZipFile. If such requests are not
45
+ supported by the server, raise HTTPRangeRequestUnsupported
46
+ during initialization.
47
+ """
48
+
49
+ def __init__(
50
+ self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE
51
+ ) -> None:
52
+ head = session.head(url, headers=HEADERS)
53
+ raise_for_status(head)
54
+ assert head.status_code == 200
55
+ self._session, self._url, self._chunk_size = session, url, chunk_size
56
+ self._length = int(head.headers["Content-Length"])
57
+ self._file = NamedTemporaryFile()
58
+ self.truncate(self._length)
59
+ self._left: List[int] = []
60
+ self._right: List[int] = []
61
+ if "bytes" not in head.headers.get("Accept-Ranges", "none"):
62
+ raise HTTPRangeRequestUnsupported("range request is not supported")
63
+ self._check_zip()
64
+
65
+ @property
66
+ def mode(self) -> str:
67
+ """Opening mode, which is always rb."""
68
+ return "rb"
69
+
70
+ @property
71
+ def name(self) -> str:
72
+ """Path to the underlying file."""
73
+ return self._file.name
74
+
75
+ def seekable(self) -> bool:
76
+ """Return whether random access is supported, which is True."""
77
+ return True
78
+
79
+ def close(self) -> None:
80
+ """Close the file."""
81
+ self._file.close()
82
+
83
+ @property
84
+ def closed(self) -> bool:
85
+ """Whether the file is closed."""
86
+ return self._file.closed
87
+
88
+ def read(self, size: int = -1) -> bytes:
89
+ """Read up to size bytes from the object and return them.
90
+
91
+ As a convenience, if size is unspecified or -1,
92
+ all bytes until EOF are returned. Fewer than
93
+ size bytes may be returned if EOF is reached.
94
+ """
95
+ download_size = max(size, self._chunk_size)
96
+ start, length = self.tell(), self._length
97
+ stop = length if size < 0 else min(start + download_size, length)
98
+ start = max(0, stop - download_size)
99
+ self._download(start, stop - 1)
100
+ return self._file.read(size)
101
+
102
+ def readable(self) -> bool:
103
+ """Return whether the file is readable, which is True."""
104
+ return True
105
+
106
+ def seek(self, offset: int, whence: int = 0) -> int:
107
+ """Change stream position and return the new absolute position.
108
+
109
+ Seek to offset relative position indicated by whence:
110
+ * 0: Start of stream (the default). pos should be >= 0;
111
+ * 1: Current position - pos may be negative;
112
+ * 2: End of stream - pos usually negative.
113
+ """
114
+ return self._file.seek(offset, whence)
115
+
116
+ def tell(self) -> int:
117
+ """Return the current position."""
118
+ return self._file.tell()
119
+
120
+ def truncate(self, size: Optional[int] = None) -> int:
121
+ """Resize the stream to the given size in bytes.
122
+
123
+ If size is unspecified resize to the current position.
124
+ The current stream position isn't changed.
125
+
126
+ Return the new file size.
127
+ """
128
+ return self._file.truncate(size)
129
+
130
+ def writable(self) -> bool:
131
+ """Return False."""
132
+ return False
133
+
134
+ def __enter__(self) -> "LazyZipOverHTTP":
135
+ self._file.__enter__()
136
+ return self
137
+
138
+ def __exit__(self, *exc: Any) -> None:
139
+ self._file.__exit__(*exc)
140
+
141
+ @contextmanager
142
+ def _stay(self) -> Generator[None, None, None]:
143
+ """Return a context manager keeping the position.
144
+
145
+ At the end of the block, seek back to original position.
146
+ """
147
+ pos = self.tell()
148
+ try:
149
+ yield
150
+ finally:
151
+ self.seek(pos)
152
+
153
+ def _check_zip(self) -> None:
154
+ """Check and download until the file is a valid ZIP."""
155
+ end = self._length - 1
156
+ for start in reversed(range(0, end, self._chunk_size)):
157
+ self._download(start, end)
158
+ with self._stay():
159
+ try:
160
+ # For read-only ZIP files, ZipFile only needs
161
+ # methods read, seek, seekable and tell.
162
+ ZipFile(self) # type: ignore
163
+ except BadZipFile:
164
+ pass
165
+ else:
166
+ break
167
+
168
+ def _stream_response(
169
+ self, start: int, end: int, base_headers: Dict[str, str] = HEADERS
170
+ ) -> Response:
171
+ """Return HTTP response to a range request from start to end."""
172
+ headers = base_headers.copy()
173
+ headers["Range"] = f"bytes={start}-{end}"
174
+ # TODO: Get range requests to be correctly cached
175
+ headers["Cache-Control"] = "no-cache"
176
+ return self._session.get(self._url, headers=headers, stream=True)
177
+
178
+ def _merge(
179
+ self, start: int, end: int, left: int, right: int
180
+ ) -> Generator[Tuple[int, int], None, None]:
181
+ """Return a generator of intervals to be fetched.
182
+
183
+ Args:
184
+ start (int): Start of needed interval
185
+ end (int): End of needed interval
186
+ left (int): Index of first overlapping downloaded data
187
+ right (int): Index after last overlapping downloaded data
188
+ """
189
+ lslice, rslice = self._left[left:right], self._right[left:right]
190
+ i = start = min([start] + lslice[:1])
191
+ end = max([end] + rslice[-1:])
192
+ for j, k in zip(lslice, rslice):
193
+ if j > i:
194
+ yield i, j - 1
195
+ i = k + 1
196
+ if i <= end:
197
+ yield i, end
198
+ self._left[left:right], self._right[left:right] = [start], [end]
199
+
200
+ def _download(self, start: int, end: int) -> None:
201
+ """Download bytes from start to end inclusively."""
202
+ with self._stay():
203
+ left = bisect_left(self._right, start)
204
+ right = bisect_right(self._left, end)
205
+ for start, end in self._merge(start, end, left, right):
206
+ response = self._stream_response(start, end)
207
+ response.raise_for_status()
208
+ self.seek(start)
209
+ for chunk in response_chunks(response, self._chunk_size):
210
+ self._file.write(chunk)
.venv/Lib/site-packages/pip/_internal/network/session.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PipSession and supporting code, containing all pip-specific
2
+ network request configuration and behavior.
3
+ """
4
+
5
+ import email.utils
6
+ import io
7
+ import ipaddress
8
+ import json
9
+ import logging
10
+ import mimetypes
11
+ import os
12
+ import platform
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import urllib.parse
17
+ import warnings
18
+ from typing import (
19
+ TYPE_CHECKING,
20
+ Any,
21
+ Dict,
22
+ Generator,
23
+ List,
24
+ Mapping,
25
+ Optional,
26
+ Sequence,
27
+ Tuple,
28
+ Union,
29
+ )
30
+
31
+ from pip._vendor import requests, urllib3
32
+ from pip._vendor.cachecontrol import CacheControlAdapter as _BaseCacheControlAdapter
33
+ from pip._vendor.requests.adapters import DEFAULT_POOLBLOCK, BaseAdapter
34
+ from pip._vendor.requests.adapters import HTTPAdapter as _BaseHTTPAdapter
35
+ from pip._vendor.requests.models import PreparedRequest, Response
36
+ from pip._vendor.requests.structures import CaseInsensitiveDict
37
+ from pip._vendor.urllib3.connectionpool import ConnectionPool
38
+ from pip._vendor.urllib3.exceptions import InsecureRequestWarning
39
+
40
+ from pip import __version__
41
+ from pip._internal.metadata import get_default_environment
42
+ from pip._internal.models.link import Link
43
+ from pip._internal.network.auth import MultiDomainBasicAuth
44
+ from pip._internal.network.cache import SafeFileCache
45
+
46
+ # Import ssl from compat so the initial import occurs in only one place.
47
+ from pip._internal.utils.compat import has_tls
48
+ from pip._internal.utils.glibc import libc_ver
49
+ from pip._internal.utils.misc import build_url_from_netloc, parse_netloc
50
+ from pip._internal.utils.urls import url_to_path
51
+
52
+ if TYPE_CHECKING:
53
+ from ssl import SSLContext
54
+
55
+ from pip._vendor.urllib3.poolmanager import PoolManager
56
+
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+ SecureOrigin = Tuple[str, str, Optional[Union[int, str]]]
61
+
62
+
63
+ # Ignore warning raised when using --trusted-host.
64
+ warnings.filterwarnings("ignore", category=InsecureRequestWarning)
65
+
66
+
67
+ SECURE_ORIGINS: List[SecureOrigin] = [
68
+ # protocol, hostname, port
69
+ # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)
70
+ ("https", "*", "*"),
71
+ ("*", "localhost", "*"),
72
+ ("*", "127.0.0.0/8", "*"),
73
+ ("*", "::1/128", "*"),
74
+ ("file", "*", None),
75
+ # ssh is always secure.
76
+ ("ssh", "*", "*"),
77
+ ]
78
+
79
+
80
+ # These are environment variables present when running under various
81
+ # CI systems. For each variable, some CI systems that use the variable
82
+ # are indicated. The collection was chosen so that for each of a number
83
+ # of popular systems, at least one of the environment variables is used.
84
+ # This list is used to provide some indication of and lower bound for
85
+ # CI traffic to PyPI. Thus, it is okay if the list is not comprehensive.
86
+ # For more background, see: https://github.com/pypa/pip/issues/5499
87
+ CI_ENVIRONMENT_VARIABLES = (
88
+ # Azure Pipelines
89
+ "BUILD_BUILDID",
90
+ # Jenkins
91
+ "BUILD_ID",
92
+ # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI
93
+ "CI",
94
+ # Explicit environment variable.
95
+ "PIP_IS_CI",
96
+ )
97
+
98
+
99
+ def looks_like_ci() -> bool:
100
+ """
101
+ Return whether it looks like pip is running under CI.
102
+ """
103
+ # We don't use the method of checking for a tty (e.g. using isatty())
104
+ # because some CI systems mimic a tty (e.g. Travis CI). Thus that
105
+ # method doesn't provide definitive information in either direction.
106
+ return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES)
107
+
108
+
109
+ def user_agent() -> str:
110
+ """
111
+ Return a string representing the user agent.
112
+ """
113
+ data: Dict[str, Any] = {
114
+ "installer": {"name": "pip", "version": __version__},
115
+ "python": platform.python_version(),
116
+ "implementation": {
117
+ "name": platform.python_implementation(),
118
+ },
119
+ }
120
+
121
+ if data["implementation"]["name"] == "CPython":
122
+ data["implementation"]["version"] = platform.python_version()
123
+ elif data["implementation"]["name"] == "PyPy":
124
+ pypy_version_info = sys.pypy_version_info # type: ignore
125
+ if pypy_version_info.releaselevel == "final":
126
+ pypy_version_info = pypy_version_info[:3]
127
+ data["implementation"]["version"] = ".".join(
128
+ [str(x) for x in pypy_version_info]
129
+ )
130
+ elif data["implementation"]["name"] == "Jython":
131
+ # Complete Guess
132
+ data["implementation"]["version"] = platform.python_version()
133
+ elif data["implementation"]["name"] == "IronPython":
134
+ # Complete Guess
135
+ data["implementation"]["version"] = platform.python_version()
136
+
137
+ if sys.platform.startswith("linux"):
138
+ from pip._vendor import distro
139
+
140
+ linux_distribution = distro.name(), distro.version(), distro.codename()
141
+ distro_infos: Dict[str, Any] = dict(
142
+ filter(
143
+ lambda x: x[1],
144
+ zip(["name", "version", "id"], linux_distribution),
145
+ )
146
+ )
147
+ libc = dict(
148
+ filter(
149
+ lambda x: x[1],
150
+ zip(["lib", "version"], libc_ver()),
151
+ )
152
+ )
153
+ if libc:
154
+ distro_infos["libc"] = libc
155
+ if distro_infos:
156
+ data["distro"] = distro_infos
157
+
158
+ if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
159
+ data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}
160
+
161
+ if platform.system():
162
+ data.setdefault("system", {})["name"] = platform.system()
163
+
164
+ if platform.release():
165
+ data.setdefault("system", {})["release"] = platform.release()
166
+
167
+ if platform.machine():
168
+ data["cpu"] = platform.machine()
169
+
170
+ if has_tls():
171
+ import _ssl as ssl
172
+
173
+ data["openssl_version"] = ssl.OPENSSL_VERSION
174
+
175
+ setuptools_dist = get_default_environment().get_distribution("setuptools")
176
+ if setuptools_dist is not None:
177
+ data["setuptools_version"] = str(setuptools_dist.version)
178
+
179
+ if shutil.which("rustc") is not None:
180
+ # If for any reason `rustc --version` fails, silently ignore it
181
+ try:
182
+ rustc_output = subprocess.check_output(
183
+ ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
184
+ )
185
+ except Exception:
186
+ pass
187
+ else:
188
+ if rustc_output.startswith(b"rustc "):
189
+ # The format of `rustc --version` is:
190
+ # `b'rustc 1.52.1 (9bc8c42bb 2021-05-09)\n'`
191
+ # We extract just the middle (1.52.1) part
192
+ data["rustc_version"] = rustc_output.split(b" ")[1].decode()
193
+
194
+ # Use None rather than False so as not to give the impression that
195
+ # pip knows it is not being run under CI. Rather, it is a null or
196
+ # inconclusive result. Also, we include some value rather than no
197
+ # value to make it easier to know that the check has been run.
198
+ data["ci"] = True if looks_like_ci() else None
199
+
200
+ user_data = os.environ.get("PIP_USER_AGENT_USER_DATA")
201
+ if user_data is not None:
202
+ data["user_data"] = user_data
203
+
204
+ return "{data[installer][name]}/{data[installer][version]} {json}".format(
205
+ data=data,
206
+ json=json.dumps(data, separators=(",", ":"), sort_keys=True),
207
+ )
208
+
209
+
210
+ class LocalFSAdapter(BaseAdapter):
211
+ def send(
212
+ self,
213
+ request: PreparedRequest,
214
+ stream: bool = False,
215
+ timeout: Optional[Union[float, Tuple[float, float]]] = None,
216
+ verify: Union[bool, str] = True,
217
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
218
+ proxies: Optional[Mapping[str, str]] = None,
219
+ ) -> Response:
220
+ pathname = url_to_path(request.url)
221
+
222
+ resp = Response()
223
+ resp.status_code = 200
224
+ resp.url = request.url
225
+
226
+ try:
227
+ stats = os.stat(pathname)
228
+ except OSError as exc:
229
+ # format the exception raised as a io.BytesIO object,
230
+ # to return a better error message:
231
+ resp.status_code = 404
232
+ resp.reason = type(exc).__name__
233
+ resp.raw = io.BytesIO(f"{resp.reason}: {exc}".encode("utf8"))
234
+ else:
235
+ modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
236
+ content_type = mimetypes.guess_type(pathname)[0] or "text/plain"
237
+ resp.headers = CaseInsensitiveDict(
238
+ {
239
+ "Content-Type": content_type,
240
+ "Content-Length": stats.st_size,
241
+ "Last-Modified": modified,
242
+ }
243
+ )
244
+
245
+ resp.raw = open(pathname, "rb")
246
+ resp.close = resp.raw.close
247
+
248
+ return resp
249
+
250
+ def close(self) -> None:
251
+ pass
252
+
253
+
254
+ class _SSLContextAdapterMixin:
255
+ """Mixin to add the ``ssl_context`` constructor argument to HTTP adapters.
256
+
257
+ The additional argument is forwarded directly to the pool manager. This allows us
258
+ to dynamically decide what SSL store to use at runtime, which is used to implement
259
+ the optional ``truststore`` backend.
260
+ """
261
+
262
+ def __init__(
263
+ self,
264
+ *,
265
+ ssl_context: Optional["SSLContext"] = None,
266
+ **kwargs: Any,
267
+ ) -> None:
268
+ self._ssl_context = ssl_context
269
+ super().__init__(**kwargs)
270
+
271
+ def init_poolmanager(
272
+ self,
273
+ connections: int,
274
+ maxsize: int,
275
+ block: bool = DEFAULT_POOLBLOCK,
276
+ **pool_kwargs: Any,
277
+ ) -> "PoolManager":
278
+ if self._ssl_context is not None:
279
+ pool_kwargs.setdefault("ssl_context", self._ssl_context)
280
+ return super().init_poolmanager( # type: ignore[misc]
281
+ connections=connections,
282
+ maxsize=maxsize,
283
+ block=block,
284
+ **pool_kwargs,
285
+ )
286
+
287
+
288
+ class HTTPAdapter(_SSLContextAdapterMixin, _BaseHTTPAdapter):
289
+ pass
290
+
291
+
292
+ class CacheControlAdapter(_SSLContextAdapterMixin, _BaseCacheControlAdapter):
293
+ pass
294
+
295
+
296
+ class InsecureHTTPAdapter(HTTPAdapter):
297
+ def cert_verify(
298
+ self,
299
+ conn: ConnectionPool,
300
+ url: str,
301
+ verify: Union[bool, str],
302
+ cert: Optional[Union[str, Tuple[str, str]]],
303
+ ) -> None:
304
+ super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
305
+
306
+
307
+ class InsecureCacheControlAdapter(CacheControlAdapter):
308
+ def cert_verify(
309
+ self,
310
+ conn: ConnectionPool,
311
+ url: str,
312
+ verify: Union[bool, str],
313
+ cert: Optional[Union[str, Tuple[str, str]]],
314
+ ) -> None:
315
+ super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
316
+
317
+
318
+ class PipSession(requests.Session):
319
+ timeout: Optional[int] = None
320
+
321
+ def __init__(
322
+ self,
323
+ *args: Any,
324
+ retries: int = 0,
325
+ cache: Optional[str] = None,
326
+ trusted_hosts: Sequence[str] = (),
327
+ index_urls: Optional[List[str]] = None,
328
+ ssl_context: Optional["SSLContext"] = None,
329
+ **kwargs: Any,
330
+ ) -> None:
331
+ """
332
+ :param trusted_hosts: Domains not to emit warnings for when not using
333
+ HTTPS.
334
+ """
335
+ super().__init__(*args, **kwargs)
336
+
337
+ # Namespace the attribute with "pip_" just in case to prevent
338
+ # possible conflicts with the base class.
339
+ self.pip_trusted_origins: List[Tuple[str, Optional[int]]] = []
340
+
341
+ # Attach our User Agent to the request
342
+ self.headers["User-Agent"] = user_agent()
343
+
344
+ # Attach our Authentication handler to the session
345
+ self.auth = MultiDomainBasicAuth(index_urls=index_urls)
346
+
347
+ # Create our urllib3.Retry instance which will allow us to customize
348
+ # how we handle retries.
349
+ retries = urllib3.Retry(
350
+ # Set the total number of retries that a particular request can
351
+ # have.
352
+ total=retries,
353
+ # A 503 error from PyPI typically means that the Fastly -> Origin
354
+ # connection got interrupted in some way. A 503 error in general
355
+ # is typically considered a transient error so we'll go ahead and
356
+ # retry it.
357
+ # A 500 may indicate transient error in Amazon S3
358
+ # A 520 or 527 - may indicate transient error in CloudFlare
359
+ status_forcelist=[500, 503, 520, 527],
360
+ # Add a small amount of back off between failed requests in
361
+ # order to prevent hammering the service.
362
+ backoff_factor=0.25,
363
+ ) # type: ignore
364
+
365
+ # Our Insecure HTTPAdapter disables HTTPS validation. It does not
366
+ # support caching so we'll use it for all http:// URLs.
367
+ # If caching is disabled, we will also use it for
368
+ # https:// hosts that we've marked as ignoring
369
+ # TLS errors for (trusted-hosts).
370
+ insecure_adapter = InsecureHTTPAdapter(max_retries=retries)
371
+
372
+ # We want to _only_ cache responses on securely fetched origins or when
373
+ # the host is specified as trusted. We do this because
374
+ # we can't validate the response of an insecurely/untrusted fetched
375
+ # origin, and we don't want someone to be able to poison the cache and
376
+ # require manual eviction from the cache to fix it.
377
+ if cache:
378
+ secure_adapter = CacheControlAdapter(
379
+ cache=SafeFileCache(cache),
380
+ max_retries=retries,
381
+ ssl_context=ssl_context,
382
+ )
383
+ self._trusted_host_adapter = InsecureCacheControlAdapter(
384
+ cache=SafeFileCache(cache),
385
+ max_retries=retries,
386
+ )
387
+ else:
388
+ secure_adapter = HTTPAdapter(max_retries=retries, ssl_context=ssl_context)
389
+ self._trusted_host_adapter = insecure_adapter
390
+
391
+ self.mount("https://", secure_adapter)
392
+ self.mount("http://", insecure_adapter)
393
+
394
+ # Enable file:// urls
395
+ self.mount("file://", LocalFSAdapter())
396
+
397
+ for host in trusted_hosts:
398
+ self.add_trusted_host(host, suppress_logging=True)
399
+
400
+ def update_index_urls(self, new_index_urls: List[str]) -> None:
401
+ """
402
+ :param new_index_urls: New index urls to update the authentication
403
+ handler with.
404
+ """
405
+ self.auth.index_urls = new_index_urls
406
+
407
+ def add_trusted_host(
408
+ self, host: str, source: Optional[str] = None, suppress_logging: bool = False
409
+ ) -> None:
410
+ """
411
+ :param host: It is okay to provide a host that has previously been
412
+ added.
413
+ :param source: An optional source string, for logging where the host
414
+ string came from.
415
+ """
416
+ if not suppress_logging:
417
+ msg = f"adding trusted host: {host!r}"
418
+ if source is not None:
419
+ msg += f" (from {source})"
420
+ logger.info(msg)
421
+
422
+ parsed_host, parsed_port = parse_netloc(host)
423
+ if parsed_host is None:
424
+ raise ValueError(f"Trusted host URL must include a host part: {host!r}")
425
+ if (parsed_host, parsed_port) not in self.pip_trusted_origins:
426
+ self.pip_trusted_origins.append((parsed_host, parsed_port))
427
+
428
+ self.mount(
429
+ build_url_from_netloc(host, scheme="http") + "/", self._trusted_host_adapter
430
+ )
431
+ self.mount(build_url_from_netloc(host) + "/", self._trusted_host_adapter)
432
+ if not parsed_port:
433
+ self.mount(
434
+ build_url_from_netloc(host, scheme="http") + ":",
435
+ self._trusted_host_adapter,
436
+ )
437
+ # Mount wildcard ports for the same host.
438
+ self.mount(build_url_from_netloc(host) + ":", self._trusted_host_adapter)
439
+
440
+ def iter_secure_origins(self) -> Generator[SecureOrigin, None, None]:
441
+ yield from SECURE_ORIGINS
442
+ for host, port in self.pip_trusted_origins:
443
+ yield ("*", host, "*" if port is None else port)
444
+
445
+ def is_secure_origin(self, location: Link) -> bool:
446
+ # Determine if this url used a secure transport mechanism
447
+ parsed = urllib.parse.urlparse(str(location))
448
+ origin_protocol, origin_host, origin_port = (
449
+ parsed.scheme,
450
+ parsed.hostname,
451
+ parsed.port,
452
+ )
453
+
454
+ # The protocol to use to see if the protocol matches.
455
+ # Don't count the repository type as part of the protocol: in
456
+ # cases such as "git+ssh", only use "ssh". (I.e., Only verify against
457
+ # the last scheme.)
458
+ origin_protocol = origin_protocol.rsplit("+", 1)[-1]
459
+
460
+ # Determine if our origin is a secure origin by looking through our
461
+ # hardcoded list of secure origins, as well as any additional ones
462
+ # configured on this PackageFinder instance.
463
+ for secure_origin in self.iter_secure_origins():
464
+ secure_protocol, secure_host, secure_port = secure_origin
465
+ if origin_protocol != secure_protocol and secure_protocol != "*":
466
+ continue
467
+
468
+ try:
469
+ addr = ipaddress.ip_address(origin_host or "")
470
+ network = ipaddress.ip_network(secure_host)
471
+ except ValueError:
472
+ # We don't have both a valid address or a valid network, so
473
+ # we'll check this origin against hostnames.
474
+ if (
475
+ origin_host
476
+ and origin_host.lower() != secure_host.lower()
477
+ and secure_host != "*"
478
+ ):
479
+ continue
480
+ else:
481
+ # We have a valid address and network, so see if the address
482
+ # is contained within the network.
483
+ if addr not in network:
484
+ continue
485
+
486
+ # Check to see if the port matches.
487
+ if (
488
+ origin_port != secure_port
489
+ and secure_port != "*"
490
+ and secure_port is not None
491
+ ):
492
+ continue
493
+
494
+ # If we've gotten here, then this origin matches the current
495
+ # secure origin and we should return True
496
+ return True
497
+
498
+ # If we've gotten to this point, then the origin isn't secure and we
499
+ # will not accept it as a valid location to search. We will however
500
+ # log a warning that we are ignoring it.
501
+ logger.warning(
502
+ "The repository located at %s is not a trusted or secure host and "
503
+ "is being ignored. If this repository is available via HTTPS we "
504
+ "recommend you use HTTPS instead, otherwise you may silence "
505
+ "this warning and allow it anyway with '--trusted-host %s'.",
506
+ origin_host,
507
+ origin_host,
508
+ )
509
+
510
+ return False
511
+
512
+ def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Response:
513
+ # Allow setting a default timeout on a session
514
+ kwargs.setdefault("timeout", self.timeout)
515
+ # Allow setting a default proxies on a session
516
+ kwargs.setdefault("proxies", self.proxies)
517
+
518
+ # Dispatch the actual request
519
+ return super().request(method, url, *args, **kwargs)
.venv/Lib/site-packages/pip/_internal/network/utils.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Generator
2
+
3
+ from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
4
+
5
+ from pip._internal.exceptions import NetworkConnectionError
6
+
7
+ # The following comments and HTTP headers were originally added by
8
+ # Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03.
9
+ #
10
+ # We use Accept-Encoding: identity here because requests defaults to
11
+ # accepting compressed responses. This breaks in a variety of ways
12
+ # depending on how the server is configured.
13
+ # - Some servers will notice that the file isn't a compressible file
14
+ # and will leave the file alone and with an empty Content-Encoding
15
+ # - Some servers will notice that the file is already compressed and
16
+ # will leave the file alone, adding a Content-Encoding: gzip header
17
+ # - Some servers won't notice anything at all and will take a file
18
+ # that's already been compressed and compress it again, and set
19
+ # the Content-Encoding: gzip header
20
+ # By setting this to request only the identity encoding we're hoping
21
+ # to eliminate the third case. Hopefully there does not exist a server
22
+ # which when given a file will notice it is already compressed and that
23
+ # you're not asking for a compressed file and will then decompress it
24
+ # before sending because if that's the case I don't think it'll ever be
25
+ # possible to make this work.
26
+ HEADERS: Dict[str, str] = {"Accept-Encoding": "identity"}
27
+
28
+
29
+ def raise_for_status(resp: Response) -> None:
30
+ http_error_msg = ""
31
+ if isinstance(resp.reason, bytes):
32
+ # We attempt to decode utf-8 first because some servers
33
+ # choose to localize their reason strings. If the string
34
+ # isn't utf-8, we fall back to iso-8859-1 for all other
35
+ # encodings.
36
+ try:
37
+ reason = resp.reason.decode("utf-8")
38
+ except UnicodeDecodeError:
39
+ reason = resp.reason.decode("iso-8859-1")
40
+ else:
41
+ reason = resp.reason
42
+
43
+ if 400 <= resp.status_code < 500:
44
+ http_error_msg = (
45
+ f"{resp.status_code} Client Error: {reason} for url: {resp.url}"
46
+ )
47
+
48
+ elif 500 <= resp.status_code < 600:
49
+ http_error_msg = (
50
+ f"{resp.status_code} Server Error: {reason} for url: {resp.url}"
51
+ )
52
+
53
+ if http_error_msg:
54
+ raise NetworkConnectionError(http_error_msg, response=resp)
55
+
56
+
57
+ def response_chunks(
58
+ response: Response, chunk_size: int = CONTENT_CHUNK_SIZE
59
+ ) -> Generator[bytes, None, None]:
60
+ """Given a requests Response, provide the data chunks."""
61
+ try:
62
+ # Special case for urllib3.
63
+ for chunk in response.raw.stream(
64
+ chunk_size,
65
+ # We use decode_content=False here because we don't
66
+ # want urllib3 to mess with the raw bytes we get
67
+ # from the server. If we decompress inside of
68
+ # urllib3 then we cannot verify the checksum
69
+ # because the checksum will be of the compressed
70
+ # file. This breakage will only occur if the
71
+ # server adds a Content-Encoding header, which
72
+ # depends on how the server was configured:
73
+ # - Some servers will notice that the file isn't a
74
+ # compressible file and will leave the file alone
75
+ # and with an empty Content-Encoding
76
+ # - Some servers will notice that the file is
77
+ # already compressed and will leave the file
78
+ # alone and will add a Content-Encoding: gzip
79
+ # header
80
+ # - Some servers won't notice anything at all and
81
+ # will take a file that's already been compressed
82
+ # and compress it again and set the
83
+ # Content-Encoding: gzip header
84
+ #
85
+ # By setting this not to decode automatically we
86
+ # hope to eliminate problems with the second case.
87
+ decode_content=False,
88
+ ):
89
+ yield chunk
90
+ except AttributeError:
91
+ # Standard file-like object.
92
+ while True:
93
+ chunk = response.raw.read(chunk_size)
94
+ if not chunk:
95
+ break
96
+ yield chunk
.venv/Lib/site-packages/pip/_internal/network/xmlrpc.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """xmlrpclib.Transport implementation
2
+ """
3
+
4
+ import logging
5
+ import urllib.parse
6
+ import xmlrpc.client
7
+ from typing import TYPE_CHECKING, Tuple
8
+
9
+ from pip._internal.exceptions import NetworkConnectionError
10
+ from pip._internal.network.session import PipSession
11
+ from pip._internal.network.utils import raise_for_status
12
+
13
+ if TYPE_CHECKING:
14
+ from xmlrpc.client import _HostType, _Marshallable
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class PipXmlrpcTransport(xmlrpc.client.Transport):
20
+ """Provide a `xmlrpclib.Transport` implementation via a `PipSession`
21
+ object.
22
+ """
23
+
24
+ def __init__(
25
+ self, index_url: str, session: PipSession, use_datetime: bool = False
26
+ ) -> None:
27
+ super().__init__(use_datetime)
28
+ index_parts = urllib.parse.urlparse(index_url)
29
+ self._scheme = index_parts.scheme
30
+ self._session = session
31
+
32
+ def request(
33
+ self,
34
+ host: "_HostType",
35
+ handler: str,
36
+ request_body: bytes,
37
+ verbose: bool = False,
38
+ ) -> Tuple["_Marshallable", ...]:
39
+ assert isinstance(host, str)
40
+ parts = (self._scheme, host, handler, None, None, None)
41
+ url = urllib.parse.urlunparse(parts)
42
+ try:
43
+ headers = {"Content-Type": "text/xml"}
44
+ response = self._session.post(
45
+ url,
46
+ data=request_body,
47
+ headers=headers,
48
+ stream=True,
49
+ )
50
+ raise_for_status(response)
51
+ self.verbose = verbose
52
+ return self.parse_response(response.raw)
53
+ except NetworkConnectionError as exc:
54
+ assert exc.response
55
+ logger.critical(
56
+ "HTTP error %s while getting %s",
57
+ exc.response.status_code,
58
+ url,
59
+ )
60
+ raise
.venv/Lib/site-packages/pip/_internal/operations/__init__.py ADDED
File without changes
.venv/Lib/site-packages/pip/_internal/operations/build/__init__.py ADDED
File without changes
.venv/Lib/site-packages/pip/_internal/operations/build/build_tracker.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import hashlib
3
+ import logging
4
+ import os
5
+ from types import TracebackType
6
+ from typing import Dict, Generator, Optional, Set, Type, Union
7
+
8
+ from pip._internal.models.link import Link
9
+ from pip._internal.req.req_install import InstallRequirement
10
+ from pip._internal.utils.temp_dir import TempDirectory
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @contextlib.contextmanager
16
+ def update_env_context_manager(**changes: str) -> Generator[None, None, None]:
17
+ target = os.environ
18
+
19
+ # Save values from the target and change them.
20
+ non_existent_marker = object()
21
+ saved_values: Dict[str, Union[object, str]] = {}
22
+ for name, new_value in changes.items():
23
+ try:
24
+ saved_values[name] = target[name]
25
+ except KeyError:
26
+ saved_values[name] = non_existent_marker
27
+ target[name] = new_value
28
+
29
+ try:
30
+ yield
31
+ finally:
32
+ # Restore original values in the target.
33
+ for name, original_value in saved_values.items():
34
+ if original_value is non_existent_marker:
35
+ del target[name]
36
+ else:
37
+ assert isinstance(original_value, str) # for mypy
38
+ target[name] = original_value
39
+
40
+
41
+ @contextlib.contextmanager
42
+ def get_build_tracker() -> Generator["BuildTracker", None, None]:
43
+ root = os.environ.get("PIP_BUILD_TRACKER")
44
+ with contextlib.ExitStack() as ctx:
45
+ if root is None:
46
+ root = ctx.enter_context(TempDirectory(kind="build-tracker")).path
47
+ ctx.enter_context(update_env_context_manager(PIP_BUILD_TRACKER=root))
48
+ logger.debug("Initialized build tracking at %s", root)
49
+
50
+ with BuildTracker(root) as tracker:
51
+ yield tracker
52
+
53
+
54
+ class BuildTracker:
55
+ def __init__(self, root: str) -> None:
56
+ self._root = root
57
+ self._entries: Set[InstallRequirement] = set()
58
+ logger.debug("Created build tracker: %s", self._root)
59
+
60
+ def __enter__(self) -> "BuildTracker":
61
+ logger.debug("Entered build tracker: %s", self._root)
62
+ return self
63
+
64
+ def __exit__(
65
+ self,
66
+ exc_type: Optional[Type[BaseException]],
67
+ exc_val: Optional[BaseException],
68
+ exc_tb: Optional[TracebackType],
69
+ ) -> None:
70
+ self.cleanup()
71
+
72
+ def _entry_path(self, link: Link) -> str:
73
+ hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest()
74
+ return os.path.join(self._root, hashed)
75
+
76
+ def add(self, req: InstallRequirement) -> None:
77
+ """Add an InstallRequirement to build tracking."""
78
+
79
+ assert req.link
80
+ # Get the file to write information about this requirement.
81
+ entry_path = self._entry_path(req.link)
82
+
83
+ # Try reading from the file. If it exists and can be read from, a build
84
+ # is already in progress, so a LookupError is raised.
85
+ try:
86
+ with open(entry_path) as fp:
87
+ contents = fp.read()
88
+ except FileNotFoundError:
89
+ pass
90
+ else:
91
+ message = "{} is already being built: {}".format(req.link, contents)
92
+ raise LookupError(message)
93
+
94
+ # If we're here, req should really not be building already.
95
+ assert req not in self._entries
96
+
97
+ # Start tracking this requirement.
98
+ with open(entry_path, "w", encoding="utf-8") as fp:
99
+ fp.write(str(req))
100
+ self._entries.add(req)
101
+
102
+ logger.debug("Added %s to build tracker %r", req, self._root)
103
+
104
+ def remove(self, req: InstallRequirement) -> None:
105
+ """Remove an InstallRequirement from build tracking."""
106
+
107
+ assert req.link
108
+ # Delete the created file and the corresponding entries.
109
+ os.unlink(self._entry_path(req.link))
110
+ self._entries.remove(req)
111
+
112
+ logger.debug("Removed %s from build tracker %r", req, self._root)
113
+
114
+ def cleanup(self) -> None:
115
+ for req in set(self._entries):
116
+ self.remove(req)
117
+
118
+ logger.debug("Removed build tracker: %r", self._root)
119
+
120
+ @contextlib.contextmanager
121
+ def track(self, req: InstallRequirement) -> Generator[None, None, None]:
122
+ self.add(req)
123
+ yield
124
+ self.remove(req)
.venv/Lib/site-packages/pip/_internal/operations/build/metadata.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metadata generation logic for source distributions.
2
+ """
3
+
4
+ import os
5
+
6
+ from pip._vendor.pyproject_hooks import BuildBackendHookCaller
7
+
8
+ from pip._internal.build_env import BuildEnvironment
9
+ from pip._internal.exceptions import (
10
+ InstallationSubprocessError,
11
+ MetadataGenerationFailed,
12
+ )
13
+ from pip._internal.utils.subprocess import runner_with_spinner_message
14
+ from pip._internal.utils.temp_dir import TempDirectory
15
+
16
+
17
+ def generate_metadata(
18
+ build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str
19
+ ) -> str:
20
+ """Generate metadata using mechanisms described in PEP 517.
21
+
22
+ Returns the generated metadata directory.
23
+ """
24
+ metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True)
25
+
26
+ metadata_dir = metadata_tmpdir.path
27
+
28
+ with build_env:
29
+ # Note that BuildBackendHookCaller implements a fallback for
30
+ # prepare_metadata_for_build_wheel, so we don't have to
31
+ # consider the possibility that this hook doesn't exist.
32
+ runner = runner_with_spinner_message("Preparing metadata (pyproject.toml)")
33
+ with backend.subprocess_runner(runner):
34
+ try:
35
+ distinfo_dir = backend.prepare_metadata_for_build_wheel(metadata_dir)
36
+ except InstallationSubprocessError as error:
37
+ raise MetadataGenerationFailed(package_details=details) from error
38
+
39
+ return os.path.join(metadata_dir, distinfo_dir)
.venv/Lib/site-packages/pip/_internal/operations/build/metadata_editable.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metadata generation logic for source distributions.
2
+ """
3
+
4
+ import os
5
+
6
+ from pip._vendor.pyproject_hooks import BuildBackendHookCaller
7
+
8
+ from pip._internal.build_env import BuildEnvironment
9
+ from pip._internal.exceptions import (
10
+ InstallationSubprocessError,
11
+ MetadataGenerationFailed,
12
+ )
13
+ from pip._internal.utils.subprocess import runner_with_spinner_message
14
+ from pip._internal.utils.temp_dir import TempDirectory
15
+
16
+
17
+ def generate_editable_metadata(
18
+ build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str
19
+ ) -> str:
20
+ """Generate metadata using mechanisms described in PEP 660.
21
+
22
+ Returns the generated metadata directory.
23
+ """
24
+ metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True)
25
+
26
+ metadata_dir = metadata_tmpdir.path
27
+
28
+ with build_env:
29
+ # Note that BuildBackendHookCaller implements a fallback for
30
+ # prepare_metadata_for_build_wheel/editable, so we don't have to
31
+ # consider the possibility that this hook doesn't exist.
32
+ runner = runner_with_spinner_message(
33
+ "Preparing editable metadata (pyproject.toml)"
34
+ )
35
+ with backend.subprocess_runner(runner):
36
+ try:
37
+ distinfo_dir = backend.prepare_metadata_for_build_editable(metadata_dir)
38
+ except InstallationSubprocessError as error:
39
+ raise MetadataGenerationFailed(package_details=details) from error
40
+
41
+ return os.path.join(metadata_dir, distinfo_dir)
.venv/Lib/site-packages/pip/_internal/operations/build/metadata_legacy.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metadata generation logic for legacy source distributions.
2
+ """
3
+
4
+ import logging
5
+ import os
6
+
7
+ from pip._internal.build_env import BuildEnvironment
8
+ from pip._internal.cli.spinners import open_spinner
9
+ from pip._internal.exceptions import (
10
+ InstallationError,
11
+ InstallationSubprocessError,
12
+ MetadataGenerationFailed,
13
+ )
14
+ from pip._internal.utils.setuptools_build import make_setuptools_egg_info_args
15
+ from pip._internal.utils.subprocess import call_subprocess
16
+ from pip._internal.utils.temp_dir import TempDirectory
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def _find_egg_info(directory: str) -> str:
22
+ """Find an .egg-info subdirectory in `directory`."""
23
+ filenames = [f for f in os.listdir(directory) if f.endswith(".egg-info")]
24
+
25
+ if not filenames:
26
+ raise InstallationError(f"No .egg-info directory found in {directory}")
27
+
28
+ if len(filenames) > 1:
29
+ raise InstallationError(
30
+ "More than one .egg-info directory found in {}".format(directory)
31
+ )
32
+
33
+ return os.path.join(directory, filenames[0])
34
+
35
+
36
+ def generate_metadata(
37
+ build_env: BuildEnvironment,
38
+ setup_py_path: str,
39
+ source_dir: str,
40
+ isolated: bool,
41
+ details: str,
42
+ ) -> str:
43
+ """Generate metadata using setup.py-based defacto mechanisms.
44
+
45
+ Returns the generated metadata directory.
46
+ """
47
+ logger.debug(
48
+ "Running setup.py (path:%s) egg_info for package %s",
49
+ setup_py_path,
50
+ details,
51
+ )
52
+
53
+ egg_info_dir = TempDirectory(kind="pip-egg-info", globally_managed=True).path
54
+
55
+ args = make_setuptools_egg_info_args(
56
+ setup_py_path,
57
+ egg_info_dir=egg_info_dir,
58
+ no_user_config=isolated,
59
+ )
60
+
61
+ with build_env:
62
+ with open_spinner("Preparing metadata (setup.py)") as spinner:
63
+ try:
64
+ call_subprocess(
65
+ args,
66
+ cwd=source_dir,
67
+ command_desc="python setup.py egg_info",
68
+ spinner=spinner,
69
+ )
70
+ except InstallationSubprocessError as error:
71
+ raise MetadataGenerationFailed(package_details=details) from error
72
+
73
+ # Return the .egg-info directory.
74
+ return _find_egg_info(egg_info_dir)
.venv/Lib/site-packages/pip/_internal/operations/build/wheel.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from typing import Optional
4
+
5
+ from pip._vendor.pyproject_hooks import BuildBackendHookCaller
6
+
7
+ from pip._internal.utils.subprocess import runner_with_spinner_message
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def build_wheel_pep517(
13
+ name: str,
14
+ backend: BuildBackendHookCaller,
15
+ metadata_directory: str,
16
+ tempd: str,
17
+ ) -> Optional[str]:
18
+ """Build one InstallRequirement using the PEP 517 build process.
19
+
20
+ Returns path to wheel if successfully built. Otherwise, returns None.
21
+ """
22
+ assert metadata_directory is not None
23
+ try:
24
+ logger.debug("Destination directory: %s", tempd)
25
+
26
+ runner = runner_with_spinner_message(
27
+ f"Building wheel for {name} (pyproject.toml)"
28
+ )
29
+ with backend.subprocess_runner(runner):
30
+ wheel_name = backend.build_wheel(
31
+ tempd,
32
+ metadata_directory=metadata_directory,
33
+ )
34
+ except Exception:
35
+ logger.error("Failed building wheel for %s", name)
36
+ return None
37
+ return os.path.join(tempd, wheel_name)
.venv/Lib/site-packages/pip/_internal/operations/build/wheel_editable.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from typing import Optional
4
+
5
+ from pip._vendor.pyproject_hooks import BuildBackendHookCaller, HookMissing
6
+
7
+ from pip._internal.utils.subprocess import runner_with_spinner_message
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def build_wheel_editable(
13
+ name: str,
14
+ backend: BuildBackendHookCaller,
15
+ metadata_directory: str,
16
+ tempd: str,
17
+ ) -> Optional[str]:
18
+ """Build one InstallRequirement using the PEP 660 build process.
19
+
20
+ Returns path to wheel if successfully built. Otherwise, returns None.
21
+ """
22
+ assert metadata_directory is not None
23
+ try:
24
+ logger.debug("Destination directory: %s", tempd)
25
+
26
+ runner = runner_with_spinner_message(
27
+ f"Building editable for {name} (pyproject.toml)"
28
+ )
29
+ with backend.subprocess_runner(runner):
30
+ try:
31
+ wheel_name = backend.build_editable(
32
+ tempd,
33
+ metadata_directory=metadata_directory,
34
+ )
35
+ except HookMissing as e:
36
+ logger.error(
37
+ "Cannot build editable %s because the build "
38
+ "backend does not have the %s hook",
39
+ name,
40
+ e,
41
+ )
42
+ return None
43
+ except Exception:
44
+ logger.error("Failed building editable for %s", name)
45
+ return None
46
+ return os.path.join(tempd, wheel_name)
.venv/Lib/site-packages/pip/_internal/operations/build/wheel_legacy.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os.path
3
+ from typing import List, Optional
4
+
5
+ from pip._internal.cli.spinners import open_spinner
6
+ from pip._internal.utils.setuptools_build import make_setuptools_bdist_wheel_args
7
+ from pip._internal.utils.subprocess import call_subprocess, format_command_args
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def format_command_result(
13
+ command_args: List[str],
14
+ command_output: str,
15
+ ) -> str:
16
+ """Format command information for logging."""
17
+ command_desc = format_command_args(command_args)
18
+ text = f"Command arguments: {command_desc}\n"
19
+
20
+ if not command_output:
21
+ text += "Command output: None"
22
+ elif logger.getEffectiveLevel() > logging.DEBUG:
23
+ text += "Command output: [use --verbose to show]"
24
+ else:
25
+ if not command_output.endswith("\n"):
26
+ command_output += "\n"
27
+ text += f"Command output:\n{command_output}"
28
+
29
+ return text
30
+
31
+
32
+ def get_legacy_build_wheel_path(
33
+ names: List[str],
34
+ temp_dir: str,
35
+ name: str,
36
+ command_args: List[str],
37
+ command_output: str,
38
+ ) -> Optional[str]:
39
+ """Return the path to the wheel in the temporary build directory."""
40
+ # Sort for determinism.
41
+ names = sorted(names)
42
+ if not names:
43
+ msg = ("Legacy build of wheel for {!r} created no files.\n").format(name)
44
+ msg += format_command_result(command_args, command_output)
45
+ logger.warning(msg)
46
+ return None
47
+
48
+ if len(names) > 1:
49
+ msg = (
50
+ "Legacy build of wheel for {!r} created more than one file.\n"
51
+ "Filenames (choosing first): {}\n"
52
+ ).format(name, names)
53
+ msg += format_command_result(command_args, command_output)
54
+ logger.warning(msg)
55
+
56
+ return os.path.join(temp_dir, names[0])
57
+
58
+
59
+ def build_wheel_legacy(
60
+ name: str,
61
+ setup_py_path: str,
62
+ source_dir: str,
63
+ global_options: List[str],
64
+ build_options: List[str],
65
+ tempd: str,
66
+ ) -> Optional[str]:
67
+ """Build one unpacked package using the "legacy" build process.
68
+
69
+ Returns path to wheel if successfully built. Otherwise, returns None.
70
+ """
71
+ wheel_args = make_setuptools_bdist_wheel_args(
72
+ setup_py_path,
73
+ global_options=global_options,
74
+ build_options=build_options,
75
+ destination_dir=tempd,
76
+ )
77
+
78
+ spin_message = f"Building wheel for {name} (setup.py)"
79
+ with open_spinner(spin_message) as spinner:
80
+ logger.debug("Destination directory: %s", tempd)
81
+
82
+ try:
83
+ output = call_subprocess(
84
+ wheel_args,
85
+ command_desc="python setup.py bdist_wheel",
86
+ cwd=source_dir,
87
+ spinner=spinner,
88
+ )
89
+ except Exception:
90
+ spinner.finish("error")
91
+ logger.error("Failed building wheel for %s", name)
92
+ return None
93
+
94
+ names = os.listdir(tempd)
95
+ wheel_path = get_legacy_build_wheel_path(
96
+ names=names,
97
+ temp_dir=tempd,
98
+ name=name,
99
+ command_args=wheel_args,
100
+ command_output=output,
101
+ )
102
+ return wheel_path
.venv/Lib/site-packages/pip/_internal/operations/check.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validation of dependencies of packages
2
+ """
3
+
4
+ import logging
5
+ from typing import Callable, Dict, List, NamedTuple, Optional, Set, Tuple
6
+
7
+ from pip._vendor.packaging.requirements import Requirement
8
+ from pip._vendor.packaging.specifiers import LegacySpecifier
9
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
10
+ from pip._vendor.packaging.version import LegacyVersion
11
+
12
+ from pip._internal.distributions import make_distribution_for_install_requirement
13
+ from pip._internal.metadata import get_default_environment
14
+ from pip._internal.metadata.base import DistributionVersion
15
+ from pip._internal.req.req_install import InstallRequirement
16
+ from pip._internal.utils.deprecation import deprecated
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class PackageDetails(NamedTuple):
22
+ version: DistributionVersion
23
+ dependencies: List[Requirement]
24
+
25
+
26
+ # Shorthands
27
+ PackageSet = Dict[NormalizedName, PackageDetails]
28
+ Missing = Tuple[NormalizedName, Requirement]
29
+ Conflicting = Tuple[NormalizedName, DistributionVersion, Requirement]
30
+
31
+ MissingDict = Dict[NormalizedName, List[Missing]]
32
+ ConflictingDict = Dict[NormalizedName, List[Conflicting]]
33
+ CheckResult = Tuple[MissingDict, ConflictingDict]
34
+ ConflictDetails = Tuple[PackageSet, CheckResult]
35
+
36
+
37
+ def create_package_set_from_installed() -> Tuple[PackageSet, bool]:
38
+ """Converts a list of distributions into a PackageSet."""
39
+ package_set = {}
40
+ problems = False
41
+ env = get_default_environment()
42
+ for dist in env.iter_installed_distributions(local_only=False, skip=()):
43
+ name = dist.canonical_name
44
+ try:
45
+ dependencies = list(dist.iter_dependencies())
46
+ package_set[name] = PackageDetails(dist.version, dependencies)
47
+ except (OSError, ValueError) as e:
48
+ # Don't crash on unreadable or broken metadata.
49
+ logger.warning("Error parsing requirements for %s: %s", name, e)
50
+ problems = True
51
+ return package_set, problems
52
+
53
+
54
+ def check_package_set(
55
+ package_set: PackageSet, should_ignore: Optional[Callable[[str], bool]] = None
56
+ ) -> CheckResult:
57
+ """Check if a package set is consistent
58
+
59
+ If should_ignore is passed, it should be a callable that takes a
60
+ package name and returns a boolean.
61
+ """
62
+
63
+ warn_legacy_versions_and_specifiers(package_set)
64
+
65
+ missing = {}
66
+ conflicting = {}
67
+
68
+ for package_name, package_detail in package_set.items():
69
+ # Info about dependencies of package_name
70
+ missing_deps: Set[Missing] = set()
71
+ conflicting_deps: Set[Conflicting] = set()
72
+
73
+ if should_ignore and should_ignore(package_name):
74
+ continue
75
+
76
+ for req in package_detail.dependencies:
77
+ name = canonicalize_name(req.name)
78
+
79
+ # Check if it's missing
80
+ if name not in package_set:
81
+ missed = True
82
+ if req.marker is not None:
83
+ missed = req.marker.evaluate({"extra": ""})
84
+ if missed:
85
+ missing_deps.add((name, req))
86
+ continue
87
+
88
+ # Check if there's a conflict
89
+ version = package_set[name].version
90
+ if not req.specifier.contains(version, prereleases=True):
91
+ conflicting_deps.add((name, version, req))
92
+
93
+ if missing_deps:
94
+ missing[package_name] = sorted(missing_deps, key=str)
95
+ if conflicting_deps:
96
+ conflicting[package_name] = sorted(conflicting_deps, key=str)
97
+
98
+ return missing, conflicting
99
+
100
+
101
+ def check_install_conflicts(to_install: List[InstallRequirement]) -> ConflictDetails:
102
+ """For checking if the dependency graph would be consistent after \
103
+ installing given requirements
104
+ """
105
+ # Start from the current state
106
+ package_set, _ = create_package_set_from_installed()
107
+ # Install packages
108
+ would_be_installed = _simulate_installation_of(to_install, package_set)
109
+
110
+ # Only warn about directly-dependent packages; create a whitelist of them
111
+ whitelist = _create_whitelist(would_be_installed, package_set)
112
+
113
+ return (
114
+ package_set,
115
+ check_package_set(
116
+ package_set, should_ignore=lambda name: name not in whitelist
117
+ ),
118
+ )
119
+
120
+
121
+ def _simulate_installation_of(
122
+ to_install: List[InstallRequirement], package_set: PackageSet
123
+ ) -> Set[NormalizedName]:
124
+ """Computes the version of packages after installing to_install."""
125
+ # Keep track of packages that were installed
126
+ installed = set()
127
+
128
+ # Modify it as installing requirement_set would (assuming no errors)
129
+ for inst_req in to_install:
130
+ abstract_dist = make_distribution_for_install_requirement(inst_req)
131
+ dist = abstract_dist.get_metadata_distribution()
132
+ name = dist.canonical_name
133
+ package_set[name] = PackageDetails(dist.version, list(dist.iter_dependencies()))
134
+
135
+ installed.add(name)
136
+
137
+ return installed
138
+
139
+
140
+ def _create_whitelist(
141
+ would_be_installed: Set[NormalizedName], package_set: PackageSet
142
+ ) -> Set[NormalizedName]:
143
+ packages_affected = set(would_be_installed)
144
+
145
+ for package_name in package_set:
146
+ if package_name in packages_affected:
147
+ continue
148
+
149
+ for req in package_set[package_name].dependencies:
150
+ if canonicalize_name(req.name) in packages_affected:
151
+ packages_affected.add(package_name)
152
+ break
153
+
154
+ return packages_affected
155
+
156
+
157
+ def warn_legacy_versions_and_specifiers(package_set: PackageSet) -> None:
158
+ for project_name, package_details in package_set.items():
159
+ if isinstance(package_details.version, LegacyVersion):
160
+ deprecated(
161
+ reason=(
162
+ f"{project_name} {package_details.version} "
163
+ f"has a non-standard version number."
164
+ ),
165
+ replacement=(
166
+ f"to upgrade to a newer version of {project_name} "
167
+ f"or contact the author to suggest that they "
168
+ f"release a version with a conforming version number"
169
+ ),
170
+ issue=12063,
171
+ gone_in="23.3",
172
+ )
173
+ for dep in package_details.dependencies:
174
+ if any(isinstance(spec, LegacySpecifier) for spec in dep.specifier):
175
+ deprecated(
176
+ reason=(
177
+ f"{project_name} {package_details.version} "
178
+ f"has a non-standard dependency specifier {dep}."
179
+ ),
180
+ replacement=(
181
+ f"to upgrade to a newer version of {project_name} "
182
+ f"or contact the author to suggest that they "
183
+ f"release a version with a conforming dependency specifiers"
184
+ ),
185
+ issue=12063,
186
+ gone_in="23.3",
187
+ )
.venv/Lib/site-packages/pip/_internal/operations/freeze.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import logging
3
+ import os
4
+ from typing import Container, Dict, Generator, Iterable, List, NamedTuple, Optional, Set
5
+
6
+ from pip._vendor.packaging.utils import canonicalize_name
7
+ from pip._vendor.packaging.version import Version
8
+
9
+ from pip._internal.exceptions import BadCommand, InstallationError
10
+ from pip._internal.metadata import BaseDistribution, get_environment
11
+ from pip._internal.req.constructors import (
12
+ install_req_from_editable,
13
+ install_req_from_line,
14
+ )
15
+ from pip._internal.req.req_file import COMMENT_RE
16
+ from pip._internal.utils.direct_url_helpers import direct_url_as_pep440_direct_reference
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class _EditableInfo(NamedTuple):
22
+ requirement: str
23
+ comments: List[str]
24
+
25
+
26
+ def freeze(
27
+ requirement: Optional[List[str]] = None,
28
+ local_only: bool = False,
29
+ user_only: bool = False,
30
+ paths: Optional[List[str]] = None,
31
+ isolated: bool = False,
32
+ exclude_editable: bool = False,
33
+ skip: Container[str] = (),
34
+ ) -> Generator[str, None, None]:
35
+ installations: Dict[str, FrozenRequirement] = {}
36
+
37
+ dists = get_environment(paths).iter_installed_distributions(
38
+ local_only=local_only,
39
+ skip=(),
40
+ user_only=user_only,
41
+ )
42
+ for dist in dists:
43
+ req = FrozenRequirement.from_dist(dist)
44
+ if exclude_editable and req.editable:
45
+ continue
46
+ installations[req.canonical_name] = req
47
+
48
+ if requirement:
49
+ # the options that don't get turned into an InstallRequirement
50
+ # should only be emitted once, even if the same option is in multiple
51
+ # requirements files, so we need to keep track of what has been emitted
52
+ # so that we don't emit it again if it's seen again
53
+ emitted_options: Set[str] = set()
54
+ # keep track of which files a requirement is in so that we can
55
+ # give an accurate warning if a requirement appears multiple times.
56
+ req_files: Dict[str, List[str]] = collections.defaultdict(list)
57
+ for req_file_path in requirement:
58
+ with open(req_file_path) as req_file:
59
+ for line in req_file:
60
+ if (
61
+ not line.strip()
62
+ or line.strip().startswith("#")
63
+ or line.startswith(
64
+ (
65
+ "-r",
66
+ "--requirement",
67
+ "-f",
68
+ "--find-links",
69
+ "-i",
70
+ "--index-url",
71
+ "--pre",
72
+ "--trusted-host",
73
+ "--process-dependency-links",
74
+ "--extra-index-url",
75
+ "--use-feature",
76
+ )
77
+ )
78
+ ):
79
+ line = line.rstrip()
80
+ if line not in emitted_options:
81
+ emitted_options.add(line)
82
+ yield line
83
+ continue
84
+
85
+ if line.startswith("-e") or line.startswith("--editable"):
86
+ if line.startswith("-e"):
87
+ line = line[2:].strip()
88
+ else:
89
+ line = line[len("--editable") :].strip().lstrip("=")
90
+ line_req = install_req_from_editable(
91
+ line,
92
+ isolated=isolated,
93
+ )
94
+ else:
95
+ line_req = install_req_from_line(
96
+ COMMENT_RE.sub("", line).strip(),
97
+ isolated=isolated,
98
+ )
99
+
100
+ if not line_req.name:
101
+ logger.info(
102
+ "Skipping line in requirement file [%s] because "
103
+ "it's not clear what it would install: %s",
104
+ req_file_path,
105
+ line.strip(),
106
+ )
107
+ logger.info(
108
+ " (add #egg=PackageName to the URL to avoid"
109
+ " this warning)"
110
+ )
111
+ else:
112
+ line_req_canonical_name = canonicalize_name(line_req.name)
113
+ if line_req_canonical_name not in installations:
114
+ # either it's not installed, or it is installed
115
+ # but has been processed already
116
+ if not req_files[line_req.name]:
117
+ logger.warning(
118
+ "Requirement file [%s] contains %s, but "
119
+ "package %r is not installed",
120
+ req_file_path,
121
+ COMMENT_RE.sub("", line).strip(),
122
+ line_req.name,
123
+ )
124
+ else:
125
+ req_files[line_req.name].append(req_file_path)
126
+ else:
127
+ yield str(installations[line_req_canonical_name]).rstrip()
128
+ del installations[line_req_canonical_name]
129
+ req_files[line_req.name].append(req_file_path)
130
+
131
+ # Warn about requirements that were included multiple times (in a
132
+ # single requirements file or in different requirements files).
133
+ for name, files in req_files.items():
134
+ if len(files) > 1:
135
+ logger.warning(
136
+ "Requirement %s included multiple times [%s]",
137
+ name,
138
+ ", ".join(sorted(set(files))),
139
+ )
140
+
141
+ yield ("## The following requirements were added by pip freeze:")
142
+ for installation in sorted(installations.values(), key=lambda x: x.name.lower()):
143
+ if installation.canonical_name not in skip:
144
+ yield str(installation).rstrip()
145
+
146
+
147
+ def _format_as_name_version(dist: BaseDistribution) -> str:
148
+ dist_version = dist.version
149
+ if isinstance(dist_version, Version):
150
+ return f"{dist.raw_name}=={dist_version}"
151
+ return f"{dist.raw_name}==={dist_version}"
152
+
153
+
154
+ def _get_editable_info(dist: BaseDistribution) -> _EditableInfo:
155
+ """
156
+ Compute and return values (req, comments) for use in
157
+ FrozenRequirement.from_dist().
158
+ """
159
+ editable_project_location = dist.editable_project_location
160
+ assert editable_project_location
161
+ location = os.path.normcase(os.path.abspath(editable_project_location))
162
+
163
+ from pip._internal.vcs import RemoteNotFoundError, RemoteNotValidError, vcs
164
+
165
+ vcs_backend = vcs.get_backend_for_dir(location)
166
+
167
+ if vcs_backend is None:
168
+ display = _format_as_name_version(dist)
169
+ logger.debug(
170
+ 'No VCS found for editable requirement "%s" in: %r',
171
+ display,
172
+ location,
173
+ )
174
+ return _EditableInfo(
175
+ requirement=location,
176
+ comments=[f"# Editable install with no version control ({display})"],
177
+ )
178
+
179
+ vcs_name = type(vcs_backend).__name__
180
+
181
+ try:
182
+ req = vcs_backend.get_src_requirement(location, dist.raw_name)
183
+ except RemoteNotFoundError:
184
+ display = _format_as_name_version(dist)
185
+ return _EditableInfo(
186
+ requirement=location,
187
+ comments=[f"# Editable {vcs_name} install with no remote ({display})"],
188
+ )
189
+ except RemoteNotValidError as ex:
190
+ display = _format_as_name_version(dist)
191
+ return _EditableInfo(
192
+ requirement=location,
193
+ comments=[
194
+ f"# Editable {vcs_name} install ({display}) with either a deleted "
195
+ f"local remote or invalid URI:",
196
+ f"# '{ex.url}'",
197
+ ],
198
+ )
199
+ except BadCommand:
200
+ logger.warning(
201
+ "cannot determine version of editable source in %s "
202
+ "(%s command not found in path)",
203
+ location,
204
+ vcs_backend.name,
205
+ )
206
+ return _EditableInfo(requirement=location, comments=[])
207
+ except InstallationError as exc:
208
+ logger.warning("Error when trying to get requirement for VCS system %s", exc)
209
+ else:
210
+ return _EditableInfo(requirement=req, comments=[])
211
+
212
+ logger.warning("Could not determine repository location of %s", location)
213
+
214
+ return _EditableInfo(
215
+ requirement=location,
216
+ comments=["## !! Could not determine repository location"],
217
+ )
218
+
219
+
220
+ class FrozenRequirement:
221
+ def __init__(
222
+ self,
223
+ name: str,
224
+ req: str,
225
+ editable: bool,
226
+ comments: Iterable[str] = (),
227
+ ) -> None:
228
+ self.name = name
229
+ self.canonical_name = canonicalize_name(name)
230
+ self.req = req
231
+ self.editable = editable
232
+ self.comments = comments
233
+
234
+ @classmethod
235
+ def from_dist(cls, dist: BaseDistribution) -> "FrozenRequirement":
236
+ editable = dist.editable
237
+ if editable:
238
+ req, comments = _get_editable_info(dist)
239
+ else:
240
+ comments = []
241
+ direct_url = dist.direct_url
242
+ if direct_url:
243
+ # if PEP 610 metadata is present, use it
244
+ req = direct_url_as_pep440_direct_reference(direct_url, dist.raw_name)
245
+ else:
246
+ # name==version requirement
247
+ req = _format_as_name_version(dist)
248
+
249
+ return cls(dist.raw_name, req, editable, comments=comments)
250
+
251
+ def __str__(self) -> str:
252
+ req = self.req
253
+ if self.editable:
254
+ req = f"-e {req}"
255
+ return "\n".join(list(self.comments) + [str(req)]) + "\n"
.venv/Lib/site-packages/pip/_internal/operations/install/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """For modules related to installing packages.
2
+ """
.venv/Lib/site-packages/pip/_internal/operations/install/editable_legacy.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Legacy editable installation process, i.e. `setup.py develop`.
2
+ """
3
+ import logging
4
+ from typing import Optional, Sequence
5
+
6
+ from pip._internal.build_env import BuildEnvironment
7
+ from pip._internal.utils.logging import indent_log
8
+ from pip._internal.utils.setuptools_build import make_setuptools_develop_args
9
+ from pip._internal.utils.subprocess import call_subprocess
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def install_editable(
15
+ *,
16
+ global_options: Sequence[str],
17
+ prefix: Optional[str],
18
+ home: Optional[str],
19
+ use_user_site: bool,
20
+ name: str,
21
+ setup_py_path: str,
22
+ isolated: bool,
23
+ build_env: BuildEnvironment,
24
+ unpacked_source_directory: str,
25
+ ) -> None:
26
+ """Install a package in editable mode. Most arguments are pass-through
27
+ to setuptools.
28
+ """
29
+ logger.info("Running setup.py develop for %s", name)
30
+
31
+ args = make_setuptools_develop_args(
32
+ setup_py_path,
33
+ global_options=global_options,
34
+ no_user_config=isolated,
35
+ prefix=prefix,
36
+ home=home,
37
+ use_user_site=use_user_site,
38
+ )
39
+
40
+ with indent_log():
41
+ with build_env:
42
+ call_subprocess(
43
+ args,
44
+ command_desc="python setup.py develop",
45
+ cwd=unpacked_source_directory,
46
+ )
.venv/Lib/site-packages/pip/_internal/operations/install/wheel.py ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support for installing and building the "wheel" binary package format.
2
+ """
3
+
4
+ import collections
5
+ import compileall
6
+ import contextlib
7
+ import csv
8
+ import importlib
9
+ import logging
10
+ import os.path
11
+ import re
12
+ import shutil
13
+ import sys
14
+ import warnings
15
+ from base64 import urlsafe_b64encode
16
+ from email.message import Message
17
+ from itertools import chain, filterfalse, starmap
18
+ from typing import (
19
+ IO,
20
+ TYPE_CHECKING,
21
+ Any,
22
+ BinaryIO,
23
+ Callable,
24
+ Dict,
25
+ Generator,
26
+ Iterable,
27
+ Iterator,
28
+ List,
29
+ NewType,
30
+ Optional,
31
+ Sequence,
32
+ Set,
33
+ Tuple,
34
+ Union,
35
+ cast,
36
+ )
37
+ from zipfile import ZipFile, ZipInfo
38
+
39
+ from pip._vendor.distlib.scripts import ScriptMaker
40
+ from pip._vendor.distlib.util import get_export_entry
41
+ from pip._vendor.packaging.utils import canonicalize_name
42
+
43
+ from pip._internal.exceptions import InstallationError
44
+ from pip._internal.locations import get_major_minor_version
45
+ from pip._internal.metadata import (
46
+ BaseDistribution,
47
+ FilesystemWheel,
48
+ get_wheel_distribution,
49
+ )
50
+ from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl
51
+ from pip._internal.models.scheme import SCHEME_KEYS, Scheme
52
+ from pip._internal.utils.filesystem import adjacent_tmp_file, replace
53
+ from pip._internal.utils.misc import captured_stdout, ensure_dir, hash_file, partition
54
+ from pip._internal.utils.unpacking import (
55
+ current_umask,
56
+ is_within_directory,
57
+ set_extracted_file_to_default_mode_plus_executable,
58
+ zip_item_is_executable,
59
+ )
60
+ from pip._internal.utils.wheel import parse_wheel
61
+
62
+ if TYPE_CHECKING:
63
+ from typing import Protocol
64
+
65
+ class File(Protocol):
66
+ src_record_path: "RecordPath"
67
+ dest_path: str
68
+ changed: bool
69
+
70
+ def save(self) -> None:
71
+ pass
72
+
73
+
74
+ logger = logging.getLogger(__name__)
75
+
76
+ RecordPath = NewType("RecordPath", str)
77
+ InstalledCSVRow = Tuple[RecordPath, str, Union[int, str]]
78
+
79
+
80
+ def rehash(path: str, blocksize: int = 1 << 20) -> Tuple[str, str]:
81
+ """Return (encoded_digest, length) for path using hashlib.sha256()"""
82
+ h, length = hash_file(path, blocksize)
83
+ digest = "sha256=" + urlsafe_b64encode(h.digest()).decode("latin1").rstrip("=")
84
+ return (digest, str(length))
85
+
86
+
87
+ def csv_io_kwargs(mode: str) -> Dict[str, Any]:
88
+ """Return keyword arguments to properly open a CSV file
89
+ in the given mode.
90
+ """
91
+ return {"mode": mode, "newline": "", "encoding": "utf-8"}
92
+
93
+
94
+ def fix_script(path: str) -> bool:
95
+ """Replace #!python with #!/path/to/python
96
+ Return True if file was changed.
97
+ """
98
+ # XXX RECORD hashes will need to be updated
99
+ assert os.path.isfile(path)
100
+
101
+ with open(path, "rb") as script:
102
+ firstline = script.readline()
103
+ if not firstline.startswith(b"#!python"):
104
+ return False
105
+ exename = sys.executable.encode(sys.getfilesystemencoding())
106
+ firstline = b"#!" + exename + os.linesep.encode("ascii")
107
+ rest = script.read()
108
+ with open(path, "wb") as script:
109
+ script.write(firstline)
110
+ script.write(rest)
111
+ return True
112
+
113
+
114
+ def wheel_root_is_purelib(metadata: Message) -> bool:
115
+ return metadata.get("Root-Is-Purelib", "").lower() == "true"
116
+
117
+
118
+ def get_entrypoints(dist: BaseDistribution) -> Tuple[Dict[str, str], Dict[str, str]]:
119
+ console_scripts = {}
120
+ gui_scripts = {}
121
+ for entry_point in dist.iter_entry_points():
122
+ if entry_point.group == "console_scripts":
123
+ console_scripts[entry_point.name] = entry_point.value
124
+ elif entry_point.group == "gui_scripts":
125
+ gui_scripts[entry_point.name] = entry_point.value
126
+ return console_scripts, gui_scripts
127
+
128
+
129
+ def message_about_scripts_not_on_PATH(scripts: Sequence[str]) -> Optional[str]:
130
+ """Determine if any scripts are not on PATH and format a warning.
131
+ Returns a warning message if one or more scripts are not on PATH,
132
+ otherwise None.
133
+ """
134
+ if not scripts:
135
+ return None
136
+
137
+ # Group scripts by the path they were installed in
138
+ grouped_by_dir: Dict[str, Set[str]] = collections.defaultdict(set)
139
+ for destfile in scripts:
140
+ parent_dir = os.path.dirname(destfile)
141
+ script_name = os.path.basename(destfile)
142
+ grouped_by_dir[parent_dir].add(script_name)
143
+
144
+ # We don't want to warn for directories that are on PATH.
145
+ not_warn_dirs = [
146
+ os.path.normcase(os.path.normpath(i)).rstrip(os.sep)
147
+ for i in os.environ.get("PATH", "").split(os.pathsep)
148
+ ]
149
+ # If an executable sits with sys.executable, we don't warn for it.
150
+ # This covers the case of venv invocations without activating the venv.
151
+ not_warn_dirs.append(
152
+ os.path.normcase(os.path.normpath(os.path.dirname(sys.executable)))
153
+ )
154
+ warn_for: Dict[str, Set[str]] = {
155
+ parent_dir: scripts
156
+ for parent_dir, scripts in grouped_by_dir.items()
157
+ if os.path.normcase(os.path.normpath(parent_dir)) not in not_warn_dirs
158
+ }
159
+ if not warn_for:
160
+ return None
161
+
162
+ # Format a message
163
+ msg_lines = []
164
+ for parent_dir, dir_scripts in warn_for.items():
165
+ sorted_scripts: List[str] = sorted(dir_scripts)
166
+ if len(sorted_scripts) == 1:
167
+ start_text = "script {} is".format(sorted_scripts[0])
168
+ else:
169
+ start_text = "scripts {} are".format(
170
+ ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1]
171
+ )
172
+
173
+ msg_lines.append(
174
+ "The {} installed in '{}' which is not on PATH.".format(
175
+ start_text, parent_dir
176
+ )
177
+ )
178
+
179
+ last_line_fmt = (
180
+ "Consider adding {} to PATH or, if you prefer "
181
+ "to suppress this warning, use --no-warn-script-location."
182
+ )
183
+ if len(msg_lines) == 1:
184
+ msg_lines.append(last_line_fmt.format("this directory"))
185
+ else:
186
+ msg_lines.append(last_line_fmt.format("these directories"))
187
+
188
+ # Add a note if any directory starts with ~
189
+ warn_for_tilde = any(
190
+ i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i
191
+ )
192
+ if warn_for_tilde:
193
+ tilde_warning_msg = (
194
+ "NOTE: The current PATH contains path(s) starting with `~`, "
195
+ "which may not be expanded by all applications."
196
+ )
197
+ msg_lines.append(tilde_warning_msg)
198
+
199
+ # Returns the formatted multiline message
200
+ return "\n".join(msg_lines)
201
+
202
+
203
+ def _normalized_outrows(
204
+ outrows: Iterable[InstalledCSVRow],
205
+ ) -> List[Tuple[str, str, str]]:
206
+ """Normalize the given rows of a RECORD file.
207
+
208
+ Items in each row are converted into str. Rows are then sorted to make
209
+ the value more predictable for tests.
210
+
211
+ Each row is a 3-tuple (path, hash, size) and corresponds to a record of
212
+ a RECORD file (see PEP 376 and PEP 427 for details). For the rows
213
+ passed to this function, the size can be an integer as an int or string,
214
+ or the empty string.
215
+ """
216
+ # Normally, there should only be one row per path, in which case the
217
+ # second and third elements don't come into play when sorting.
218
+ # However, in cases in the wild where a path might happen to occur twice,
219
+ # we don't want the sort operation to trigger an error (but still want
220
+ # determinism). Since the third element can be an int or string, we
221
+ # coerce each element to a string to avoid a TypeError in this case.
222
+ # For additional background, see--
223
+ # https://github.com/pypa/pip/issues/5868
224
+ return sorted(
225
+ (record_path, hash_, str(size)) for record_path, hash_, size in outrows
226
+ )
227
+
228
+
229
+ def _record_to_fs_path(record_path: RecordPath, lib_dir: str) -> str:
230
+ return os.path.join(lib_dir, record_path)
231
+
232
+
233
+ def _fs_to_record_path(path: str, lib_dir: str) -> RecordPath:
234
+ # On Windows, do not handle relative paths if they belong to different
235
+ # logical disks
236
+ if os.path.splitdrive(path)[0].lower() == os.path.splitdrive(lib_dir)[0].lower():
237
+ path = os.path.relpath(path, lib_dir)
238
+
239
+ path = path.replace(os.path.sep, "/")
240
+ return cast("RecordPath", path)
241
+
242
+
243
+ def get_csv_rows_for_installed(
244
+ old_csv_rows: List[List[str]],
245
+ installed: Dict[RecordPath, RecordPath],
246
+ changed: Set[RecordPath],
247
+ generated: List[str],
248
+ lib_dir: str,
249
+ ) -> List[InstalledCSVRow]:
250
+ """
251
+ :param installed: A map from archive RECORD path to installation RECORD
252
+ path.
253
+ """
254
+ installed_rows: List[InstalledCSVRow] = []
255
+ for row in old_csv_rows:
256
+ if len(row) > 3:
257
+ logger.warning("RECORD line has more than three elements: %s", row)
258
+ old_record_path = cast("RecordPath", row[0])
259
+ new_record_path = installed.pop(old_record_path, old_record_path)
260
+ if new_record_path in changed:
261
+ digest, length = rehash(_record_to_fs_path(new_record_path, lib_dir))
262
+ else:
263
+ digest = row[1] if len(row) > 1 else ""
264
+ length = row[2] if len(row) > 2 else ""
265
+ installed_rows.append((new_record_path, digest, length))
266
+ for f in generated:
267
+ path = _fs_to_record_path(f, lib_dir)
268
+ digest, length = rehash(f)
269
+ installed_rows.append((path, digest, length))
270
+ for installed_record_path in installed.values():
271
+ installed_rows.append((installed_record_path, "", ""))
272
+ return installed_rows
273
+
274
+
275
+ def get_console_script_specs(console: Dict[str, str]) -> List[str]:
276
+ """
277
+ Given the mapping from entrypoint name to callable, return the relevant
278
+ console script specs.
279
+ """
280
+ # Don't mutate caller's version
281
+ console = console.copy()
282
+
283
+ scripts_to_generate = []
284
+
285
+ # Special case pip and setuptools to generate versioned wrappers
286
+ #
287
+ # The issue is that some projects (specifically, pip and setuptools) use
288
+ # code in setup.py to create "versioned" entry points - pip2.7 on Python
289
+ # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into
290
+ # the wheel metadata at build time, and so if the wheel is installed with
291
+ # a *different* version of Python the entry points will be wrong. The
292
+ # correct fix for this is to enhance the metadata to be able to describe
293
+ # such versioned entry points, but that won't happen till Metadata 2.0 is
294
+ # available.
295
+ # In the meantime, projects using versioned entry points will either have
296
+ # incorrect versioned entry points, or they will not be able to distribute
297
+ # "universal" wheels (i.e., they will need a wheel per Python version).
298
+ #
299
+ # Because setuptools and pip are bundled with _ensurepip and virtualenv,
300
+ # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we
301
+ # override the versioned entry points in the wheel and generate the
302
+ # correct ones. This code is purely a short-term measure until Metadata 2.0
303
+ # is available.
304
+ #
305
+ # To add the level of hack in this section of code, in order to support
306
+ # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment
307
+ # variable which will control which version scripts get installed.
308
+ #
309
+ # ENSUREPIP_OPTIONS=altinstall
310
+ # - Only pipX.Y and easy_install-X.Y will be generated and installed
311
+ # ENSUREPIP_OPTIONS=install
312
+ # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note
313
+ # that this option is technically if ENSUREPIP_OPTIONS is set and is
314
+ # not altinstall
315
+ # DEFAULT
316
+ # - The default behavior is to install pip, pipX, pipX.Y, easy_install
317
+ # and easy_install-X.Y.
318
+ pip_script = console.pop("pip", None)
319
+ if pip_script:
320
+ if "ENSUREPIP_OPTIONS" not in os.environ:
321
+ scripts_to_generate.append("pip = " + pip_script)
322
+
323
+ if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall":
324
+ scripts_to_generate.append(
325
+ "pip{} = {}".format(sys.version_info[0], pip_script)
326
+ )
327
+
328
+ scripts_to_generate.append(f"pip{get_major_minor_version()} = {pip_script}")
329
+ # Delete any other versioned pip entry points
330
+ pip_ep = [k for k in console if re.match(r"pip(\d+(\.\d+)?)?$", k)]
331
+ for k in pip_ep:
332
+ del console[k]
333
+ easy_install_script = console.pop("easy_install", None)
334
+ if easy_install_script:
335
+ if "ENSUREPIP_OPTIONS" not in os.environ:
336
+ scripts_to_generate.append("easy_install = " + easy_install_script)
337
+
338
+ scripts_to_generate.append(
339
+ "easy_install-{} = {}".format(
340
+ get_major_minor_version(), easy_install_script
341
+ )
342
+ )
343
+ # Delete any other versioned easy_install entry points
344
+ easy_install_ep = [
345
+ k for k in console if re.match(r"easy_install(-\d+\.\d+)?$", k)
346
+ ]
347
+ for k in easy_install_ep:
348
+ del console[k]
349
+
350
+ # Generate the console entry points specified in the wheel
351
+ scripts_to_generate.extend(starmap("{} = {}".format, console.items()))
352
+
353
+ return scripts_to_generate
354
+
355
+
356
+ class ZipBackedFile:
357
+ def __init__(
358
+ self, src_record_path: RecordPath, dest_path: str, zip_file: ZipFile
359
+ ) -> None:
360
+ self.src_record_path = src_record_path
361
+ self.dest_path = dest_path
362
+ self._zip_file = zip_file
363
+ self.changed = False
364
+
365
+ def _getinfo(self) -> ZipInfo:
366
+ return self._zip_file.getinfo(self.src_record_path)
367
+
368
+ def save(self) -> None:
369
+ # directory creation is lazy and after file filtering
370
+ # to ensure we don't install empty dirs; empty dirs can't be
371
+ # uninstalled.
372
+ parent_dir = os.path.dirname(self.dest_path)
373
+ ensure_dir(parent_dir)
374
+
375
+ # When we open the output file below, any existing file is truncated
376
+ # before we start writing the new contents. This is fine in most
377
+ # cases, but can cause a segfault if pip has loaded a shared
378
+ # object (e.g. from pyopenssl through its vendored urllib3)
379
+ # Since the shared object is mmap'd an attempt to call a
380
+ # symbol in it will then cause a segfault. Unlinking the file
381
+ # allows writing of new contents while allowing the process to
382
+ # continue to use the old copy.
383
+ if os.path.exists(self.dest_path):
384
+ os.unlink(self.dest_path)
385
+
386
+ zipinfo = self._getinfo()
387
+
388
+ with self._zip_file.open(zipinfo) as f:
389
+ with open(self.dest_path, "wb") as dest:
390
+ shutil.copyfileobj(f, dest)
391
+
392
+ if zip_item_is_executable(zipinfo):
393
+ set_extracted_file_to_default_mode_plus_executable(self.dest_path)
394
+
395
+
396
+ class ScriptFile:
397
+ def __init__(self, file: "File") -> None:
398
+ self._file = file
399
+ self.src_record_path = self._file.src_record_path
400
+ self.dest_path = self._file.dest_path
401
+ self.changed = False
402
+
403
+ def save(self) -> None:
404
+ self._file.save()
405
+ self.changed = fix_script(self.dest_path)
406
+
407
+
408
+ class MissingCallableSuffix(InstallationError):
409
+ def __init__(self, entry_point: str) -> None:
410
+ super().__init__(
411
+ "Invalid script entry point: {} - A callable "
412
+ "suffix is required. Cf https://packaging.python.org/"
413
+ "specifications/entry-points/#use-for-scripts for more "
414
+ "information.".format(entry_point)
415
+ )
416
+
417
+
418
+ def _raise_for_invalid_entrypoint(specification: str) -> None:
419
+ entry = get_export_entry(specification)
420
+ if entry is not None and entry.suffix is None:
421
+ raise MissingCallableSuffix(str(entry))
422
+
423
+
424
+ class PipScriptMaker(ScriptMaker):
425
+ def make(
426
+ self, specification: str, options: Optional[Dict[str, Any]] = None
427
+ ) -> List[str]:
428
+ _raise_for_invalid_entrypoint(specification)
429
+ return super().make(specification, options)
430
+
431
+
432
+ def _install_wheel(
433
+ name: str,
434
+ wheel_zip: ZipFile,
435
+ wheel_path: str,
436
+ scheme: Scheme,
437
+ pycompile: bool = True,
438
+ warn_script_location: bool = True,
439
+ direct_url: Optional[DirectUrl] = None,
440
+ requested: bool = False,
441
+ ) -> None:
442
+ """Install a wheel.
443
+
444
+ :param name: Name of the project to install
445
+ :param wheel_zip: open ZipFile for wheel being installed
446
+ :param scheme: Distutils scheme dictating the install directories
447
+ :param req_description: String used in place of the requirement, for
448
+ logging
449
+ :param pycompile: Whether to byte-compile installed Python files
450
+ :param warn_script_location: Whether to check that scripts are installed
451
+ into a directory on PATH
452
+ :raises UnsupportedWheel:
453
+ * when the directory holds an unpacked wheel with incompatible
454
+ Wheel-Version
455
+ * when the .dist-info dir does not match the wheel
456
+ """
457
+ info_dir, metadata = parse_wheel(wheel_zip, name)
458
+
459
+ if wheel_root_is_purelib(metadata):
460
+ lib_dir = scheme.purelib
461
+ else:
462
+ lib_dir = scheme.platlib
463
+
464
+ # Record details of the files moved
465
+ # installed = files copied from the wheel to the destination
466
+ # changed = files changed while installing (scripts #! line typically)
467
+ # generated = files newly generated during the install (script wrappers)
468
+ installed: Dict[RecordPath, RecordPath] = {}
469
+ changed: Set[RecordPath] = set()
470
+ generated: List[str] = []
471
+
472
+ def record_installed(
473
+ srcfile: RecordPath, destfile: str, modified: bool = False
474
+ ) -> None:
475
+ """Map archive RECORD paths to installation RECORD paths."""
476
+ newpath = _fs_to_record_path(destfile, lib_dir)
477
+ installed[srcfile] = newpath
478
+ if modified:
479
+ changed.add(newpath)
480
+
481
+ def is_dir_path(path: RecordPath) -> bool:
482
+ return path.endswith("/")
483
+
484
+ def assert_no_path_traversal(dest_dir_path: str, target_path: str) -> None:
485
+ if not is_within_directory(dest_dir_path, target_path):
486
+ message = (
487
+ "The wheel {!r} has a file {!r} trying to install"
488
+ " outside the target directory {!r}"
489
+ )
490
+ raise InstallationError(
491
+ message.format(wheel_path, target_path, dest_dir_path)
492
+ )
493
+
494
+ def root_scheme_file_maker(
495
+ zip_file: ZipFile, dest: str
496
+ ) -> Callable[[RecordPath], "File"]:
497
+ def make_root_scheme_file(record_path: RecordPath) -> "File":
498
+ normed_path = os.path.normpath(record_path)
499
+ dest_path = os.path.join(dest, normed_path)
500
+ assert_no_path_traversal(dest, dest_path)
501
+ return ZipBackedFile(record_path, dest_path, zip_file)
502
+
503
+ return make_root_scheme_file
504
+
505
+ def data_scheme_file_maker(
506
+ zip_file: ZipFile, scheme: Scheme
507
+ ) -> Callable[[RecordPath], "File"]:
508
+ scheme_paths = {key: getattr(scheme, key) for key in SCHEME_KEYS}
509
+
510
+ def make_data_scheme_file(record_path: RecordPath) -> "File":
511
+ normed_path = os.path.normpath(record_path)
512
+ try:
513
+ _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2)
514
+ except ValueError:
515
+ message = (
516
+ "Unexpected file in {}: {!r}. .data directory contents"
517
+ " should be named like: '<scheme key>/<path>'."
518
+ ).format(wheel_path, record_path)
519
+ raise InstallationError(message)
520
+
521
+ try:
522
+ scheme_path = scheme_paths[scheme_key]
523
+ except KeyError:
524
+ valid_scheme_keys = ", ".join(sorted(scheme_paths))
525
+ message = (
526
+ "Unknown scheme key used in {}: {} (for file {!r}). .data"
527
+ " directory contents should be in subdirectories named"
528
+ " with a valid scheme key ({})"
529
+ ).format(wheel_path, scheme_key, record_path, valid_scheme_keys)
530
+ raise InstallationError(message)
531
+
532
+ dest_path = os.path.join(scheme_path, dest_subpath)
533
+ assert_no_path_traversal(scheme_path, dest_path)
534
+ return ZipBackedFile(record_path, dest_path, zip_file)
535
+
536
+ return make_data_scheme_file
537
+
538
+ def is_data_scheme_path(path: RecordPath) -> bool:
539
+ return path.split("/", 1)[0].endswith(".data")
540
+
541
+ paths = cast(List[RecordPath], wheel_zip.namelist())
542
+ file_paths = filterfalse(is_dir_path, paths)
543
+ root_scheme_paths, data_scheme_paths = partition(is_data_scheme_path, file_paths)
544
+
545
+ make_root_scheme_file = root_scheme_file_maker(wheel_zip, lib_dir)
546
+ files: Iterator[File] = map(make_root_scheme_file, root_scheme_paths)
547
+
548
+ def is_script_scheme_path(path: RecordPath) -> bool:
549
+ parts = path.split("/", 2)
550
+ return len(parts) > 2 and parts[0].endswith(".data") and parts[1] == "scripts"
551
+
552
+ other_scheme_paths, script_scheme_paths = partition(
553
+ is_script_scheme_path, data_scheme_paths
554
+ )
555
+
556
+ make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme)
557
+ other_scheme_files = map(make_data_scheme_file, other_scheme_paths)
558
+ files = chain(files, other_scheme_files)
559
+
560
+ # Get the defined entry points
561
+ distribution = get_wheel_distribution(
562
+ FilesystemWheel(wheel_path),
563
+ canonicalize_name(name),
564
+ )
565
+ console, gui = get_entrypoints(distribution)
566
+
567
+ def is_entrypoint_wrapper(file: "File") -> bool:
568
+ # EP, EP.exe and EP-script.py are scripts generated for
569
+ # entry point EP by setuptools
570
+ path = file.dest_path
571
+ name = os.path.basename(path)
572
+ if name.lower().endswith(".exe"):
573
+ matchname = name[:-4]
574
+ elif name.lower().endswith("-script.py"):
575
+ matchname = name[:-10]
576
+ elif name.lower().endswith(".pya"):
577
+ matchname = name[:-4]
578
+ else:
579
+ matchname = name
580
+ # Ignore setuptools-generated scripts
581
+ return matchname in console or matchname in gui
582
+
583
+ script_scheme_files: Iterator[File] = map(
584
+ make_data_scheme_file, script_scheme_paths
585
+ )
586
+ script_scheme_files = filterfalse(is_entrypoint_wrapper, script_scheme_files)
587
+ script_scheme_files = map(ScriptFile, script_scheme_files)
588
+ files = chain(files, script_scheme_files)
589
+
590
+ for file in files:
591
+ file.save()
592
+ record_installed(file.src_record_path, file.dest_path, file.changed)
593
+
594
+ def pyc_source_file_paths() -> Generator[str, None, None]:
595
+ # We de-duplicate installation paths, since there can be overlap (e.g.
596
+ # file in .data maps to same location as file in wheel root).
597
+ # Sorting installation paths makes it easier to reproduce and debug
598
+ # issues related to permissions on existing files.
599
+ for installed_path in sorted(set(installed.values())):
600
+ full_installed_path = os.path.join(lib_dir, installed_path)
601
+ if not os.path.isfile(full_installed_path):
602
+ continue
603
+ if not full_installed_path.endswith(".py"):
604
+ continue
605
+ yield full_installed_path
606
+
607
+ def pyc_output_path(path: str) -> str:
608
+ """Return the path the pyc file would have been written to."""
609
+ return importlib.util.cache_from_source(path)
610
+
611
+ # Compile all of the pyc files for the installed files
612
+ if pycompile:
613
+ with captured_stdout() as stdout:
614
+ with warnings.catch_warnings():
615
+ warnings.filterwarnings("ignore")
616
+ for path in pyc_source_file_paths():
617
+ success = compileall.compile_file(path, force=True, quiet=True)
618
+ if success:
619
+ pyc_path = pyc_output_path(path)
620
+ assert os.path.exists(pyc_path)
621
+ pyc_record_path = cast(
622
+ "RecordPath", pyc_path.replace(os.path.sep, "/")
623
+ )
624
+ record_installed(pyc_record_path, pyc_path)
625
+ logger.debug(stdout.getvalue())
626
+
627
+ maker = PipScriptMaker(None, scheme.scripts)
628
+
629
+ # Ensure old scripts are overwritten.
630
+ # See https://github.com/pypa/pip/issues/1800
631
+ maker.clobber = True
632
+
633
+ # Ensure we don't generate any variants for scripts because this is almost
634
+ # never what somebody wants.
635
+ # See https://bitbucket.org/pypa/distlib/issue/35/
636
+ maker.variants = {""}
637
+
638
+ # This is required because otherwise distlib creates scripts that are not
639
+ # executable.
640
+ # See https://bitbucket.org/pypa/distlib/issue/32/
641
+ maker.set_mode = True
642
+
643
+ # Generate the console and GUI entry points specified in the wheel
644
+ scripts_to_generate = get_console_script_specs(console)
645
+
646
+ gui_scripts_to_generate = list(starmap("{} = {}".format, gui.items()))
647
+
648
+ generated_console_scripts = maker.make_multiple(scripts_to_generate)
649
+ generated.extend(generated_console_scripts)
650
+
651
+ generated.extend(maker.make_multiple(gui_scripts_to_generate, {"gui": True}))
652
+
653
+ if warn_script_location:
654
+ msg = message_about_scripts_not_on_PATH(generated_console_scripts)
655
+ if msg is not None:
656
+ logger.warning(msg)
657
+
658
+ generated_file_mode = 0o666 & ~current_umask()
659
+
660
+ @contextlib.contextmanager
661
+ def _generate_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:
662
+ with adjacent_tmp_file(path, **kwargs) as f:
663
+ yield f
664
+ os.chmod(f.name, generated_file_mode)
665
+ replace(f.name, path)
666
+
667
+ dest_info_dir = os.path.join(lib_dir, info_dir)
668
+
669
+ # Record pip as the installer
670
+ installer_path = os.path.join(dest_info_dir, "INSTALLER")
671
+ with _generate_file(installer_path) as installer_file:
672
+ installer_file.write(b"pip\n")
673
+ generated.append(installer_path)
674
+
675
+ # Record the PEP 610 direct URL reference
676
+ if direct_url is not None:
677
+ direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME)
678
+ with _generate_file(direct_url_path) as direct_url_file:
679
+ direct_url_file.write(direct_url.to_json().encode("utf-8"))
680
+ generated.append(direct_url_path)
681
+
682
+ # Record the REQUESTED file
683
+ if requested:
684
+ requested_path = os.path.join(dest_info_dir, "REQUESTED")
685
+ with open(requested_path, "wb"):
686
+ pass
687
+ generated.append(requested_path)
688
+
689
+ record_text = distribution.read_text("RECORD")
690
+ record_rows = list(csv.reader(record_text.splitlines()))
691
+
692
+ rows = get_csv_rows_for_installed(
693
+ record_rows,
694
+ installed=installed,
695
+ changed=changed,
696
+ generated=generated,
697
+ lib_dir=lib_dir,
698
+ )
699
+
700
+ # Record details of all files installed
701
+ record_path = os.path.join(dest_info_dir, "RECORD")
702
+
703
+ with _generate_file(record_path, **csv_io_kwargs("w")) as record_file:
704
+ # Explicitly cast to typing.IO[str] as a workaround for the mypy error:
705
+ # "writer" has incompatible type "BinaryIO"; expected "_Writer"
706
+ writer = csv.writer(cast("IO[str]", record_file))
707
+ writer.writerows(_normalized_outrows(rows))
708
+
709
+
710
+ @contextlib.contextmanager
711
+ def req_error_context(req_description: str) -> Generator[None, None, None]:
712
+ try:
713
+ yield
714
+ except InstallationError as e:
715
+ message = "For req: {}. {}".format(req_description, e.args[0])
716
+ raise InstallationError(message) from e
717
+
718
+
719
+ def install_wheel(
720
+ name: str,
721
+ wheel_path: str,
722
+ scheme: Scheme,
723
+ req_description: str,
724
+ pycompile: bool = True,
725
+ warn_script_location: bool = True,
726
+ direct_url: Optional[DirectUrl] = None,
727
+ requested: bool = False,
728
+ ) -> None:
729
+ with ZipFile(wheel_path, allowZip64=True) as z:
730
+ with req_error_context(req_description):
731
+ _install_wheel(
732
+ name=name,
733
+ wheel_zip=z,
734
+ wheel_path=wheel_path,
735
+ scheme=scheme,
736
+ pycompile=pycompile,
737
+ warn_script_location=warn_script_location,
738
+ direct_url=direct_url,
739
+ requested=requested,
740
+ )
.venv/Lib/site-packages/pip/_internal/operations/prepare.py ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prepares a distribution for installation
2
+ """
3
+
4
+ # The following comment should be removed at some point in the future.
5
+ # mypy: strict-optional=False
6
+
7
+ import logging
8
+ import mimetypes
9
+ import os
10
+ import shutil
11
+ from typing import Dict, Iterable, List, Optional
12
+
13
+ from pip._vendor.packaging.utils import canonicalize_name
14
+
15
+ from pip._internal.distributions import make_distribution_for_install_requirement
16
+ from pip._internal.distributions.installed import InstalledDistribution
17
+ from pip._internal.exceptions import (
18
+ DirectoryUrlHashUnsupported,
19
+ HashMismatch,
20
+ HashUnpinned,
21
+ InstallationError,
22
+ MetadataInconsistent,
23
+ NetworkConnectionError,
24
+ PreviousBuildDirError,
25
+ VcsHashUnsupported,
26
+ )
27
+ from pip._internal.index.package_finder import PackageFinder
28
+ from pip._internal.metadata import BaseDistribution, get_metadata_distribution
29
+ from pip._internal.models.direct_url import ArchiveInfo
30
+ from pip._internal.models.link import Link
31
+ from pip._internal.models.wheel import Wheel
32
+ from pip._internal.network.download import BatchDownloader, Downloader
33
+ from pip._internal.network.lazy_wheel import (
34
+ HTTPRangeRequestUnsupported,
35
+ dist_from_wheel_url,
36
+ )
37
+ from pip._internal.network.session import PipSession
38
+ from pip._internal.operations.build.build_tracker import BuildTracker
39
+ from pip._internal.req.req_install import InstallRequirement
40
+ from pip._internal.utils.direct_url_helpers import (
41
+ direct_url_for_editable,
42
+ direct_url_from_link,
43
+ )
44
+ from pip._internal.utils.hashes import Hashes, MissingHashes
45
+ from pip._internal.utils.logging import indent_log
46
+ from pip._internal.utils.misc import (
47
+ display_path,
48
+ hash_file,
49
+ hide_url,
50
+ is_installable_dir,
51
+ )
52
+ from pip._internal.utils.temp_dir import TempDirectory
53
+ from pip._internal.utils.unpacking import unpack_file
54
+ from pip._internal.vcs import vcs
55
+
56
+ logger = logging.getLogger(__name__)
57
+
58
+
59
+ def _get_prepared_distribution(
60
+ req: InstallRequirement,
61
+ build_tracker: BuildTracker,
62
+ finder: PackageFinder,
63
+ build_isolation: bool,
64
+ check_build_deps: bool,
65
+ ) -> BaseDistribution:
66
+ """Prepare a distribution for installation."""
67
+ abstract_dist = make_distribution_for_install_requirement(req)
68
+ with build_tracker.track(req):
69
+ abstract_dist.prepare_distribution_metadata(
70
+ finder, build_isolation, check_build_deps
71
+ )
72
+ return abstract_dist.get_metadata_distribution()
73
+
74
+
75
+ def unpack_vcs_link(link: Link, location: str, verbosity: int) -> None:
76
+ vcs_backend = vcs.get_backend_for_scheme(link.scheme)
77
+ assert vcs_backend is not None
78
+ vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity)
79
+
80
+
81
+ class File:
82
+ def __init__(self, path: str, content_type: Optional[str]) -> None:
83
+ self.path = path
84
+ if content_type is None:
85
+ self.content_type = mimetypes.guess_type(path)[0]
86
+ else:
87
+ self.content_type = content_type
88
+
89
+
90
+ def get_http_url(
91
+ link: Link,
92
+ download: Downloader,
93
+ download_dir: Optional[str] = None,
94
+ hashes: Optional[Hashes] = None,
95
+ ) -> File:
96
+ temp_dir = TempDirectory(kind="unpack", globally_managed=True)
97
+ # If a download dir is specified, is the file already downloaded there?
98
+ already_downloaded_path = None
99
+ if download_dir:
100
+ already_downloaded_path = _check_download_dir(link, download_dir, hashes)
101
+
102
+ if already_downloaded_path:
103
+ from_path = already_downloaded_path
104
+ content_type = None
105
+ else:
106
+ # let's download to a tmp dir
107
+ from_path, content_type = download(link, temp_dir.path)
108
+ if hashes:
109
+ hashes.check_against_path(from_path)
110
+
111
+ return File(from_path, content_type)
112
+
113
+
114
+ def get_file_url(
115
+ link: Link, download_dir: Optional[str] = None, hashes: Optional[Hashes] = None
116
+ ) -> File:
117
+ """Get file and optionally check its hash."""
118
+ # If a download dir is specified, is the file already there and valid?
119
+ already_downloaded_path = None
120
+ if download_dir:
121
+ already_downloaded_path = _check_download_dir(link, download_dir, hashes)
122
+
123
+ if already_downloaded_path:
124
+ from_path = already_downloaded_path
125
+ else:
126
+ from_path = link.file_path
127
+
128
+ # If --require-hashes is off, `hashes` is either empty, the
129
+ # link's embedded hash, or MissingHashes; it is required to
130
+ # match. If --require-hashes is on, we are satisfied by any
131
+ # hash in `hashes` matching: a URL-based or an option-based
132
+ # one; no internet-sourced hash will be in `hashes`.
133
+ if hashes:
134
+ hashes.check_against_path(from_path)
135
+ return File(from_path, None)
136
+
137
+
138
+ def unpack_url(
139
+ link: Link,
140
+ location: str,
141
+ download: Downloader,
142
+ verbosity: int,
143
+ download_dir: Optional[str] = None,
144
+ hashes: Optional[Hashes] = None,
145
+ ) -> Optional[File]:
146
+ """Unpack link into location, downloading if required.
147
+
148
+ :param hashes: A Hashes object, one of whose embedded hashes must match,
149
+ or HashMismatch will be raised. If the Hashes is empty, no matches are
150
+ required, and unhashable types of requirements (like VCS ones, which
151
+ would ordinarily raise HashUnsupported) are allowed.
152
+ """
153
+ # non-editable vcs urls
154
+ if link.is_vcs:
155
+ unpack_vcs_link(link, location, verbosity=verbosity)
156
+ return None
157
+
158
+ assert not link.is_existing_dir()
159
+
160
+ # file urls
161
+ if link.is_file:
162
+ file = get_file_url(link, download_dir, hashes=hashes)
163
+
164
+ # http urls
165
+ else:
166
+ file = get_http_url(
167
+ link,
168
+ download,
169
+ download_dir,
170
+ hashes=hashes,
171
+ )
172
+
173
+ # unpack the archive to the build dir location. even when only downloading
174
+ # archives, they have to be unpacked to parse dependencies, except wheels
175
+ if not link.is_wheel:
176
+ unpack_file(file.path, location, file.content_type)
177
+
178
+ return file
179
+
180
+
181
+ def _check_download_dir(
182
+ link: Link,
183
+ download_dir: str,
184
+ hashes: Optional[Hashes],
185
+ warn_on_hash_mismatch: bool = True,
186
+ ) -> Optional[str]:
187
+ """Check download_dir for previously downloaded file with correct hash
188
+ If a correct file is found return its path else None
189
+ """
190
+ download_path = os.path.join(download_dir, link.filename)
191
+
192
+ if not os.path.exists(download_path):
193
+ return None
194
+
195
+ # If already downloaded, does its hash match?
196
+ logger.info("File was already downloaded %s", download_path)
197
+ if hashes:
198
+ try:
199
+ hashes.check_against_path(download_path)
200
+ except HashMismatch:
201
+ if warn_on_hash_mismatch:
202
+ logger.warning(
203
+ "Previously-downloaded file %s has bad hash. Re-downloading.",
204
+ download_path,
205
+ )
206
+ os.unlink(download_path)
207
+ return None
208
+ return download_path
209
+
210
+
211
+ class RequirementPreparer:
212
+ """Prepares a Requirement"""
213
+
214
+ def __init__(
215
+ self,
216
+ build_dir: str,
217
+ download_dir: Optional[str],
218
+ src_dir: str,
219
+ build_isolation: bool,
220
+ check_build_deps: bool,
221
+ build_tracker: BuildTracker,
222
+ session: PipSession,
223
+ progress_bar: str,
224
+ finder: PackageFinder,
225
+ require_hashes: bool,
226
+ use_user_site: bool,
227
+ lazy_wheel: bool,
228
+ verbosity: int,
229
+ legacy_resolver: bool,
230
+ ) -> None:
231
+ super().__init__()
232
+
233
+ self.src_dir = src_dir
234
+ self.build_dir = build_dir
235
+ self.build_tracker = build_tracker
236
+ self._session = session
237
+ self._download = Downloader(session, progress_bar)
238
+ self._batch_download = BatchDownloader(session, progress_bar)
239
+ self.finder = finder
240
+
241
+ # Where still-packed archives should be written to. If None, they are
242
+ # not saved, and are deleted immediately after unpacking.
243
+ self.download_dir = download_dir
244
+
245
+ # Is build isolation allowed?
246
+ self.build_isolation = build_isolation
247
+
248
+ # Should check build dependencies?
249
+ self.check_build_deps = check_build_deps
250
+
251
+ # Should hash-checking be required?
252
+ self.require_hashes = require_hashes
253
+
254
+ # Should install in user site-packages?
255
+ self.use_user_site = use_user_site
256
+
257
+ # Should wheels be downloaded lazily?
258
+ self.use_lazy_wheel = lazy_wheel
259
+
260
+ # How verbose should underlying tooling be?
261
+ self.verbosity = verbosity
262
+
263
+ # Are we using the legacy resolver?
264
+ self.legacy_resolver = legacy_resolver
265
+
266
+ # Memoized downloaded files, as mapping of url: path.
267
+ self._downloaded: Dict[str, str] = {}
268
+
269
+ # Previous "header" printed for a link-based InstallRequirement
270
+ self._previous_requirement_header = ("", "")
271
+
272
+ def _log_preparing_link(self, req: InstallRequirement) -> None:
273
+ """Provide context for the requirement being prepared."""
274
+ if req.link.is_file and not req.is_wheel_from_cache:
275
+ message = "Processing %s"
276
+ information = str(display_path(req.link.file_path))
277
+ else:
278
+ message = "Collecting %s"
279
+ information = str(req.req or req)
280
+
281
+ # If we used req.req, inject requirement source if available (this
282
+ # would already be included if we used req directly)
283
+ if req.req and req.comes_from:
284
+ if isinstance(req.comes_from, str):
285
+ comes_from: Optional[str] = req.comes_from
286
+ else:
287
+ comes_from = req.comes_from.from_path()
288
+ if comes_from:
289
+ information += f" (from {comes_from})"
290
+
291
+ if (message, information) != self._previous_requirement_header:
292
+ self._previous_requirement_header = (message, information)
293
+ logger.info(message, information)
294
+
295
+ if req.is_wheel_from_cache:
296
+ with indent_log():
297
+ logger.info("Using cached %s", req.link.filename)
298
+
299
+ def _ensure_link_req_src_dir(
300
+ self, req: InstallRequirement, parallel_builds: bool
301
+ ) -> None:
302
+ """Ensure source_dir of a linked InstallRequirement."""
303
+ # Since source_dir is only set for editable requirements.
304
+ if req.link.is_wheel:
305
+ # We don't need to unpack wheels, so no need for a source
306
+ # directory.
307
+ return
308
+ assert req.source_dir is None
309
+ if req.link.is_existing_dir():
310
+ # build local directories in-tree
311
+ req.source_dir = req.link.file_path
312
+ return
313
+
314
+ # We always delete unpacked sdists after pip runs.
315
+ req.ensure_has_source_dir(
316
+ self.build_dir,
317
+ autodelete=True,
318
+ parallel_builds=parallel_builds,
319
+ )
320
+
321
+ # If a checkout exists, it's unwise to keep going. version
322
+ # inconsistencies are logged later, but do not fail the
323
+ # installation.
324
+ # FIXME: this won't upgrade when there's an existing
325
+ # package unpacked in `req.source_dir`
326
+ # TODO: this check is now probably dead code
327
+ if is_installable_dir(req.source_dir):
328
+ raise PreviousBuildDirError(
329
+ "pip can't proceed with requirements '{}' due to a"
330
+ "pre-existing build directory ({}). This is likely "
331
+ "due to a previous installation that failed . pip is "
332
+ "being responsible and not assuming it can delete this. "
333
+ "Please delete it and try again.".format(req, req.source_dir)
334
+ )
335
+
336
+ def _get_linked_req_hashes(self, req: InstallRequirement) -> Hashes:
337
+ # By the time this is called, the requirement's link should have
338
+ # been checked so we can tell what kind of requirements req is
339
+ # and raise some more informative errors than otherwise.
340
+ # (For example, we can raise VcsHashUnsupported for a VCS URL
341
+ # rather than HashMissing.)
342
+ if not self.require_hashes:
343
+ return req.hashes(trust_internet=True)
344
+
345
+ # We could check these first 2 conditions inside unpack_url
346
+ # and save repetition of conditions, but then we would
347
+ # report less-useful error messages for unhashable
348
+ # requirements, complaining that there's no hash provided.
349
+ if req.link.is_vcs:
350
+ raise VcsHashUnsupported()
351
+ if req.link.is_existing_dir():
352
+ raise DirectoryUrlHashUnsupported()
353
+
354
+ # Unpinned packages are asking for trouble when a new version
355
+ # is uploaded. This isn't a security check, but it saves users
356
+ # a surprising hash mismatch in the future.
357
+ # file:/// URLs aren't pinnable, so don't complain about them
358
+ # not being pinned.
359
+ if not req.is_direct and not req.is_pinned:
360
+ raise HashUnpinned()
361
+
362
+ # If known-good hashes are missing for this requirement,
363
+ # shim it with a facade object that will provoke hash
364
+ # computation and then raise a HashMissing exception
365
+ # showing the user what the hash should be.
366
+ return req.hashes(trust_internet=False) or MissingHashes()
367
+
368
+ def _fetch_metadata_only(
369
+ self,
370
+ req: InstallRequirement,
371
+ ) -> Optional[BaseDistribution]:
372
+ if self.legacy_resolver:
373
+ logger.debug(
374
+ "Metadata-only fetching is not used in the legacy resolver",
375
+ )
376
+ return None
377
+ if self.require_hashes:
378
+ logger.debug(
379
+ "Metadata-only fetching is not used as hash checking is required",
380
+ )
381
+ return None
382
+ # Try PEP 658 metadata first, then fall back to lazy wheel if unavailable.
383
+ return self._fetch_metadata_using_link_data_attr(
384
+ req
385
+ ) or self._fetch_metadata_using_lazy_wheel(req.link)
386
+
387
+ def _fetch_metadata_using_link_data_attr(
388
+ self,
389
+ req: InstallRequirement,
390
+ ) -> Optional[BaseDistribution]:
391
+ """Fetch metadata from the data-dist-info-metadata attribute, if possible."""
392
+ # (1) Get the link to the metadata file, if provided by the backend.
393
+ metadata_link = req.link.metadata_link()
394
+ if metadata_link is None:
395
+ return None
396
+ assert req.req is not None
397
+ logger.info(
398
+ "Obtaining dependency information for %s from %s",
399
+ req.req,
400
+ metadata_link,
401
+ )
402
+ # (2) Download the contents of the METADATA file, separate from the dist itself.
403
+ metadata_file = get_http_url(
404
+ metadata_link,
405
+ self._download,
406
+ hashes=metadata_link.as_hashes(),
407
+ )
408
+ with open(metadata_file.path, "rb") as f:
409
+ metadata_contents = f.read()
410
+ # (3) Generate a dist just from those file contents.
411
+ metadata_dist = get_metadata_distribution(
412
+ metadata_contents,
413
+ req.link.filename,
414
+ req.req.name,
415
+ )
416
+ # (4) Ensure the Name: field from the METADATA file matches the name from the
417
+ # install requirement.
418
+ #
419
+ # NB: raw_name will fall back to the name from the install requirement if
420
+ # the Name: field is not present, but it's noted in the raw_name docstring
421
+ # that that should NEVER happen anyway.
422
+ if canonicalize_name(metadata_dist.raw_name) != canonicalize_name(req.req.name):
423
+ raise MetadataInconsistent(
424
+ req, "Name", req.req.name, metadata_dist.raw_name
425
+ )
426
+ return metadata_dist
427
+
428
+ def _fetch_metadata_using_lazy_wheel(
429
+ self,
430
+ link: Link,
431
+ ) -> Optional[BaseDistribution]:
432
+ """Fetch metadata using lazy wheel, if possible."""
433
+ # --use-feature=fast-deps must be provided.
434
+ if not self.use_lazy_wheel:
435
+ return None
436
+ if link.is_file or not link.is_wheel:
437
+ logger.debug(
438
+ "Lazy wheel is not used as %r does not point to a remote wheel",
439
+ link,
440
+ )
441
+ return None
442
+
443
+ wheel = Wheel(link.filename)
444
+ name = canonicalize_name(wheel.name)
445
+ logger.info(
446
+ "Obtaining dependency information from %s %s",
447
+ name,
448
+ wheel.version,
449
+ )
450
+ url = link.url.split("#", 1)[0]
451
+ try:
452
+ return dist_from_wheel_url(name, url, self._session)
453
+ except HTTPRangeRequestUnsupported:
454
+ logger.debug("%s does not support range requests", url)
455
+ return None
456
+
457
+ def _complete_partial_requirements(
458
+ self,
459
+ partially_downloaded_reqs: Iterable[InstallRequirement],
460
+ parallel_builds: bool = False,
461
+ ) -> None:
462
+ """Download any requirements which were only fetched by metadata."""
463
+ # Download to a temporary directory. These will be copied over as
464
+ # needed for downstream 'download', 'wheel', and 'install' commands.
465
+ temp_dir = TempDirectory(kind="unpack", globally_managed=True).path
466
+
467
+ # Map each link to the requirement that owns it. This allows us to set
468
+ # `req.local_file_path` on the appropriate requirement after passing
469
+ # all the links at once into BatchDownloader.
470
+ links_to_fully_download: Dict[Link, InstallRequirement] = {}
471
+ for req in partially_downloaded_reqs:
472
+ assert req.link
473
+ links_to_fully_download[req.link] = req
474
+
475
+ batch_download = self._batch_download(
476
+ links_to_fully_download.keys(),
477
+ temp_dir,
478
+ )
479
+ for link, (filepath, _) in batch_download:
480
+ logger.debug("Downloading link %s to %s", link, filepath)
481
+ req = links_to_fully_download[link]
482
+ req.local_file_path = filepath
483
+ # TODO: This needs fixing for sdists
484
+ # This is an emergency fix for #11847, which reports that
485
+ # distributions get downloaded twice when metadata is loaded
486
+ # from a PEP 658 standalone metadata file. Setting _downloaded
487
+ # fixes this for wheels, but breaks the sdist case (tests
488
+ # test_download_metadata). As PyPI is currently only serving
489
+ # metadata for wheels, this is not an immediate issue.
490
+ # Fixing the problem properly looks like it will require a
491
+ # complete refactoring of the `prepare_linked_requirements_more`
492
+ # logic, and I haven't a clue where to start on that, so for now
493
+ # I have fixed the issue *just* for wheels.
494
+ if req.is_wheel:
495
+ self._downloaded[req.link.url] = filepath
496
+
497
+ # This step is necessary to ensure all lazy wheels are processed
498
+ # successfully by the 'download', 'wheel', and 'install' commands.
499
+ for req in partially_downloaded_reqs:
500
+ self._prepare_linked_requirement(req, parallel_builds)
501
+
502
+ def prepare_linked_requirement(
503
+ self, req: InstallRequirement, parallel_builds: bool = False
504
+ ) -> BaseDistribution:
505
+ """Prepare a requirement to be obtained from req.link."""
506
+ assert req.link
507
+ self._log_preparing_link(req)
508
+ with indent_log():
509
+ # Check if the relevant file is already available
510
+ # in the download directory
511
+ file_path = None
512
+ if self.download_dir is not None and req.link.is_wheel:
513
+ hashes = self._get_linked_req_hashes(req)
514
+ file_path = _check_download_dir(
515
+ req.link,
516
+ self.download_dir,
517
+ hashes,
518
+ # When a locally built wheel has been found in cache, we don't warn
519
+ # about re-downloading when the already downloaded wheel hash does
520
+ # not match. This is because the hash must be checked against the
521
+ # original link, not the cached link. It that case the already
522
+ # downloaded file will be removed and re-fetched from cache (which
523
+ # implies a hash check against the cache entry's origin.json).
524
+ warn_on_hash_mismatch=not req.is_wheel_from_cache,
525
+ )
526
+
527
+ if file_path is not None:
528
+ # The file is already available, so mark it as downloaded
529
+ self._downloaded[req.link.url] = file_path
530
+ else:
531
+ # The file is not available, attempt to fetch only metadata
532
+ metadata_dist = self._fetch_metadata_only(req)
533
+ if metadata_dist is not None:
534
+ req.needs_more_preparation = True
535
+ return metadata_dist
536
+
537
+ # None of the optimizations worked, fully prepare the requirement
538
+ return self._prepare_linked_requirement(req, parallel_builds)
539
+
540
+ def prepare_linked_requirements_more(
541
+ self, reqs: Iterable[InstallRequirement], parallel_builds: bool = False
542
+ ) -> None:
543
+ """Prepare linked requirements more, if needed."""
544
+ reqs = [req for req in reqs if req.needs_more_preparation]
545
+ for req in reqs:
546
+ # Determine if any of these requirements were already downloaded.
547
+ if self.download_dir is not None and req.link.is_wheel:
548
+ hashes = self._get_linked_req_hashes(req)
549
+ file_path = _check_download_dir(req.link, self.download_dir, hashes)
550
+ if file_path is not None:
551
+ self._downloaded[req.link.url] = file_path
552
+ req.needs_more_preparation = False
553
+
554
+ # Prepare requirements we found were already downloaded for some
555
+ # reason. The other downloads will be completed separately.
556
+ partially_downloaded_reqs: List[InstallRequirement] = []
557
+ for req in reqs:
558
+ if req.needs_more_preparation:
559
+ partially_downloaded_reqs.append(req)
560
+ else:
561
+ self._prepare_linked_requirement(req, parallel_builds)
562
+
563
+ # TODO: separate this part out from RequirementPreparer when the v1
564
+ # resolver can be removed!
565
+ self._complete_partial_requirements(
566
+ partially_downloaded_reqs,
567
+ parallel_builds=parallel_builds,
568
+ )
569
+
570
+ def _prepare_linked_requirement(
571
+ self, req: InstallRequirement, parallel_builds: bool
572
+ ) -> BaseDistribution:
573
+ assert req.link
574
+ link = req.link
575
+
576
+ hashes = self._get_linked_req_hashes(req)
577
+
578
+ if hashes and req.is_wheel_from_cache:
579
+ assert req.download_info is not None
580
+ assert link.is_wheel
581
+ assert link.is_file
582
+ # We need to verify hashes, and we have found the requirement in the cache
583
+ # of locally built wheels.
584
+ if (
585
+ isinstance(req.download_info.info, ArchiveInfo)
586
+ and req.download_info.info.hashes
587
+ and hashes.has_one_of(req.download_info.info.hashes)
588
+ ):
589
+ # At this point we know the requirement was built from a hashable source
590
+ # artifact, and we verified that the cache entry's hash of the original
591
+ # artifact matches one of the hashes we expect. We don't verify hashes
592
+ # against the cached wheel, because the wheel is not the original.
593
+ hashes = None
594
+ else:
595
+ logger.warning(
596
+ "The hashes of the source archive found in cache entry "
597
+ "don't match, ignoring cached built wheel "
598
+ "and re-downloading source."
599
+ )
600
+ req.link = req.cached_wheel_source_link
601
+ link = req.link
602
+
603
+ self._ensure_link_req_src_dir(req, parallel_builds)
604
+
605
+ if link.is_existing_dir():
606
+ local_file = None
607
+ elif link.url not in self._downloaded:
608
+ try:
609
+ local_file = unpack_url(
610
+ link,
611
+ req.source_dir,
612
+ self._download,
613
+ self.verbosity,
614
+ self.download_dir,
615
+ hashes,
616
+ )
617
+ except NetworkConnectionError as exc:
618
+ raise InstallationError(
619
+ "Could not install requirement {} because of HTTP "
620
+ "error {} for URL {}".format(req, exc, link)
621
+ )
622
+ else:
623
+ file_path = self._downloaded[link.url]
624
+ if hashes:
625
+ hashes.check_against_path(file_path)
626
+ local_file = File(file_path, content_type=None)
627
+
628
+ # If download_info is set, we got it from the wheel cache.
629
+ if req.download_info is None:
630
+ # Editables don't go through this function (see
631
+ # prepare_editable_requirement).
632
+ assert not req.editable
633
+ req.download_info = direct_url_from_link(link, req.source_dir)
634
+ # Make sure we have a hash in download_info. If we got it as part of the
635
+ # URL, it will have been verified and we can rely on it. Otherwise we
636
+ # compute it from the downloaded file.
637
+ # FIXME: https://github.com/pypa/pip/issues/11943
638
+ if (
639
+ isinstance(req.download_info.info, ArchiveInfo)
640
+ and not req.download_info.info.hashes
641
+ and local_file
642
+ ):
643
+ hash = hash_file(local_file.path)[0].hexdigest()
644
+ # We populate info.hash for backward compatibility.
645
+ # This will automatically populate info.hashes.
646
+ req.download_info.info.hash = f"sha256={hash}"
647
+
648
+ # For use in later processing,
649
+ # preserve the file path on the requirement.
650
+ if local_file:
651
+ req.local_file_path = local_file.path
652
+
653
+ dist = _get_prepared_distribution(
654
+ req,
655
+ self.build_tracker,
656
+ self.finder,
657
+ self.build_isolation,
658
+ self.check_build_deps,
659
+ )
660
+ return dist
661
+
662
+ def save_linked_requirement(self, req: InstallRequirement) -> None:
663
+ assert self.download_dir is not None
664
+ assert req.link is not None
665
+ link = req.link
666
+ if link.is_vcs or (link.is_existing_dir() and req.editable):
667
+ # Make a .zip of the source_dir we already created.
668
+ req.archive(self.download_dir)
669
+ return
670
+
671
+ if link.is_existing_dir():
672
+ logger.debug(
673
+ "Not copying link to destination directory "
674
+ "since it is a directory: %s",
675
+ link,
676
+ )
677
+ return
678
+ if req.local_file_path is None:
679
+ # No distribution was downloaded for this requirement.
680
+ return
681
+
682
+ download_location = os.path.join(self.download_dir, link.filename)
683
+ if not os.path.exists(download_location):
684
+ shutil.copy(req.local_file_path, download_location)
685
+ download_path = display_path(download_location)
686
+ logger.info("Saved %s", download_path)
687
+
688
+ def prepare_editable_requirement(
689
+ self,
690
+ req: InstallRequirement,
691
+ ) -> BaseDistribution:
692
+ """Prepare an editable requirement."""
693
+ assert req.editable, "cannot prepare a non-editable req as editable"
694
+
695
+ logger.info("Obtaining %s", req)
696
+
697
+ with indent_log():
698
+ if self.require_hashes:
699
+ raise InstallationError(
700
+ "The editable requirement {} cannot be installed when "
701
+ "requiring hashes, because there is no single file to "
702
+ "hash.".format(req)
703
+ )
704
+ req.ensure_has_source_dir(self.src_dir)
705
+ req.update_editable()
706
+ assert req.source_dir
707
+ req.download_info = direct_url_for_editable(req.unpacked_source_directory)
708
+
709
+ dist = _get_prepared_distribution(
710
+ req,
711
+ self.build_tracker,
712
+ self.finder,
713
+ self.build_isolation,
714
+ self.check_build_deps,
715
+ )
716
+
717
+ req.check_if_exists(self.use_user_site)
718
+
719
+ return dist
720
+
721
+ def prepare_installed_requirement(
722
+ self,
723
+ req: InstallRequirement,
724
+ skip_reason: str,
725
+ ) -> BaseDistribution:
726
+ """Prepare an already-installed requirement."""
727
+ assert req.satisfied_by, "req should have been satisfied but isn't"
728
+ assert skip_reason is not None, (
729
+ "did not get skip reason skipped but req.satisfied_by "
730
+ "is set to {}".format(req.satisfied_by)
731
+ )
732
+ logger.info(
733
+ "Requirement %s: %s (%s)", skip_reason, req, req.satisfied_by.version
734
+ )
735
+ with indent_log():
736
+ if self.require_hashes:
737
+ logger.debug(
738
+ "Since it is already installed, we are trusting this "
739
+ "package without checking its hash. To ensure a "
740
+ "completely repeatable environment, install into an "
741
+ "empty virtualenv."
742
+ )
743
+ return InstalledDistribution(req).get_metadata_distribution()
.venv/Lib/site-packages/pip/_internal/req/__init__.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import logging
3
+ from typing import Generator, List, Optional, Sequence, Tuple
4
+
5
+ from pip._internal.utils.logging import indent_log
6
+
7
+ from .req_file import parse_requirements
8
+ from .req_install import InstallRequirement
9
+ from .req_set import RequirementSet
10
+
11
+ __all__ = [
12
+ "RequirementSet",
13
+ "InstallRequirement",
14
+ "parse_requirements",
15
+ "install_given_reqs",
16
+ ]
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class InstallationResult:
22
+ def __init__(self, name: str) -> None:
23
+ self.name = name
24
+
25
+ def __repr__(self) -> str:
26
+ return f"InstallationResult(name={self.name!r})"
27
+
28
+
29
+ def _validate_requirements(
30
+ requirements: List[InstallRequirement],
31
+ ) -> Generator[Tuple[str, InstallRequirement], None, None]:
32
+ for req in requirements:
33
+ assert req.name, f"invalid to-be-installed requirement: {req}"
34
+ yield req.name, req
35
+
36
+
37
+ def install_given_reqs(
38
+ requirements: List[InstallRequirement],
39
+ global_options: Sequence[str],
40
+ root: Optional[str],
41
+ home: Optional[str],
42
+ prefix: Optional[str],
43
+ warn_script_location: bool,
44
+ use_user_site: bool,
45
+ pycompile: bool,
46
+ ) -> List[InstallationResult]:
47
+ """
48
+ Install everything in the given list.
49
+
50
+ (to be called after having downloaded and unpacked the packages)
51
+ """
52
+ to_install = collections.OrderedDict(_validate_requirements(requirements))
53
+
54
+ if to_install:
55
+ logger.info(
56
+ "Installing collected packages: %s",
57
+ ", ".join(to_install.keys()),
58
+ )
59
+
60
+ installed = []
61
+
62
+ with indent_log():
63
+ for req_name, requirement in to_install.items():
64
+ if requirement.should_reinstall:
65
+ logger.info("Attempting uninstall: %s", req_name)
66
+ with indent_log():
67
+ uninstalled_pathset = requirement.uninstall(auto_confirm=True)
68
+ else:
69
+ uninstalled_pathset = None
70
+
71
+ try:
72
+ requirement.install(
73
+ global_options,
74
+ root=root,
75
+ home=home,
76
+ prefix=prefix,
77
+ warn_script_location=warn_script_location,
78
+ use_user_site=use_user_site,
79
+ pycompile=pycompile,
80
+ )
81
+ except Exception:
82
+ # if install did not succeed, rollback previous uninstall
83
+ if uninstalled_pathset and not requirement.install_succeeded:
84
+ uninstalled_pathset.rollback()
85
+ raise
86
+ else:
87
+ if uninstalled_pathset and requirement.install_succeeded:
88
+ uninstalled_pathset.commit()
89
+
90
+ installed.append(InstallationResult(req_name))
91
+
92
+ return installed
.venv/Lib/site-packages/pip/_internal/req/constructors.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backing implementation for InstallRequirement's various constructors
2
+
3
+ The idea here is that these formed a major chunk of InstallRequirement's size
4
+ so, moving them and support code dedicated to them outside of that class
5
+ helps creates for better understandability for the rest of the code.
6
+
7
+ These are meant to be used elsewhere within pip to create instances of
8
+ InstallRequirement.
9
+ """
10
+
11
+ import logging
12
+ import os
13
+ import re
14
+ from typing import Dict, List, Optional, Set, Tuple, Union
15
+
16
+ from pip._vendor.packaging.markers import Marker
17
+ from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
18
+ from pip._vendor.packaging.specifiers import Specifier
19
+
20
+ from pip._internal.exceptions import InstallationError
21
+ from pip._internal.models.index import PyPI, TestPyPI
22
+ from pip._internal.models.link import Link
23
+ from pip._internal.models.wheel import Wheel
24
+ from pip._internal.req.req_file import ParsedRequirement
25
+ from pip._internal.req.req_install import InstallRequirement
26
+ from pip._internal.utils.filetypes import is_archive_file
27
+ from pip._internal.utils.misc import is_installable_dir
28
+ from pip._internal.utils.packaging import get_requirement
29
+ from pip._internal.utils.urls import path_to_url
30
+ from pip._internal.vcs import is_url, vcs
31
+
32
+ __all__ = [
33
+ "install_req_from_editable",
34
+ "install_req_from_line",
35
+ "parse_editable",
36
+ ]
37
+
38
+ logger = logging.getLogger(__name__)
39
+ operators = Specifier._operators.keys()
40
+
41
+
42
+ def _strip_extras(path: str) -> Tuple[str, Optional[str]]:
43
+ m = re.match(r"^(.+)(\[[^\]]+\])$", path)
44
+ extras = None
45
+ if m:
46
+ path_no_extras = m.group(1)
47
+ extras = m.group(2)
48
+ else:
49
+ path_no_extras = path
50
+
51
+ return path_no_extras, extras
52
+
53
+
54
+ def convert_extras(extras: Optional[str]) -> Set[str]:
55
+ if not extras:
56
+ return set()
57
+ return get_requirement("placeholder" + extras.lower()).extras
58
+
59
+
60
+ def parse_editable(editable_req: str) -> Tuple[Optional[str], str, Set[str]]:
61
+ """Parses an editable requirement into:
62
+ - a requirement name
63
+ - an URL
64
+ - extras
65
+ - editable options
66
+ Accepted requirements:
67
+ svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
68
+ .[some_extra]
69
+ """
70
+
71
+ url = editable_req
72
+
73
+ # If a file path is specified with extras, strip off the extras.
74
+ url_no_extras, extras = _strip_extras(url)
75
+
76
+ if os.path.isdir(url_no_extras):
77
+ # Treating it as code that has already been checked out
78
+ url_no_extras = path_to_url(url_no_extras)
79
+
80
+ if url_no_extras.lower().startswith("file:"):
81
+ package_name = Link(url_no_extras).egg_fragment
82
+ if extras:
83
+ return (
84
+ package_name,
85
+ url_no_extras,
86
+ get_requirement("placeholder" + extras.lower()).extras,
87
+ )
88
+ else:
89
+ return package_name, url_no_extras, set()
90
+
91
+ for version_control in vcs:
92
+ if url.lower().startswith(f"{version_control}:"):
93
+ url = f"{version_control}+{url}"
94
+ break
95
+
96
+ link = Link(url)
97
+
98
+ if not link.is_vcs:
99
+ backends = ", ".join(vcs.all_schemes)
100
+ raise InstallationError(
101
+ f"{editable_req} is not a valid editable requirement. "
102
+ f"It should either be a path to a local project or a VCS URL "
103
+ f"(beginning with {backends})."
104
+ )
105
+
106
+ package_name = link.egg_fragment
107
+ if not package_name:
108
+ raise InstallationError(
109
+ "Could not detect requirement name for '{}', please specify one "
110
+ "with #egg=your_package_name".format(editable_req)
111
+ )
112
+ return package_name, url, set()
113
+
114
+
115
+ def check_first_requirement_in_file(filename: str) -> None:
116
+ """Check if file is parsable as a requirements file.
117
+
118
+ This is heavily based on ``pkg_resources.parse_requirements``, but
119
+ simplified to just check the first meaningful line.
120
+
121
+ :raises InvalidRequirement: If the first meaningful line cannot be parsed
122
+ as an requirement.
123
+ """
124
+ with open(filename, encoding="utf-8", errors="ignore") as f:
125
+ # Create a steppable iterator, so we can handle \-continuations.
126
+ lines = (
127
+ line
128
+ for line in (line.strip() for line in f)
129
+ if line and not line.startswith("#") # Skip blank lines/comments.
130
+ )
131
+
132
+ for line in lines:
133
+ # Drop comments -- a hash without a space may be in a URL.
134
+ if " #" in line:
135
+ line = line[: line.find(" #")]
136
+ # If there is a line continuation, drop it, and append the next line.
137
+ if line.endswith("\\"):
138
+ line = line[:-2].strip() + next(lines, "")
139
+ Requirement(line)
140
+ return
141
+
142
+
143
+ def deduce_helpful_msg(req: str) -> str:
144
+ """Returns helpful msg in case requirements file does not exist,
145
+ or cannot be parsed.
146
+
147
+ :params req: Requirements file path
148
+ """
149
+ if not os.path.exists(req):
150
+ return f" File '{req}' does not exist."
151
+ msg = " The path does exist. "
152
+ # Try to parse and check if it is a requirements file.
153
+ try:
154
+ check_first_requirement_in_file(req)
155
+ except InvalidRequirement:
156
+ logger.debug("Cannot parse '%s' as requirements file", req)
157
+ else:
158
+ msg += (
159
+ f"The argument you provided "
160
+ f"({req}) appears to be a"
161
+ f" requirements file. If that is the"
162
+ f" case, use the '-r' flag to install"
163
+ f" the packages specified within it."
164
+ )
165
+ return msg
166
+
167
+
168
+ class RequirementParts:
169
+ def __init__(
170
+ self,
171
+ requirement: Optional[Requirement],
172
+ link: Optional[Link],
173
+ markers: Optional[Marker],
174
+ extras: Set[str],
175
+ ):
176
+ self.requirement = requirement
177
+ self.link = link
178
+ self.markers = markers
179
+ self.extras = extras
180
+
181
+
182
+ def parse_req_from_editable(editable_req: str) -> RequirementParts:
183
+ name, url, extras_override = parse_editable(editable_req)
184
+
185
+ if name is not None:
186
+ try:
187
+ req: Optional[Requirement] = Requirement(name)
188
+ except InvalidRequirement:
189
+ raise InstallationError(f"Invalid requirement: '{name}'")
190
+ else:
191
+ req = None
192
+
193
+ link = Link(url)
194
+
195
+ return RequirementParts(req, link, None, extras_override)
196
+
197
+
198
+ # ---- The actual constructors follow ----
199
+
200
+
201
+ def install_req_from_editable(
202
+ editable_req: str,
203
+ comes_from: Optional[Union[InstallRequirement, str]] = None,
204
+ *,
205
+ use_pep517: Optional[bool] = None,
206
+ isolated: bool = False,
207
+ global_options: Optional[List[str]] = None,
208
+ hash_options: Optional[Dict[str, List[str]]] = None,
209
+ constraint: bool = False,
210
+ user_supplied: bool = False,
211
+ permit_editable_wheels: bool = False,
212
+ config_settings: Optional[Dict[str, Union[str, List[str]]]] = None,
213
+ ) -> InstallRequirement:
214
+ parts = parse_req_from_editable(editable_req)
215
+
216
+ return InstallRequirement(
217
+ parts.requirement,
218
+ comes_from=comes_from,
219
+ user_supplied=user_supplied,
220
+ editable=True,
221
+ permit_editable_wheels=permit_editable_wheels,
222
+ link=parts.link,
223
+ constraint=constraint,
224
+ use_pep517=use_pep517,
225
+ isolated=isolated,
226
+ global_options=global_options,
227
+ hash_options=hash_options,
228
+ config_settings=config_settings,
229
+ extras=parts.extras,
230
+ )
231
+
232
+
233
+ def _looks_like_path(name: str) -> bool:
234
+ """Checks whether the string "looks like" a path on the filesystem.
235
+
236
+ This does not check whether the target actually exists, only judge from the
237
+ appearance.
238
+
239
+ Returns true if any of the following conditions is true:
240
+ * a path separator is found (either os.path.sep or os.path.altsep);
241
+ * a dot is found (which represents the current directory).
242
+ """
243
+ if os.path.sep in name:
244
+ return True
245
+ if os.path.altsep is not None and os.path.altsep in name:
246
+ return True
247
+ if name.startswith("."):
248
+ return True
249
+ return False
250
+
251
+
252
+ def _get_url_from_path(path: str, name: str) -> Optional[str]:
253
+ """
254
+ First, it checks whether a provided path is an installable directory. If it
255
+ is, returns the path.
256
+
257
+ If false, check if the path is an archive file (such as a .whl).
258
+ The function checks if the path is a file. If false, if the path has
259
+ an @, it will treat it as a PEP 440 URL requirement and return the path.
260
+ """
261
+ if _looks_like_path(name) and os.path.isdir(path):
262
+ if is_installable_dir(path):
263
+ return path_to_url(path)
264
+ # TODO: The is_installable_dir test here might not be necessary
265
+ # now that it is done in load_pyproject_toml too.
266
+ raise InstallationError(
267
+ f"Directory {name!r} is not installable. Neither 'setup.py' "
268
+ "nor 'pyproject.toml' found."
269
+ )
270
+ if not is_archive_file(path):
271
+ return None
272
+ if os.path.isfile(path):
273
+ return path_to_url(path)
274
+ urlreq_parts = name.split("@", 1)
275
+ if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]):
276
+ # If the path contains '@' and the part before it does not look
277
+ # like a path, try to treat it as a PEP 440 URL req instead.
278
+ return None
279
+ logger.warning(
280
+ "Requirement %r looks like a filename, but the file does not exist",
281
+ name,
282
+ )
283
+ return path_to_url(path)
284
+
285
+
286
+ def parse_req_from_line(name: str, line_source: Optional[str]) -> RequirementParts:
287
+ if is_url(name):
288
+ marker_sep = "; "
289
+ else:
290
+ marker_sep = ";"
291
+ if marker_sep in name:
292
+ name, markers_as_string = name.split(marker_sep, 1)
293
+ markers_as_string = markers_as_string.strip()
294
+ if not markers_as_string:
295
+ markers = None
296
+ else:
297
+ markers = Marker(markers_as_string)
298
+ else:
299
+ markers = None
300
+ name = name.strip()
301
+ req_as_string = None
302
+ path = os.path.normpath(os.path.abspath(name))
303
+ link = None
304
+ extras_as_string = None
305
+
306
+ if is_url(name):
307
+ link = Link(name)
308
+ else:
309
+ p, extras_as_string = _strip_extras(path)
310
+ url = _get_url_from_path(p, name)
311
+ if url is not None:
312
+ link = Link(url)
313
+
314
+ # it's a local file, dir, or url
315
+ if link:
316
+ # Handle relative file URLs
317
+ if link.scheme == "file" and re.search(r"\.\./", link.url):
318
+ link = Link(path_to_url(os.path.normpath(os.path.abspath(link.path))))
319
+ # wheel file
320
+ if link.is_wheel:
321
+ wheel = Wheel(link.filename) # can raise InvalidWheelFilename
322
+ req_as_string = f"{wheel.name}=={wheel.version}"
323
+ else:
324
+ # set the req to the egg fragment. when it's not there, this
325
+ # will become an 'unnamed' requirement
326
+ req_as_string = link.egg_fragment
327
+
328
+ # a requirement specifier
329
+ else:
330
+ req_as_string = name
331
+
332
+ extras = convert_extras(extras_as_string)
333
+
334
+ def with_source(text: str) -> str:
335
+ if not line_source:
336
+ return text
337
+ return f"{text} (from {line_source})"
338
+
339
+ def _parse_req_string(req_as_string: str) -> Requirement:
340
+ try:
341
+ req = get_requirement(req_as_string)
342
+ except InvalidRequirement:
343
+ if os.path.sep in req_as_string:
344
+ add_msg = "It looks like a path."
345
+ add_msg += deduce_helpful_msg(req_as_string)
346
+ elif "=" in req_as_string and not any(
347
+ op in req_as_string for op in operators
348
+ ):
349
+ add_msg = "= is not a valid operator. Did you mean == ?"
350
+ else:
351
+ add_msg = ""
352
+ msg = with_source(f"Invalid requirement: {req_as_string!r}")
353
+ if add_msg:
354
+ msg += f"\nHint: {add_msg}"
355
+ raise InstallationError(msg)
356
+ else:
357
+ # Deprecate extras after specifiers: "name>=1.0[extras]"
358
+ # This currently works by accident because _strip_extras() parses
359
+ # any extras in the end of the string and those are saved in
360
+ # RequirementParts
361
+ for spec in req.specifier:
362
+ spec_str = str(spec)
363
+ if spec_str.endswith("]"):
364
+ msg = f"Extras after version '{spec_str}'."
365
+ raise InstallationError(msg)
366
+ return req
367
+
368
+ if req_as_string is not None:
369
+ req: Optional[Requirement] = _parse_req_string(req_as_string)
370
+ else:
371
+ req = None
372
+
373
+ return RequirementParts(req, link, markers, extras)
374
+
375
+
376
+ def install_req_from_line(
377
+ name: str,
378
+ comes_from: Optional[Union[str, InstallRequirement]] = None,
379
+ *,
380
+ use_pep517: Optional[bool] = None,
381
+ isolated: bool = False,
382
+ global_options: Optional[List[str]] = None,
383
+ hash_options: Optional[Dict[str, List[str]]] = None,
384
+ constraint: bool = False,
385
+ line_source: Optional[str] = None,
386
+ user_supplied: bool = False,
387
+ config_settings: Optional[Dict[str, Union[str, List[str]]]] = None,
388
+ ) -> InstallRequirement:
389
+ """Creates an InstallRequirement from a name, which might be a
390
+ requirement, directory containing 'setup.py', filename, or URL.
391
+
392
+ :param line_source: An optional string describing where the line is from,
393
+ for logging purposes in case of an error.
394
+ """
395
+ parts = parse_req_from_line(name, line_source)
396
+
397
+ return InstallRequirement(
398
+ parts.requirement,
399
+ comes_from,
400
+ link=parts.link,
401
+ markers=parts.markers,
402
+ use_pep517=use_pep517,
403
+ isolated=isolated,
404
+ global_options=global_options,
405
+ hash_options=hash_options,
406
+ config_settings=config_settings,
407
+ constraint=constraint,
408
+ extras=parts.extras,
409
+ user_supplied=user_supplied,
410
+ )
411
+
412
+
413
+ def install_req_from_req_string(
414
+ req_string: str,
415
+ comes_from: Optional[InstallRequirement] = None,
416
+ isolated: bool = False,
417
+ use_pep517: Optional[bool] = None,
418
+ user_supplied: bool = False,
419
+ ) -> InstallRequirement:
420
+ try:
421
+ req = get_requirement(req_string)
422
+ except InvalidRequirement:
423
+ raise InstallationError(f"Invalid requirement: '{req_string}'")
424
+
425
+ domains_not_allowed = [
426
+ PyPI.file_storage_domain,
427
+ TestPyPI.file_storage_domain,
428
+ ]
429
+ if (
430
+ req.url
431
+ and comes_from
432
+ and comes_from.link
433
+ and comes_from.link.netloc in domains_not_allowed
434
+ ):
435
+ # Explicitly disallow pypi packages that depend on external urls
436
+ raise InstallationError(
437
+ "Packages installed from PyPI cannot depend on packages "
438
+ "which are not also hosted on PyPI.\n"
439
+ "{} depends on {} ".format(comes_from.name, req)
440
+ )
441
+
442
+ return InstallRequirement(
443
+ req,
444
+ comes_from,
445
+ isolated=isolated,
446
+ use_pep517=use_pep517,
447
+ user_supplied=user_supplied,
448
+ )
449
+
450
+
451
+ def install_req_from_parsed_requirement(
452
+ parsed_req: ParsedRequirement,
453
+ isolated: bool = False,
454
+ use_pep517: Optional[bool] = None,
455
+ user_supplied: bool = False,
456
+ config_settings: Optional[Dict[str, Union[str, List[str]]]] = None,
457
+ ) -> InstallRequirement:
458
+ if parsed_req.is_editable:
459
+ req = install_req_from_editable(
460
+ parsed_req.requirement,
461
+ comes_from=parsed_req.comes_from,
462
+ use_pep517=use_pep517,
463
+ constraint=parsed_req.constraint,
464
+ isolated=isolated,
465
+ user_supplied=user_supplied,
466
+ config_settings=config_settings,
467
+ )
468
+
469
+ else:
470
+ req = install_req_from_line(
471
+ parsed_req.requirement,
472
+ comes_from=parsed_req.comes_from,
473
+ use_pep517=use_pep517,
474
+ isolated=isolated,
475
+ global_options=(
476
+ parsed_req.options.get("global_options", [])
477
+ if parsed_req.options
478
+ else []
479
+ ),
480
+ hash_options=(
481
+ parsed_req.options.get("hashes", {}) if parsed_req.options else {}
482
+ ),
483
+ constraint=parsed_req.constraint,
484
+ line_source=parsed_req.line_source,
485
+ user_supplied=user_supplied,
486
+ config_settings=config_settings,
487
+ )
488
+ return req
489
+
490
+
491
+ def install_req_from_link_and_ireq(
492
+ link: Link, ireq: InstallRequirement
493
+ ) -> InstallRequirement:
494
+ return InstallRequirement(
495
+ req=ireq.req,
496
+ comes_from=ireq.comes_from,
497
+ editable=ireq.editable,
498
+ link=link,
499
+ markers=ireq.markers,
500
+ use_pep517=ireq.use_pep517,
501
+ isolated=ireq.isolated,
502
+ global_options=ireq.global_options,
503
+ hash_options=ireq.hash_options,
504
+ config_settings=ireq.config_settings,
505
+ user_supplied=ireq.user_supplied,
506
+ )
.venv/Lib/site-packages/pip/_internal/req/req_file.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Requirements file parsing
3
+ """
4
+
5
+ import logging
6
+ import optparse
7
+ import os
8
+ import re
9
+ import shlex
10
+ import urllib.parse
11
+ from optparse import Values
12
+ from typing import (
13
+ TYPE_CHECKING,
14
+ Any,
15
+ Callable,
16
+ Dict,
17
+ Generator,
18
+ Iterable,
19
+ List,
20
+ Optional,
21
+ Tuple,
22
+ )
23
+
24
+ from pip._internal.cli import cmdoptions
25
+ from pip._internal.exceptions import InstallationError, RequirementsFileParseError
26
+ from pip._internal.models.search_scope import SearchScope
27
+ from pip._internal.network.session import PipSession
28
+ from pip._internal.network.utils import raise_for_status
29
+ from pip._internal.utils.encoding import auto_decode
30
+ from pip._internal.utils.urls import get_url_scheme
31
+
32
+ if TYPE_CHECKING:
33
+ # NoReturn introduced in 3.6.2; imported only for type checking to maintain
34
+ # pip compatibility with older patch versions of Python 3.6
35
+ from typing import NoReturn
36
+
37
+ from pip._internal.index.package_finder import PackageFinder
38
+
39
+ __all__ = ["parse_requirements"]
40
+
41
+ ReqFileLines = Iterable[Tuple[int, str]]
42
+
43
+ LineParser = Callable[[str], Tuple[str, Values]]
44
+
45
+ SCHEME_RE = re.compile(r"^(http|https|file):", re.I)
46
+ COMMENT_RE = re.compile(r"(^|\s+)#.*$")
47
+
48
+ # Matches environment variable-style values in '${MY_VARIABLE_1}' with the
49
+ # variable name consisting of only uppercase letters, digits or the '_'
50
+ # (underscore). This follows the POSIX standard defined in IEEE Std 1003.1,
51
+ # 2013 Edition.
52
+ ENV_VAR_RE = re.compile(r"(?P<var>\$\{(?P<name>[A-Z0-9_]+)\})")
53
+
54
+ SUPPORTED_OPTIONS: List[Callable[..., optparse.Option]] = [
55
+ cmdoptions.index_url,
56
+ cmdoptions.extra_index_url,
57
+ cmdoptions.no_index,
58
+ cmdoptions.constraints,
59
+ cmdoptions.requirements,
60
+ cmdoptions.editable,
61
+ cmdoptions.find_links,
62
+ cmdoptions.no_binary,
63
+ cmdoptions.only_binary,
64
+ cmdoptions.prefer_binary,
65
+ cmdoptions.require_hashes,
66
+ cmdoptions.pre,
67
+ cmdoptions.trusted_host,
68
+ cmdoptions.use_new_feature,
69
+ ]
70
+
71
+ # options to be passed to requirements
72
+ SUPPORTED_OPTIONS_REQ: List[Callable[..., optparse.Option]] = [
73
+ cmdoptions.global_options,
74
+ cmdoptions.hash,
75
+ cmdoptions.config_settings,
76
+ ]
77
+
78
+ # the 'dest' string values
79
+ SUPPORTED_OPTIONS_REQ_DEST = [str(o().dest) for o in SUPPORTED_OPTIONS_REQ]
80
+
81
+ logger = logging.getLogger(__name__)
82
+
83
+
84
+ class ParsedRequirement:
85
+ def __init__(
86
+ self,
87
+ requirement: str,
88
+ is_editable: bool,
89
+ comes_from: str,
90
+ constraint: bool,
91
+ options: Optional[Dict[str, Any]] = None,
92
+ line_source: Optional[str] = None,
93
+ ) -> None:
94
+ self.requirement = requirement
95
+ self.is_editable = is_editable
96
+ self.comes_from = comes_from
97
+ self.options = options
98
+ self.constraint = constraint
99
+ self.line_source = line_source
100
+
101
+
102
+ class ParsedLine:
103
+ def __init__(
104
+ self,
105
+ filename: str,
106
+ lineno: int,
107
+ args: str,
108
+ opts: Values,
109
+ constraint: bool,
110
+ ) -> None:
111
+ self.filename = filename
112
+ self.lineno = lineno
113
+ self.opts = opts
114
+ self.constraint = constraint
115
+
116
+ if args:
117
+ self.is_requirement = True
118
+ self.is_editable = False
119
+ self.requirement = args
120
+ elif opts.editables:
121
+ self.is_requirement = True
122
+ self.is_editable = True
123
+ # We don't support multiple -e on one line
124
+ self.requirement = opts.editables[0]
125
+ else:
126
+ self.is_requirement = False
127
+
128
+
129
+ def parse_requirements(
130
+ filename: str,
131
+ session: PipSession,
132
+ finder: Optional["PackageFinder"] = None,
133
+ options: Optional[optparse.Values] = None,
134
+ constraint: bool = False,
135
+ ) -> Generator[ParsedRequirement, None, None]:
136
+ """Parse a requirements file and yield ParsedRequirement instances.
137
+
138
+ :param filename: Path or url of requirements file.
139
+ :param session: PipSession instance.
140
+ :param finder: Instance of pip.index.PackageFinder.
141
+ :param options: cli options.
142
+ :param constraint: If true, parsing a constraint file rather than
143
+ requirements file.
144
+ """
145
+ line_parser = get_line_parser(finder)
146
+ parser = RequirementsFileParser(session, line_parser)
147
+
148
+ for parsed_line in parser.parse(filename, constraint):
149
+ parsed_req = handle_line(
150
+ parsed_line, options=options, finder=finder, session=session
151
+ )
152
+ if parsed_req is not None:
153
+ yield parsed_req
154
+
155
+
156
+ def preprocess(content: str) -> ReqFileLines:
157
+ """Split, filter, and join lines, and return a line iterator
158
+
159
+ :param content: the content of the requirements file
160
+ """
161
+ lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1)
162
+ lines_enum = join_lines(lines_enum)
163
+ lines_enum = ignore_comments(lines_enum)
164
+ lines_enum = expand_env_variables(lines_enum)
165
+ return lines_enum
166
+
167
+
168
+ def handle_requirement_line(
169
+ line: ParsedLine,
170
+ options: Optional[optparse.Values] = None,
171
+ ) -> ParsedRequirement:
172
+ # preserve for the nested code path
173
+ line_comes_from = "{} {} (line {})".format(
174
+ "-c" if line.constraint else "-r",
175
+ line.filename,
176
+ line.lineno,
177
+ )
178
+
179
+ assert line.is_requirement
180
+
181
+ if line.is_editable:
182
+ # For editable requirements, we don't support per-requirement
183
+ # options, so just return the parsed requirement.
184
+ return ParsedRequirement(
185
+ requirement=line.requirement,
186
+ is_editable=line.is_editable,
187
+ comes_from=line_comes_from,
188
+ constraint=line.constraint,
189
+ )
190
+ else:
191
+ # get the options that apply to requirements
192
+ req_options = {}
193
+ for dest in SUPPORTED_OPTIONS_REQ_DEST:
194
+ if dest in line.opts.__dict__ and line.opts.__dict__[dest]:
195
+ req_options[dest] = line.opts.__dict__[dest]
196
+
197
+ line_source = f"line {line.lineno} of {line.filename}"
198
+ return ParsedRequirement(
199
+ requirement=line.requirement,
200
+ is_editable=line.is_editable,
201
+ comes_from=line_comes_from,
202
+ constraint=line.constraint,
203
+ options=req_options,
204
+ line_source=line_source,
205
+ )
206
+
207
+
208
+ def handle_option_line(
209
+ opts: Values,
210
+ filename: str,
211
+ lineno: int,
212
+ finder: Optional["PackageFinder"] = None,
213
+ options: Optional[optparse.Values] = None,
214
+ session: Optional[PipSession] = None,
215
+ ) -> None:
216
+ if opts.hashes:
217
+ logger.warning(
218
+ "%s line %s has --hash but no requirement, and will be ignored.",
219
+ filename,
220
+ lineno,
221
+ )
222
+
223
+ if options:
224
+ # percolate options upward
225
+ if opts.require_hashes:
226
+ options.require_hashes = opts.require_hashes
227
+ if opts.features_enabled:
228
+ options.features_enabled.extend(
229
+ f for f in opts.features_enabled if f not in options.features_enabled
230
+ )
231
+
232
+ # set finder options
233
+ if finder:
234
+ find_links = finder.find_links
235
+ index_urls = finder.index_urls
236
+ no_index = finder.search_scope.no_index
237
+ if opts.no_index is True:
238
+ no_index = True
239
+ index_urls = []
240
+ if opts.index_url and not no_index:
241
+ index_urls = [opts.index_url]
242
+ if opts.extra_index_urls and not no_index:
243
+ index_urls.extend(opts.extra_index_urls)
244
+ if opts.find_links:
245
+ # FIXME: it would be nice to keep track of the source
246
+ # of the find_links: support a find-links local path
247
+ # relative to a requirements file.
248
+ value = opts.find_links[0]
249
+ req_dir = os.path.dirname(os.path.abspath(filename))
250
+ relative_to_reqs_file = os.path.join(req_dir, value)
251
+ if os.path.exists(relative_to_reqs_file):
252
+ value = relative_to_reqs_file
253
+ find_links.append(value)
254
+
255
+ if session:
256
+ # We need to update the auth urls in session
257
+ session.update_index_urls(index_urls)
258
+
259
+ search_scope = SearchScope(
260
+ find_links=find_links,
261
+ index_urls=index_urls,
262
+ no_index=no_index,
263
+ )
264
+ finder.search_scope = search_scope
265
+
266
+ if opts.pre:
267
+ finder.set_allow_all_prereleases()
268
+
269
+ if opts.prefer_binary:
270
+ finder.set_prefer_binary()
271
+
272
+ if session:
273
+ for host in opts.trusted_hosts or []:
274
+ source = f"line {lineno} of {filename}"
275
+ session.add_trusted_host(host, source=source)
276
+
277
+
278
+ def handle_line(
279
+ line: ParsedLine,
280
+ options: Optional[optparse.Values] = None,
281
+ finder: Optional["PackageFinder"] = None,
282
+ session: Optional[PipSession] = None,
283
+ ) -> Optional[ParsedRequirement]:
284
+ """Handle a single parsed requirements line; This can result in
285
+ creating/yielding requirements, or updating the finder.
286
+
287
+ :param line: The parsed line to be processed.
288
+ :param options: CLI options.
289
+ :param finder: The finder - updated by non-requirement lines.
290
+ :param session: The session - updated by non-requirement lines.
291
+
292
+ Returns a ParsedRequirement object if the line is a requirement line,
293
+ otherwise returns None.
294
+
295
+ For lines that contain requirements, the only options that have an effect
296
+ are from SUPPORTED_OPTIONS_REQ, and they are scoped to the
297
+ requirement. Other options from SUPPORTED_OPTIONS may be present, but are
298
+ ignored.
299
+
300
+ For lines that do not contain requirements, the only options that have an
301
+ effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may
302
+ be present, but are ignored. These lines may contain multiple options
303
+ (although our docs imply only one is supported), and all our parsed and
304
+ affect the finder.
305
+ """
306
+
307
+ if line.is_requirement:
308
+ parsed_req = handle_requirement_line(line, options)
309
+ return parsed_req
310
+ else:
311
+ handle_option_line(
312
+ line.opts,
313
+ line.filename,
314
+ line.lineno,
315
+ finder,
316
+ options,
317
+ session,
318
+ )
319
+ return None
320
+
321
+
322
+ class RequirementsFileParser:
323
+ def __init__(
324
+ self,
325
+ session: PipSession,
326
+ line_parser: LineParser,
327
+ ) -> None:
328
+ self._session = session
329
+ self._line_parser = line_parser
330
+
331
+ def parse(
332
+ self, filename: str, constraint: bool
333
+ ) -> Generator[ParsedLine, None, None]:
334
+ """Parse a given file, yielding parsed lines."""
335
+ yield from self._parse_and_recurse(filename, constraint)
336
+
337
+ def _parse_and_recurse(
338
+ self, filename: str, constraint: bool
339
+ ) -> Generator[ParsedLine, None, None]:
340
+ for line in self._parse_file(filename, constraint):
341
+ if not line.is_requirement and (
342
+ line.opts.requirements or line.opts.constraints
343
+ ):
344
+ # parse a nested requirements file
345
+ if line.opts.requirements:
346
+ req_path = line.opts.requirements[0]
347
+ nested_constraint = False
348
+ else:
349
+ req_path = line.opts.constraints[0]
350
+ nested_constraint = True
351
+
352
+ # original file is over http
353
+ if SCHEME_RE.search(filename):
354
+ # do a url join so relative paths work
355
+ req_path = urllib.parse.urljoin(filename, req_path)
356
+ # original file and nested file are paths
357
+ elif not SCHEME_RE.search(req_path):
358
+ # do a join so relative paths work
359
+ req_path = os.path.join(
360
+ os.path.dirname(filename),
361
+ req_path,
362
+ )
363
+
364
+ yield from self._parse_and_recurse(req_path, nested_constraint)
365
+ else:
366
+ yield line
367
+
368
+ def _parse_file(
369
+ self, filename: str, constraint: bool
370
+ ) -> Generator[ParsedLine, None, None]:
371
+ _, content = get_file_content(filename, self._session)
372
+
373
+ lines_enum = preprocess(content)
374
+
375
+ for line_number, line in lines_enum:
376
+ try:
377
+ args_str, opts = self._line_parser(line)
378
+ except OptionParsingError as e:
379
+ # add offending line
380
+ msg = f"Invalid requirement: {line}\n{e.msg}"
381
+ raise RequirementsFileParseError(msg)
382
+
383
+ yield ParsedLine(
384
+ filename,
385
+ line_number,
386
+ args_str,
387
+ opts,
388
+ constraint,
389
+ )
390
+
391
+
392
+ def get_line_parser(finder: Optional["PackageFinder"]) -> LineParser:
393
+ def parse_line(line: str) -> Tuple[str, Values]:
394
+ # Build new parser for each line since it accumulates appendable
395
+ # options.
396
+ parser = build_parser()
397
+ defaults = parser.get_default_values()
398
+ defaults.index_url = None
399
+ if finder:
400
+ defaults.format_control = finder.format_control
401
+
402
+ args_str, options_str = break_args_options(line)
403
+
404
+ try:
405
+ options = shlex.split(options_str)
406
+ except ValueError as e:
407
+ raise OptionParsingError(f"Could not split options: {options_str}") from e
408
+
409
+ opts, _ = parser.parse_args(options, defaults)
410
+
411
+ return args_str, opts
412
+
413
+ return parse_line
414
+
415
+
416
+ def break_args_options(line: str) -> Tuple[str, str]:
417
+ """Break up the line into an args and options string. We only want to shlex
418
+ (and then optparse) the options, not the args. args can contain markers
419
+ which are corrupted by shlex.
420
+ """
421
+ tokens = line.split(" ")
422
+ args = []
423
+ options = tokens[:]
424
+ for token in tokens:
425
+ if token.startswith("-") or token.startswith("--"):
426
+ break
427
+ else:
428
+ args.append(token)
429
+ options.pop(0)
430
+ return " ".join(args), " ".join(options)
431
+
432
+
433
+ class OptionParsingError(Exception):
434
+ def __init__(self, msg: str) -> None:
435
+ self.msg = msg
436
+
437
+
438
+ def build_parser() -> optparse.OptionParser:
439
+ """
440
+ Return a parser for parsing requirement lines
441
+ """
442
+ parser = optparse.OptionParser(add_help_option=False)
443
+
444
+ option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
445
+ for option_factory in option_factories:
446
+ option = option_factory()
447
+ parser.add_option(option)
448
+
449
+ # By default optparse sys.exits on parsing errors. We want to wrap
450
+ # that in our own exception.
451
+ def parser_exit(self: Any, msg: str) -> "NoReturn":
452
+ raise OptionParsingError(msg)
453
+
454
+ # NOTE: mypy disallows assigning to a method
455
+ # https://github.com/python/mypy/issues/2427
456
+ parser.exit = parser_exit # type: ignore
457
+
458
+ return parser
459
+
460
+
461
+ def join_lines(lines_enum: ReqFileLines) -> ReqFileLines:
462
+ """Joins a line ending in '\' with the previous line (except when following
463
+ comments). The joined line takes on the index of the first line.
464
+ """
465
+ primary_line_number = None
466
+ new_line: List[str] = []
467
+ for line_number, line in lines_enum:
468
+ if not line.endswith("\\") or COMMENT_RE.match(line):
469
+ if COMMENT_RE.match(line):
470
+ # this ensures comments are always matched later
471
+ line = " " + line
472
+ if new_line:
473
+ new_line.append(line)
474
+ assert primary_line_number is not None
475
+ yield primary_line_number, "".join(new_line)
476
+ new_line = []
477
+ else:
478
+ yield line_number, line
479
+ else:
480
+ if not new_line:
481
+ primary_line_number = line_number
482
+ new_line.append(line.strip("\\"))
483
+
484
+ # last line contains \
485
+ if new_line:
486
+ assert primary_line_number is not None
487
+ yield primary_line_number, "".join(new_line)
488
+
489
+ # TODO: handle space after '\'.
490
+
491
+
492
+ def ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines:
493
+ """
494
+ Strips comments and filter empty lines.
495
+ """
496
+ for line_number, line in lines_enum:
497
+ line = COMMENT_RE.sub("", line)
498
+ line = line.strip()
499
+ if line:
500
+ yield line_number, line
501
+
502
+
503
+ def expand_env_variables(lines_enum: ReqFileLines) -> ReqFileLines:
504
+ """Replace all environment variables that can be retrieved via `os.getenv`.
505
+
506
+ The only allowed format for environment variables defined in the
507
+ requirement file is `${MY_VARIABLE_1}` to ensure two things:
508
+
509
+ 1. Strings that contain a `$` aren't accidentally (partially) expanded.
510
+ 2. Ensure consistency across platforms for requirement files.
511
+
512
+ These points are the result of a discussion on the `github pull
513
+ request #3514 <https://github.com/pypa/pip/pull/3514>`_.
514
+
515
+ Valid characters in variable names follow the `POSIX standard
516
+ <http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
517
+ to uppercase letter, digits and the `_` (underscore).
518
+ """
519
+ for line_number, line in lines_enum:
520
+ for env_var, var_name in ENV_VAR_RE.findall(line):
521
+ value = os.getenv(var_name)
522
+ if not value:
523
+ continue
524
+
525
+ line = line.replace(env_var, value)
526
+
527
+ yield line_number, line
528
+
529
+
530
+ def get_file_content(url: str, session: PipSession) -> Tuple[str, str]:
531
+ """Gets the content of a file; it may be a filename, file: URL, or
532
+ http: URL. Returns (location, content). Content is unicode.
533
+ Respects # -*- coding: declarations on the retrieved files.
534
+
535
+ :param url: File path or url.
536
+ :param session: PipSession instance.
537
+ """
538
+ scheme = get_url_scheme(url)
539
+
540
+ # Pip has special support for file:// URLs (LocalFSAdapter).
541
+ if scheme in ["http", "https", "file"]:
542
+ resp = session.get(url)
543
+ raise_for_status(resp)
544
+ return resp.url, resp.text
545
+
546
+ # Assume this is a bare path.
547
+ try:
548
+ with open(url, "rb") as f:
549
+ content = auto_decode(f.read())
550
+ except OSError as exc:
551
+ raise InstallationError(f"Could not open requirements file: {exc}")
552
+ return url, content
.venv/Lib/site-packages/pip/_internal/req/req_install.py ADDED
@@ -0,0 +1,874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The following comment should be removed at some point in the future.
2
+ # mypy: strict-optional=False
3
+
4
+ import functools
5
+ import logging
6
+ import os
7
+ import shutil
8
+ import sys
9
+ import uuid
10
+ import zipfile
11
+ from optparse import Values
12
+ from typing import Any, Collection, Dict, Iterable, List, Optional, Sequence, Union
13
+
14
+ from pip._vendor.packaging.markers import Marker
15
+ from pip._vendor.packaging.requirements import Requirement
16
+ from pip._vendor.packaging.specifiers import SpecifierSet
17
+ from pip._vendor.packaging.utils import canonicalize_name
18
+ from pip._vendor.packaging.version import Version
19
+ from pip._vendor.packaging.version import parse as parse_version
20
+ from pip._vendor.pyproject_hooks import BuildBackendHookCaller
21
+
22
+ from pip._internal.build_env import BuildEnvironment, NoOpBuildEnvironment
23
+ from pip._internal.exceptions import InstallationError
24
+ from pip._internal.locations import get_scheme
25
+ from pip._internal.metadata import (
26
+ BaseDistribution,
27
+ get_default_environment,
28
+ get_directory_distribution,
29
+ get_wheel_distribution,
30
+ )
31
+ from pip._internal.metadata.base import FilesystemWheel
32
+ from pip._internal.models.direct_url import DirectUrl
33
+ from pip._internal.models.link import Link
34
+ from pip._internal.operations.build.metadata import generate_metadata
35
+ from pip._internal.operations.build.metadata_editable import generate_editable_metadata
36
+ from pip._internal.operations.build.metadata_legacy import (
37
+ generate_metadata as generate_metadata_legacy,
38
+ )
39
+ from pip._internal.operations.install.editable_legacy import (
40
+ install_editable as install_editable_legacy,
41
+ )
42
+ from pip._internal.operations.install.wheel import install_wheel
43
+ from pip._internal.pyproject import load_pyproject_toml, make_pyproject_path
44
+ from pip._internal.req.req_uninstall import UninstallPathSet
45
+ from pip._internal.utils.deprecation import deprecated
46
+ from pip._internal.utils.hashes import Hashes
47
+ from pip._internal.utils.misc import (
48
+ ConfiguredBuildBackendHookCaller,
49
+ ask_path_exists,
50
+ backup_dir,
51
+ display_path,
52
+ hide_url,
53
+ redact_auth_from_url,
54
+ )
55
+ from pip._internal.utils.packaging import safe_extra
56
+ from pip._internal.utils.subprocess import runner_with_spinner_message
57
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
58
+ from pip._internal.utils.virtualenv import running_under_virtualenv
59
+ from pip._internal.vcs import vcs
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+
64
+ class InstallRequirement:
65
+ """
66
+ Represents something that may be installed later on, may have information
67
+ about where to fetch the relevant requirement and also contains logic for
68
+ installing the said requirement.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ req: Optional[Requirement],
74
+ comes_from: Optional[Union[str, "InstallRequirement"]],
75
+ editable: bool = False,
76
+ link: Optional[Link] = None,
77
+ markers: Optional[Marker] = None,
78
+ use_pep517: Optional[bool] = None,
79
+ isolated: bool = False,
80
+ *,
81
+ global_options: Optional[List[str]] = None,
82
+ hash_options: Optional[Dict[str, List[str]]] = None,
83
+ config_settings: Optional[Dict[str, Union[str, List[str]]]] = None,
84
+ constraint: bool = False,
85
+ extras: Collection[str] = (),
86
+ user_supplied: bool = False,
87
+ permit_editable_wheels: bool = False,
88
+ ) -> None:
89
+ assert req is None or isinstance(req, Requirement), req
90
+ self.req = req
91
+ self.comes_from = comes_from
92
+ self.constraint = constraint
93
+ self.editable = editable
94
+ self.permit_editable_wheels = permit_editable_wheels
95
+
96
+ # source_dir is the local directory where the linked requirement is
97
+ # located, or unpacked. In case unpacking is needed, creating and
98
+ # populating source_dir is done by the RequirementPreparer. Note this
99
+ # is not necessarily the directory where pyproject.toml or setup.py is
100
+ # located - that one is obtained via unpacked_source_directory.
101
+ self.source_dir: Optional[str] = None
102
+ if self.editable:
103
+ assert link
104
+ if link.is_file:
105
+ self.source_dir = os.path.normpath(os.path.abspath(link.file_path))
106
+
107
+ # original_link is the direct URL that was provided by the user for the
108
+ # requirement, either directly or via a constraints file.
109
+ if link is None and req and req.url:
110
+ # PEP 508 URL requirement
111
+ link = Link(req.url)
112
+ self.link = self.original_link = link
113
+
114
+ # When this InstallRequirement is a wheel obtained from the cache of locally
115
+ # built wheels, this is the source link corresponding to the cache entry, which
116
+ # was used to download and build the cached wheel.
117
+ self.cached_wheel_source_link: Optional[Link] = None
118
+
119
+ # Information about the location of the artifact that was downloaded . This
120
+ # property is guaranteed to be set in resolver results.
121
+ self.download_info: Optional[DirectUrl] = None
122
+
123
+ # Path to any downloaded or already-existing package.
124
+ self.local_file_path: Optional[str] = None
125
+ if self.link and self.link.is_file:
126
+ self.local_file_path = self.link.file_path
127
+
128
+ if extras:
129
+ self.extras = extras
130
+ elif req:
131
+ self.extras = {safe_extra(extra) for extra in req.extras}
132
+ else:
133
+ self.extras = set()
134
+ if markers is None and req:
135
+ markers = req.marker
136
+ self.markers = markers
137
+
138
+ # This holds the Distribution object if this requirement is already installed.
139
+ self.satisfied_by: Optional[BaseDistribution] = None
140
+ # Whether the installation process should try to uninstall an existing
141
+ # distribution before installing this requirement.
142
+ self.should_reinstall = False
143
+ # Temporary build location
144
+ self._temp_build_dir: Optional[TempDirectory] = None
145
+ # Set to True after successful installation
146
+ self.install_succeeded: Optional[bool] = None
147
+ # Supplied options
148
+ self.global_options = global_options if global_options else []
149
+ self.hash_options = hash_options if hash_options else {}
150
+ self.config_settings = config_settings
151
+ # Set to True after successful preparation of this requirement
152
+ self.prepared = False
153
+ # User supplied requirement are explicitly requested for installation
154
+ # by the user via CLI arguments or requirements files, as opposed to,
155
+ # e.g. dependencies, extras or constraints.
156
+ self.user_supplied = user_supplied
157
+
158
+ self.isolated = isolated
159
+ self.build_env: BuildEnvironment = NoOpBuildEnvironment()
160
+
161
+ # For PEP 517, the directory where we request the project metadata
162
+ # gets stored. We need this to pass to build_wheel, so the backend
163
+ # can ensure that the wheel matches the metadata (see the PEP for
164
+ # details).
165
+ self.metadata_directory: Optional[str] = None
166
+
167
+ # The static build requirements (from pyproject.toml)
168
+ self.pyproject_requires: Optional[List[str]] = None
169
+
170
+ # Build requirements that we will check are available
171
+ self.requirements_to_check: List[str] = []
172
+
173
+ # The PEP 517 backend we should use to build the project
174
+ self.pep517_backend: Optional[BuildBackendHookCaller] = None
175
+
176
+ # Are we using PEP 517 for this requirement?
177
+ # After pyproject.toml has been loaded, the only valid values are True
178
+ # and False. Before loading, None is valid (meaning "use the default").
179
+ # Setting an explicit value before loading pyproject.toml is supported,
180
+ # but after loading this flag should be treated as read only.
181
+ self.use_pep517 = use_pep517
182
+
183
+ # This requirement needs more preparation before it can be built
184
+ self.needs_more_preparation = False
185
+
186
+ def __str__(self) -> str:
187
+ if self.req:
188
+ s = str(self.req)
189
+ if self.link:
190
+ s += " from {}".format(redact_auth_from_url(self.link.url))
191
+ elif self.link:
192
+ s = redact_auth_from_url(self.link.url)
193
+ else:
194
+ s = "<InstallRequirement>"
195
+ if self.satisfied_by is not None:
196
+ if self.satisfied_by.location is not None:
197
+ location = display_path(self.satisfied_by.location)
198
+ else:
199
+ location = "<memory>"
200
+ s += f" in {location}"
201
+ if self.comes_from:
202
+ if isinstance(self.comes_from, str):
203
+ comes_from: Optional[str] = self.comes_from
204
+ else:
205
+ comes_from = self.comes_from.from_path()
206
+ if comes_from:
207
+ s += f" (from {comes_from})"
208
+ return s
209
+
210
+ def __repr__(self) -> str:
211
+ return "<{} object: {} editable={!r}>".format(
212
+ self.__class__.__name__, str(self), self.editable
213
+ )
214
+
215
+ def format_debug(self) -> str:
216
+ """An un-tested helper for getting state, for debugging."""
217
+ attributes = vars(self)
218
+ names = sorted(attributes)
219
+
220
+ state = ("{}={!r}".format(attr, attributes[attr]) for attr in sorted(names))
221
+ return "<{name} object: {{{state}}}>".format(
222
+ name=self.__class__.__name__,
223
+ state=", ".join(state),
224
+ )
225
+
226
+ # Things that are valid for all kinds of requirements?
227
+ @property
228
+ def name(self) -> Optional[str]:
229
+ if self.req is None:
230
+ return None
231
+ return self.req.name
232
+
233
+ @functools.lru_cache() # use cached_property in python 3.8+
234
+ def supports_pyproject_editable(self) -> bool:
235
+ if not self.use_pep517:
236
+ return False
237
+ assert self.pep517_backend
238
+ with self.build_env:
239
+ runner = runner_with_spinner_message(
240
+ "Checking if build backend supports build_editable"
241
+ )
242
+ with self.pep517_backend.subprocess_runner(runner):
243
+ return "build_editable" in self.pep517_backend._supported_features()
244
+
245
+ @property
246
+ def specifier(self) -> SpecifierSet:
247
+ return self.req.specifier
248
+
249
+ @property
250
+ def is_direct(self) -> bool:
251
+ """Whether this requirement was specified as a direct URL."""
252
+ return self.original_link is not None
253
+
254
+ @property
255
+ def is_pinned(self) -> bool:
256
+ """Return whether I am pinned to an exact version.
257
+
258
+ For example, some-package==1.2 is pinned; some-package>1.2 is not.
259
+ """
260
+ specifiers = self.specifier
261
+ return len(specifiers) == 1 and next(iter(specifiers)).operator in {"==", "==="}
262
+
263
+ def match_markers(self, extras_requested: Optional[Iterable[str]] = None) -> bool:
264
+ if not extras_requested:
265
+ # Provide an extra to safely evaluate the markers
266
+ # without matching any extra
267
+ extras_requested = ("",)
268
+ if self.markers is not None:
269
+ return any(
270
+ self.markers.evaluate({"extra": extra}) for extra in extras_requested
271
+ )
272
+ else:
273
+ return True
274
+
275
+ @property
276
+ def has_hash_options(self) -> bool:
277
+ """Return whether any known-good hashes are specified as options.
278
+
279
+ These activate --require-hashes mode; hashes specified as part of a
280
+ URL do not.
281
+
282
+ """
283
+ return bool(self.hash_options)
284
+
285
+ def hashes(self, trust_internet: bool = True) -> Hashes:
286
+ """Return a hash-comparer that considers my option- and URL-based
287
+ hashes to be known-good.
288
+
289
+ Hashes in URLs--ones embedded in the requirements file, not ones
290
+ downloaded from an index server--are almost peers with ones from
291
+ flags. They satisfy --require-hashes (whether it was implicitly or
292
+ explicitly activated) but do not activate it. md5 and sha224 are not
293
+ allowed in flags, which should nudge people toward good algos. We
294
+ always OR all hashes together, even ones from URLs.
295
+
296
+ :param trust_internet: Whether to trust URL-based (#md5=...) hashes
297
+ downloaded from the internet, as by populate_link()
298
+
299
+ """
300
+ good_hashes = self.hash_options.copy()
301
+ if trust_internet:
302
+ link = self.link
303
+ elif self.is_direct and self.user_supplied:
304
+ link = self.original_link
305
+ else:
306
+ link = None
307
+ if link and link.hash:
308
+ good_hashes.setdefault(link.hash_name, []).append(link.hash)
309
+ return Hashes(good_hashes)
310
+
311
+ def from_path(self) -> Optional[str]:
312
+ """Format a nice indicator to show where this "comes from" """
313
+ if self.req is None:
314
+ return None
315
+ s = str(self.req)
316
+ if self.comes_from:
317
+ if isinstance(self.comes_from, str):
318
+ comes_from = self.comes_from
319
+ else:
320
+ comes_from = self.comes_from.from_path()
321
+ if comes_from:
322
+ s += "->" + comes_from
323
+ return s
324
+
325
+ def ensure_build_location(
326
+ self, build_dir: str, autodelete: bool, parallel_builds: bool
327
+ ) -> str:
328
+ assert build_dir is not None
329
+ if self._temp_build_dir is not None:
330
+ assert self._temp_build_dir.path
331
+ return self._temp_build_dir.path
332
+ if self.req is None:
333
+ # Some systems have /tmp as a symlink which confuses custom
334
+ # builds (such as numpy). Thus, we ensure that the real path
335
+ # is returned.
336
+ self._temp_build_dir = TempDirectory(
337
+ kind=tempdir_kinds.REQ_BUILD, globally_managed=True
338
+ )
339
+
340
+ return self._temp_build_dir.path
341
+
342
+ # This is the only remaining place where we manually determine the path
343
+ # for the temporary directory. It is only needed for editables where
344
+ # it is the value of the --src option.
345
+
346
+ # When parallel builds are enabled, add a UUID to the build directory
347
+ # name so multiple builds do not interfere with each other.
348
+ dir_name: str = canonicalize_name(self.name)
349
+ if parallel_builds:
350
+ dir_name = f"{dir_name}_{uuid.uuid4().hex}"
351
+
352
+ # FIXME: Is there a better place to create the build_dir? (hg and bzr
353
+ # need this)
354
+ if not os.path.exists(build_dir):
355
+ logger.debug("Creating directory %s", build_dir)
356
+ os.makedirs(build_dir)
357
+ actual_build_dir = os.path.join(build_dir, dir_name)
358
+ # `None` indicates that we respect the globally-configured deletion
359
+ # settings, which is what we actually want when auto-deleting.
360
+ delete_arg = None if autodelete else False
361
+ return TempDirectory(
362
+ path=actual_build_dir,
363
+ delete=delete_arg,
364
+ kind=tempdir_kinds.REQ_BUILD,
365
+ globally_managed=True,
366
+ ).path
367
+
368
+ def _set_requirement(self) -> None:
369
+ """Set requirement after generating metadata."""
370
+ assert self.req is None
371
+ assert self.metadata is not None
372
+ assert self.source_dir is not None
373
+
374
+ # Construct a Requirement object from the generated metadata
375
+ if isinstance(parse_version(self.metadata["Version"]), Version):
376
+ op = "=="
377
+ else:
378
+ op = "==="
379
+
380
+ self.req = Requirement(
381
+ "".join(
382
+ [
383
+ self.metadata["Name"],
384
+ op,
385
+ self.metadata["Version"],
386
+ ]
387
+ )
388
+ )
389
+
390
+ def warn_on_mismatching_name(self) -> None:
391
+ metadata_name = canonicalize_name(self.metadata["Name"])
392
+ if canonicalize_name(self.req.name) == metadata_name:
393
+ # Everything is fine.
394
+ return
395
+
396
+ # If we're here, there's a mismatch. Log a warning about it.
397
+ logger.warning(
398
+ "Generating metadata for package %s "
399
+ "produced metadata for project name %s. Fix your "
400
+ "#egg=%s fragments.",
401
+ self.name,
402
+ metadata_name,
403
+ self.name,
404
+ )
405
+ self.req = Requirement(metadata_name)
406
+
407
+ def check_if_exists(self, use_user_site: bool) -> None:
408
+ """Find an installed distribution that satisfies or conflicts
409
+ with this requirement, and set self.satisfied_by or
410
+ self.should_reinstall appropriately.
411
+ """
412
+ if self.req is None:
413
+ return
414
+ existing_dist = get_default_environment().get_distribution(self.req.name)
415
+ if not existing_dist:
416
+ return
417
+
418
+ version_compatible = self.req.specifier.contains(
419
+ existing_dist.version,
420
+ prereleases=True,
421
+ )
422
+ if not version_compatible:
423
+ self.satisfied_by = None
424
+ if use_user_site:
425
+ if existing_dist.in_usersite:
426
+ self.should_reinstall = True
427
+ elif running_under_virtualenv() and existing_dist.in_site_packages:
428
+ raise InstallationError(
429
+ f"Will not install to the user site because it will "
430
+ f"lack sys.path precedence to {existing_dist.raw_name} "
431
+ f"in {existing_dist.location}"
432
+ )
433
+ else:
434
+ self.should_reinstall = True
435
+ else:
436
+ if self.editable:
437
+ self.should_reinstall = True
438
+ # when installing editables, nothing pre-existing should ever
439
+ # satisfy
440
+ self.satisfied_by = None
441
+ else:
442
+ self.satisfied_by = existing_dist
443
+
444
+ # Things valid for wheels
445
+ @property
446
+ def is_wheel(self) -> bool:
447
+ if not self.link:
448
+ return False
449
+ return self.link.is_wheel
450
+
451
+ @property
452
+ def is_wheel_from_cache(self) -> bool:
453
+ # When True, it means that this InstallRequirement is a local wheel file in the
454
+ # cache of locally built wheels.
455
+ return self.cached_wheel_source_link is not None
456
+
457
+ # Things valid for sdists
458
+ @property
459
+ def unpacked_source_directory(self) -> str:
460
+ return os.path.join(
461
+ self.source_dir, self.link and self.link.subdirectory_fragment or ""
462
+ )
463
+
464
+ @property
465
+ def setup_py_path(self) -> str:
466
+ assert self.source_dir, f"No source dir for {self}"
467
+ setup_py = os.path.join(self.unpacked_source_directory, "setup.py")
468
+
469
+ return setup_py
470
+
471
+ @property
472
+ def setup_cfg_path(self) -> str:
473
+ assert self.source_dir, f"No source dir for {self}"
474
+ setup_cfg = os.path.join(self.unpacked_source_directory, "setup.cfg")
475
+
476
+ return setup_cfg
477
+
478
+ @property
479
+ def pyproject_toml_path(self) -> str:
480
+ assert self.source_dir, f"No source dir for {self}"
481
+ return make_pyproject_path(self.unpacked_source_directory)
482
+
483
+ def load_pyproject_toml(self) -> None:
484
+ """Load the pyproject.toml file.
485
+
486
+ After calling this routine, all of the attributes related to PEP 517
487
+ processing for this requirement have been set. In particular, the
488
+ use_pep517 attribute can be used to determine whether we should
489
+ follow the PEP 517 or legacy (setup.py) code path.
490
+ """
491
+ pyproject_toml_data = load_pyproject_toml(
492
+ self.use_pep517, self.pyproject_toml_path, self.setup_py_path, str(self)
493
+ )
494
+
495
+ if pyproject_toml_data is None:
496
+ if self.config_settings:
497
+ deprecated(
498
+ reason=f"Config settings are ignored for project {self}.",
499
+ replacement=(
500
+ "to use --use-pep517 or add a "
501
+ "pyproject.toml file to the project"
502
+ ),
503
+ gone_in="23.3",
504
+ )
505
+ self.use_pep517 = False
506
+ return
507
+
508
+ self.use_pep517 = True
509
+ requires, backend, check, backend_path = pyproject_toml_data
510
+ self.requirements_to_check = check
511
+ self.pyproject_requires = requires
512
+ self.pep517_backend = ConfiguredBuildBackendHookCaller(
513
+ self,
514
+ self.unpacked_source_directory,
515
+ backend,
516
+ backend_path=backend_path,
517
+ )
518
+
519
+ def isolated_editable_sanity_check(self) -> None:
520
+ """Check that an editable requirement if valid for use with PEP 517/518.
521
+
522
+ This verifies that an editable that has a pyproject.toml either supports PEP 660
523
+ or as a setup.py or a setup.cfg
524
+ """
525
+ if (
526
+ self.editable
527
+ and self.use_pep517
528
+ and not self.supports_pyproject_editable()
529
+ and not os.path.isfile(self.setup_py_path)
530
+ and not os.path.isfile(self.setup_cfg_path)
531
+ ):
532
+ raise InstallationError(
533
+ f"Project {self} has a 'pyproject.toml' and its build "
534
+ f"backend is missing the 'build_editable' hook. Since it does not "
535
+ f"have a 'setup.py' nor a 'setup.cfg', "
536
+ f"it cannot be installed in editable mode. "
537
+ f"Consider using a build backend that supports PEP 660."
538
+ )
539
+
540
+ def prepare_metadata(self) -> None:
541
+ """Ensure that project metadata is available.
542
+
543
+ Under PEP 517 and PEP 660, call the backend hook to prepare the metadata.
544
+ Under legacy processing, call setup.py egg-info.
545
+ """
546
+ assert self.source_dir
547
+ details = self.name or f"from {self.link}"
548
+
549
+ if self.use_pep517:
550
+ assert self.pep517_backend is not None
551
+ if (
552
+ self.editable
553
+ and self.permit_editable_wheels
554
+ and self.supports_pyproject_editable()
555
+ ):
556
+ self.metadata_directory = generate_editable_metadata(
557
+ build_env=self.build_env,
558
+ backend=self.pep517_backend,
559
+ details=details,
560
+ )
561
+ else:
562
+ self.metadata_directory = generate_metadata(
563
+ build_env=self.build_env,
564
+ backend=self.pep517_backend,
565
+ details=details,
566
+ )
567
+ else:
568
+ self.metadata_directory = generate_metadata_legacy(
569
+ build_env=self.build_env,
570
+ setup_py_path=self.setup_py_path,
571
+ source_dir=self.unpacked_source_directory,
572
+ isolated=self.isolated,
573
+ details=details,
574
+ )
575
+
576
+ # Act on the newly generated metadata, based on the name and version.
577
+ if not self.name:
578
+ self._set_requirement()
579
+ else:
580
+ self.warn_on_mismatching_name()
581
+
582
+ self.assert_source_matches_version()
583
+
584
+ @property
585
+ def metadata(self) -> Any:
586
+ if not hasattr(self, "_metadata"):
587
+ self._metadata = self.get_dist().metadata
588
+
589
+ return self._metadata
590
+
591
+ def get_dist(self) -> BaseDistribution:
592
+ if self.metadata_directory:
593
+ return get_directory_distribution(self.metadata_directory)
594
+ elif self.local_file_path and self.is_wheel:
595
+ return get_wheel_distribution(
596
+ FilesystemWheel(self.local_file_path), canonicalize_name(self.name)
597
+ )
598
+ raise AssertionError(
599
+ f"InstallRequirement {self} has no metadata directory and no wheel: "
600
+ f"can't make a distribution."
601
+ )
602
+
603
+ def assert_source_matches_version(self) -> None:
604
+ assert self.source_dir
605
+ version = self.metadata["version"]
606
+ if self.req.specifier and version not in self.req.specifier:
607
+ logger.warning(
608
+ "Requested %s, but installing version %s",
609
+ self,
610
+ version,
611
+ )
612
+ else:
613
+ logger.debug(
614
+ "Source in %s has version %s, which satisfies requirement %s",
615
+ display_path(self.source_dir),
616
+ version,
617
+ self,
618
+ )
619
+
620
+ # For both source distributions and editables
621
+ def ensure_has_source_dir(
622
+ self,
623
+ parent_dir: str,
624
+ autodelete: bool = False,
625
+ parallel_builds: bool = False,
626
+ ) -> None:
627
+ """Ensure that a source_dir is set.
628
+
629
+ This will create a temporary build dir if the name of the requirement
630
+ isn't known yet.
631
+
632
+ :param parent_dir: The ideal pip parent_dir for the source_dir.
633
+ Generally src_dir for editables and build_dir for sdists.
634
+ :return: self.source_dir
635
+ """
636
+ if self.source_dir is None:
637
+ self.source_dir = self.ensure_build_location(
638
+ parent_dir,
639
+ autodelete=autodelete,
640
+ parallel_builds=parallel_builds,
641
+ )
642
+
643
+ # For editable installations
644
+ def update_editable(self) -> None:
645
+ if not self.link:
646
+ logger.debug(
647
+ "Cannot update repository at %s; repository location is unknown",
648
+ self.source_dir,
649
+ )
650
+ return
651
+ assert self.editable
652
+ assert self.source_dir
653
+ if self.link.scheme == "file":
654
+ # Static paths don't get updated
655
+ return
656
+ vcs_backend = vcs.get_backend_for_scheme(self.link.scheme)
657
+ # Editable requirements are validated in Requirement constructors.
658
+ # So here, if it's neither a path nor a valid VCS URL, it's a bug.
659
+ assert vcs_backend, f"Unsupported VCS URL {self.link.url}"
660
+ hidden_url = hide_url(self.link.url)
661
+ vcs_backend.obtain(self.source_dir, url=hidden_url, verbosity=0)
662
+
663
+ # Top-level Actions
664
+ def uninstall(
665
+ self, auto_confirm: bool = False, verbose: bool = False
666
+ ) -> Optional[UninstallPathSet]:
667
+ """
668
+ Uninstall the distribution currently satisfying this requirement.
669
+
670
+ Prompts before removing or modifying files unless
671
+ ``auto_confirm`` is True.
672
+
673
+ Refuses to delete or modify files outside of ``sys.prefix`` -
674
+ thus uninstallation within a virtual environment can only
675
+ modify that virtual environment, even if the virtualenv is
676
+ linked to global site-packages.
677
+
678
+ """
679
+ assert self.req
680
+ dist = get_default_environment().get_distribution(self.req.name)
681
+ if not dist:
682
+ logger.warning("Skipping %s as it is not installed.", self.name)
683
+ return None
684
+ logger.info("Found existing installation: %s", dist)
685
+
686
+ uninstalled_pathset = UninstallPathSet.from_dist(dist)
687
+ uninstalled_pathset.remove(auto_confirm, verbose)
688
+ return uninstalled_pathset
689
+
690
+ def _get_archive_name(self, path: str, parentdir: str, rootdir: str) -> str:
691
+ def _clean_zip_name(name: str, prefix: str) -> str:
692
+ assert name.startswith(
693
+ prefix + os.path.sep
694
+ ), f"name {name!r} doesn't start with prefix {prefix!r}"
695
+ name = name[len(prefix) + 1 :]
696
+ name = name.replace(os.path.sep, "/")
697
+ return name
698
+
699
+ path = os.path.join(parentdir, path)
700
+ name = _clean_zip_name(path, rootdir)
701
+ return self.name + "/" + name
702
+
703
+ def archive(self, build_dir: Optional[str]) -> None:
704
+ """Saves archive to provided build_dir.
705
+
706
+ Used for saving downloaded VCS requirements as part of `pip download`.
707
+ """
708
+ assert self.source_dir
709
+ if build_dir is None:
710
+ return
711
+
712
+ create_archive = True
713
+ archive_name = "{}-{}.zip".format(self.name, self.metadata["version"])
714
+ archive_path = os.path.join(build_dir, archive_name)
715
+
716
+ if os.path.exists(archive_path):
717
+ response = ask_path_exists(
718
+ "The file {} exists. (i)gnore, (w)ipe, "
719
+ "(b)ackup, (a)bort ".format(display_path(archive_path)),
720
+ ("i", "w", "b", "a"),
721
+ )
722
+ if response == "i":
723
+ create_archive = False
724
+ elif response == "w":
725
+ logger.warning("Deleting %s", display_path(archive_path))
726
+ os.remove(archive_path)
727
+ elif response == "b":
728
+ dest_file = backup_dir(archive_path)
729
+ logger.warning(
730
+ "Backing up %s to %s",
731
+ display_path(archive_path),
732
+ display_path(dest_file),
733
+ )
734
+ shutil.move(archive_path, dest_file)
735
+ elif response == "a":
736
+ sys.exit(-1)
737
+
738
+ if not create_archive:
739
+ return
740
+
741
+ zip_output = zipfile.ZipFile(
742
+ archive_path,
743
+ "w",
744
+ zipfile.ZIP_DEFLATED,
745
+ allowZip64=True,
746
+ )
747
+ with zip_output:
748
+ dir = os.path.normcase(os.path.abspath(self.unpacked_source_directory))
749
+ for dirpath, dirnames, filenames in os.walk(dir):
750
+ for dirname in dirnames:
751
+ dir_arcname = self._get_archive_name(
752
+ dirname,
753
+ parentdir=dirpath,
754
+ rootdir=dir,
755
+ )
756
+ zipdir = zipfile.ZipInfo(dir_arcname + "/")
757
+ zipdir.external_attr = 0x1ED << 16 # 0o755
758
+ zip_output.writestr(zipdir, "")
759
+ for filename in filenames:
760
+ file_arcname = self._get_archive_name(
761
+ filename,
762
+ parentdir=dirpath,
763
+ rootdir=dir,
764
+ )
765
+ filename = os.path.join(dirpath, filename)
766
+ zip_output.write(filename, file_arcname)
767
+
768
+ logger.info("Saved %s", display_path(archive_path))
769
+
770
+ def install(
771
+ self,
772
+ global_options: Optional[Sequence[str]] = None,
773
+ root: Optional[str] = None,
774
+ home: Optional[str] = None,
775
+ prefix: Optional[str] = None,
776
+ warn_script_location: bool = True,
777
+ use_user_site: bool = False,
778
+ pycompile: bool = True,
779
+ ) -> None:
780
+ scheme = get_scheme(
781
+ self.name,
782
+ user=use_user_site,
783
+ home=home,
784
+ root=root,
785
+ isolated=self.isolated,
786
+ prefix=prefix,
787
+ )
788
+
789
+ if self.editable and not self.is_wheel:
790
+ install_editable_legacy(
791
+ global_options=global_options if global_options is not None else [],
792
+ prefix=prefix,
793
+ home=home,
794
+ use_user_site=use_user_site,
795
+ name=self.name,
796
+ setup_py_path=self.setup_py_path,
797
+ isolated=self.isolated,
798
+ build_env=self.build_env,
799
+ unpacked_source_directory=self.unpacked_source_directory,
800
+ )
801
+ self.install_succeeded = True
802
+ return
803
+
804
+ assert self.is_wheel
805
+ assert self.local_file_path
806
+
807
+ install_wheel(
808
+ self.name,
809
+ self.local_file_path,
810
+ scheme=scheme,
811
+ req_description=str(self.req),
812
+ pycompile=pycompile,
813
+ warn_script_location=warn_script_location,
814
+ direct_url=self.download_info if self.is_direct else None,
815
+ requested=self.user_supplied,
816
+ )
817
+ self.install_succeeded = True
818
+
819
+
820
+ def check_invalid_constraint_type(req: InstallRequirement) -> str:
821
+ # Check for unsupported forms
822
+ problem = ""
823
+ if not req.name:
824
+ problem = "Unnamed requirements are not allowed as constraints"
825
+ elif req.editable:
826
+ problem = "Editable requirements are not allowed as constraints"
827
+ elif req.extras:
828
+ problem = "Constraints cannot have extras"
829
+
830
+ if problem:
831
+ deprecated(
832
+ reason=(
833
+ "Constraints are only allowed to take the form of a package "
834
+ "name and a version specifier. Other forms were originally "
835
+ "permitted as an accident of the implementation, but were "
836
+ "undocumented. The new implementation of the resolver no "
837
+ "longer supports these forms."
838
+ ),
839
+ replacement="replacing the constraint with a requirement",
840
+ # No plan yet for when the new resolver becomes default
841
+ gone_in=None,
842
+ issue=8210,
843
+ )
844
+
845
+ return problem
846
+
847
+
848
+ def _has_option(options: Values, reqs: List[InstallRequirement], option: str) -> bool:
849
+ if getattr(options, option, None):
850
+ return True
851
+ for req in reqs:
852
+ if getattr(req, option, None):
853
+ return True
854
+ return False
855
+
856
+
857
+ def check_legacy_setup_py_options(
858
+ options: Values,
859
+ reqs: List[InstallRequirement],
860
+ ) -> None:
861
+ has_build_options = _has_option(options, reqs, "build_options")
862
+ has_global_options = _has_option(options, reqs, "global_options")
863
+ if has_build_options or has_global_options:
864
+ deprecated(
865
+ reason="--build-option and --global-option are deprecated.",
866
+ issue=11859,
867
+ replacement="to use --config-settings",
868
+ gone_in="23.3",
869
+ )
870
+ logger.warning(
871
+ "Implying --no-binary=:all: due to the presence of "
872
+ "--build-option / --global-option. "
873
+ )
874
+ options.format_control.disallow_binaries()
.venv/Lib/site-packages/pip/_internal/req/req_set.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from collections import OrderedDict
3
+ from typing import Dict, List
4
+
5
+ from pip._vendor.packaging.specifiers import LegacySpecifier
6
+ from pip._vendor.packaging.utils import canonicalize_name
7
+ from pip._vendor.packaging.version import LegacyVersion
8
+
9
+ from pip._internal.req.req_install import InstallRequirement
10
+ from pip._internal.utils.deprecation import deprecated
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class RequirementSet:
16
+ def __init__(self, check_supported_wheels: bool = True) -> None:
17
+ """Create a RequirementSet."""
18
+
19
+ self.requirements: Dict[str, InstallRequirement] = OrderedDict()
20
+ self.check_supported_wheels = check_supported_wheels
21
+
22
+ self.unnamed_requirements: List[InstallRequirement] = []
23
+
24
+ def __str__(self) -> str:
25
+ requirements = sorted(
26
+ (req for req in self.requirements.values() if not req.comes_from),
27
+ key=lambda req: canonicalize_name(req.name or ""),
28
+ )
29
+ return " ".join(str(req.req) for req in requirements)
30
+
31
+ def __repr__(self) -> str:
32
+ requirements = sorted(
33
+ self.requirements.values(),
34
+ key=lambda req: canonicalize_name(req.name or ""),
35
+ )
36
+
37
+ format_string = "<{classname} object; {count} requirement(s): {reqs}>"
38
+ return format_string.format(
39
+ classname=self.__class__.__name__,
40
+ count=len(requirements),
41
+ reqs=", ".join(str(req.req) for req in requirements),
42
+ )
43
+
44
+ def add_unnamed_requirement(self, install_req: InstallRequirement) -> None:
45
+ assert not install_req.name
46
+ self.unnamed_requirements.append(install_req)
47
+
48
+ def add_named_requirement(self, install_req: InstallRequirement) -> None:
49
+ assert install_req.name
50
+
51
+ project_name = canonicalize_name(install_req.name)
52
+ self.requirements[project_name] = install_req
53
+
54
+ def has_requirement(self, name: str) -> bool:
55
+ project_name = canonicalize_name(name)
56
+
57
+ return (
58
+ project_name in self.requirements
59
+ and not self.requirements[project_name].constraint
60
+ )
61
+
62
+ def get_requirement(self, name: str) -> InstallRequirement:
63
+ project_name = canonicalize_name(name)
64
+
65
+ if project_name in self.requirements:
66
+ return self.requirements[project_name]
67
+
68
+ raise KeyError(f"No project with the name {name!r}")
69
+
70
+ @property
71
+ def all_requirements(self) -> List[InstallRequirement]:
72
+ return self.unnamed_requirements + list(self.requirements.values())
73
+
74
+ @property
75
+ def requirements_to_install(self) -> List[InstallRequirement]:
76
+ """Return the list of requirements that need to be installed.
77
+
78
+ TODO remove this property together with the legacy resolver, since the new
79
+ resolver only returns requirements that need to be installed.
80
+ """
81
+ return [
82
+ install_req
83
+ for install_req in self.all_requirements
84
+ if not install_req.constraint and not install_req.satisfied_by
85
+ ]
86
+
87
+ def warn_legacy_versions_and_specifiers(self) -> None:
88
+ for req in self.requirements_to_install:
89
+ version = req.get_dist().version
90
+ if isinstance(version, LegacyVersion):
91
+ deprecated(
92
+ reason=(
93
+ f"pip has selected the non standard version {version} "
94
+ f"of {req}. In the future this version will be "
95
+ f"ignored as it isn't standard compliant."
96
+ ),
97
+ replacement=(
98
+ "set or update constraints to select another version "
99
+ "or contact the package author to fix the version number"
100
+ ),
101
+ issue=12063,
102
+ gone_in="23.3",
103
+ )
104
+ for dep in req.get_dist().iter_dependencies():
105
+ if any(isinstance(spec, LegacySpecifier) for spec in dep.specifier):
106
+ deprecated(
107
+ reason=(
108
+ f"pip has selected {req} {version} which has non "
109
+ f"standard dependency specifier {dep}. "
110
+ f"In the future this version of {req} will be "
111
+ f"ignored as it isn't standard compliant."
112
+ ),
113
+ replacement=(
114
+ "set or update constraints to select another version "
115
+ "or contact the package author to fix the version number"
116
+ ),
117
+ issue=12063,
118
+ gone_in="23.3",
119
+ )
.venv/Lib/site-packages/pip/_internal/req/req_uninstall.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import os
3
+ import sys
4
+ import sysconfig
5
+ from importlib.util import cache_from_source
6
+ from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple
7
+
8
+ from pip._internal.exceptions import UninstallationError
9
+ from pip._internal.locations import get_bin_prefix, get_bin_user
10
+ from pip._internal.metadata import BaseDistribution
11
+ from pip._internal.utils.compat import WINDOWS
12
+ from pip._internal.utils.egg_link import egg_link_path_from_location
13
+ from pip._internal.utils.logging import getLogger, indent_log
14
+ from pip._internal.utils.misc import ask, normalize_path, renames, rmtree
15
+ from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory
16
+ from pip._internal.utils.virtualenv import running_under_virtualenv
17
+
18
+ logger = getLogger(__name__)
19
+
20
+
21
+ def _script_names(
22
+ bin_dir: str, script_name: str, is_gui: bool
23
+ ) -> Generator[str, None, None]:
24
+ """Create the fully qualified name of the files created by
25
+ {console,gui}_scripts for the given ``dist``.
26
+ Returns the list of file names
27
+ """
28
+ exe_name = os.path.join(bin_dir, script_name)
29
+ yield exe_name
30
+ if not WINDOWS:
31
+ return
32
+ yield f"{exe_name}.exe"
33
+ yield f"{exe_name}.exe.manifest"
34
+ if is_gui:
35
+ yield f"{exe_name}-script.pyw"
36
+ else:
37
+ yield f"{exe_name}-script.py"
38
+
39
+
40
+ def _unique(
41
+ fn: Callable[..., Generator[Any, None, None]]
42
+ ) -> Callable[..., Generator[Any, None, None]]:
43
+ @functools.wraps(fn)
44
+ def unique(*args: Any, **kw: Any) -> Generator[Any, None, None]:
45
+ seen: Set[Any] = set()
46
+ for item in fn(*args, **kw):
47
+ if item not in seen:
48
+ seen.add(item)
49
+ yield item
50
+
51
+ return unique
52
+
53
+
54
+ @_unique
55
+ def uninstallation_paths(dist: BaseDistribution) -> Generator[str, None, None]:
56
+ """
57
+ Yield all the uninstallation paths for dist based on RECORD-without-.py[co]
58
+
59
+ Yield paths to all the files in RECORD. For each .py file in RECORD, add
60
+ the .pyc and .pyo in the same directory.
61
+
62
+ UninstallPathSet.add() takes care of the __pycache__ .py[co].
63
+
64
+ If RECORD is not found, raises UninstallationError,
65
+ with possible information from the INSTALLER file.
66
+
67
+ https://packaging.python.org/specifications/recording-installed-packages/
68
+ """
69
+ location = dist.location
70
+ assert location is not None, "not installed"
71
+
72
+ entries = dist.iter_declared_entries()
73
+ if entries is None:
74
+ msg = "Cannot uninstall {dist}, RECORD file not found.".format(dist=dist)
75
+ installer = dist.installer
76
+ if not installer or installer == "pip":
77
+ dep = "{}=={}".format(dist.raw_name, dist.version)
78
+ msg += (
79
+ " You might be able to recover from this via: "
80
+ "'pip install --force-reinstall --no-deps {}'.".format(dep)
81
+ )
82
+ else:
83
+ msg += " Hint: The package was installed by {}.".format(installer)
84
+ raise UninstallationError(msg)
85
+
86
+ for entry in entries:
87
+ path = os.path.join(location, entry)
88
+ yield path
89
+ if path.endswith(".py"):
90
+ dn, fn = os.path.split(path)
91
+ base = fn[:-3]
92
+ path = os.path.join(dn, base + ".pyc")
93
+ yield path
94
+ path = os.path.join(dn, base + ".pyo")
95
+ yield path
96
+
97
+
98
+ def compact(paths: Iterable[str]) -> Set[str]:
99
+ """Compact a path set to contain the minimal number of paths
100
+ necessary to contain all paths in the set. If /a/path/ and
101
+ /a/path/to/a/file.txt are both in the set, leave only the
102
+ shorter path."""
103
+
104
+ sep = os.path.sep
105
+ short_paths: Set[str] = set()
106
+ for path in sorted(paths, key=len):
107
+ should_skip = any(
108
+ path.startswith(shortpath.rstrip("*"))
109
+ and path[len(shortpath.rstrip("*").rstrip(sep))] == sep
110
+ for shortpath in short_paths
111
+ )
112
+ if not should_skip:
113
+ short_paths.add(path)
114
+ return short_paths
115
+
116
+
117
+ def compress_for_rename(paths: Iterable[str]) -> Set[str]:
118
+ """Returns a set containing the paths that need to be renamed.
119
+
120
+ This set may include directories when the original sequence of paths
121
+ included every file on disk.
122
+ """
123
+ case_map = {os.path.normcase(p): p for p in paths}
124
+ remaining = set(case_map)
125
+ unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len)
126
+ wildcards: Set[str] = set()
127
+
128
+ def norm_join(*a: str) -> str:
129
+ return os.path.normcase(os.path.join(*a))
130
+
131
+ for root in unchecked:
132
+ if any(os.path.normcase(root).startswith(w) for w in wildcards):
133
+ # This directory has already been handled.
134
+ continue
135
+
136
+ all_files: Set[str] = set()
137
+ all_subdirs: Set[str] = set()
138
+ for dirname, subdirs, files in os.walk(root):
139
+ all_subdirs.update(norm_join(root, dirname, d) for d in subdirs)
140
+ all_files.update(norm_join(root, dirname, f) for f in files)
141
+ # If all the files we found are in our remaining set of files to
142
+ # remove, then remove them from the latter set and add a wildcard
143
+ # for the directory.
144
+ if not (all_files - remaining):
145
+ remaining.difference_update(all_files)
146
+ wildcards.add(root + os.sep)
147
+
148
+ return set(map(case_map.__getitem__, remaining)) | wildcards
149
+
150
+
151
+ def compress_for_output_listing(paths: Iterable[str]) -> Tuple[Set[str], Set[str]]:
152
+ """Returns a tuple of 2 sets of which paths to display to user
153
+
154
+ The first set contains paths that would be deleted. Files of a package
155
+ are not added and the top-level directory of the package has a '*' added
156
+ at the end - to signify that all it's contents are removed.
157
+
158
+ The second set contains files that would have been skipped in the above
159
+ folders.
160
+ """
161
+
162
+ will_remove = set(paths)
163
+ will_skip = set()
164
+
165
+ # Determine folders and files
166
+ folders = set()
167
+ files = set()
168
+ for path in will_remove:
169
+ if path.endswith(".pyc"):
170
+ continue
171
+ if path.endswith("__init__.py") or ".dist-info" in path:
172
+ folders.add(os.path.dirname(path))
173
+ files.add(path)
174
+
175
+ # probably this one https://github.com/python/mypy/issues/390
176
+ _normcased_files = set(map(os.path.normcase, files)) # type: ignore
177
+
178
+ folders = compact(folders)
179
+
180
+ # This walks the tree using os.walk to not miss extra folders
181
+ # that might get added.
182
+ for folder in folders:
183
+ for dirpath, _, dirfiles in os.walk(folder):
184
+ for fname in dirfiles:
185
+ if fname.endswith(".pyc"):
186
+ continue
187
+
188
+ file_ = os.path.join(dirpath, fname)
189
+ if (
190
+ os.path.isfile(file_)
191
+ and os.path.normcase(file_) not in _normcased_files
192
+ ):
193
+ # We are skipping this file. Add it to the set.
194
+ will_skip.add(file_)
195
+
196
+ will_remove = files | {os.path.join(folder, "*") for folder in folders}
197
+
198
+ return will_remove, will_skip
199
+
200
+
201
+ class StashedUninstallPathSet:
202
+ """A set of file rename operations to stash files while
203
+ tentatively uninstalling them."""
204
+
205
+ def __init__(self) -> None:
206
+ # Mapping from source file root to [Adjacent]TempDirectory
207
+ # for files under that directory.
208
+ self._save_dirs: Dict[str, TempDirectory] = {}
209
+ # (old path, new path) tuples for each move that may need
210
+ # to be undone.
211
+ self._moves: List[Tuple[str, str]] = []
212
+
213
+ def _get_directory_stash(self, path: str) -> str:
214
+ """Stashes a directory.
215
+
216
+ Directories are stashed adjacent to their original location if
217
+ possible, or else moved/copied into the user's temp dir."""
218
+
219
+ try:
220
+ save_dir: TempDirectory = AdjacentTempDirectory(path)
221
+ except OSError:
222
+ save_dir = TempDirectory(kind="uninstall")
223
+ self._save_dirs[os.path.normcase(path)] = save_dir
224
+
225
+ return save_dir.path
226
+
227
+ def _get_file_stash(self, path: str) -> str:
228
+ """Stashes a file.
229
+
230
+ If no root has been provided, one will be created for the directory
231
+ in the user's temp directory."""
232
+ path = os.path.normcase(path)
233
+ head, old_head = os.path.dirname(path), None
234
+ save_dir = None
235
+
236
+ while head != old_head:
237
+ try:
238
+ save_dir = self._save_dirs[head]
239
+ break
240
+ except KeyError:
241
+ pass
242
+ head, old_head = os.path.dirname(head), head
243
+ else:
244
+ # Did not find any suitable root
245
+ head = os.path.dirname(path)
246
+ save_dir = TempDirectory(kind="uninstall")
247
+ self._save_dirs[head] = save_dir
248
+
249
+ relpath = os.path.relpath(path, head)
250
+ if relpath and relpath != os.path.curdir:
251
+ return os.path.join(save_dir.path, relpath)
252
+ return save_dir.path
253
+
254
+ def stash(self, path: str) -> str:
255
+ """Stashes the directory or file and returns its new location.
256
+ Handle symlinks as files to avoid modifying the symlink targets.
257
+ """
258
+ path_is_dir = os.path.isdir(path) and not os.path.islink(path)
259
+ if path_is_dir:
260
+ new_path = self._get_directory_stash(path)
261
+ else:
262
+ new_path = self._get_file_stash(path)
263
+
264
+ self._moves.append((path, new_path))
265
+ if path_is_dir and os.path.isdir(new_path):
266
+ # If we're moving a directory, we need to
267
+ # remove the destination first or else it will be
268
+ # moved to inside the existing directory.
269
+ # We just created new_path ourselves, so it will
270
+ # be removable.
271
+ os.rmdir(new_path)
272
+ renames(path, new_path)
273
+ return new_path
274
+
275
+ def commit(self) -> None:
276
+ """Commits the uninstall by removing stashed files."""
277
+ for _, save_dir in self._save_dirs.items():
278
+ save_dir.cleanup()
279
+ self._moves = []
280
+ self._save_dirs = {}
281
+
282
+ def rollback(self) -> None:
283
+ """Undoes the uninstall by moving stashed files back."""
284
+ for p in self._moves:
285
+ logger.info("Moving to %s\n from %s", *p)
286
+
287
+ for new_path, path in self._moves:
288
+ try:
289
+ logger.debug("Replacing %s from %s", new_path, path)
290
+ if os.path.isfile(new_path) or os.path.islink(new_path):
291
+ os.unlink(new_path)
292
+ elif os.path.isdir(new_path):
293
+ rmtree(new_path)
294
+ renames(path, new_path)
295
+ except OSError as ex:
296
+ logger.error("Failed to restore %s", new_path)
297
+ logger.debug("Exception: %s", ex)
298
+
299
+ self.commit()
300
+
301
+ @property
302
+ def can_rollback(self) -> bool:
303
+ return bool(self._moves)
304
+
305
+
306
+ class UninstallPathSet:
307
+ """A set of file paths to be removed in the uninstallation of a
308
+ requirement."""
309
+
310
+ def __init__(self, dist: BaseDistribution) -> None:
311
+ self._paths: Set[str] = set()
312
+ self._refuse: Set[str] = set()
313
+ self._pth: Dict[str, UninstallPthEntries] = {}
314
+ self._dist = dist
315
+ self._moved_paths = StashedUninstallPathSet()
316
+ # Create local cache of normalize_path results. Creating an UninstallPathSet
317
+ # can result in hundreds/thousands of redundant calls to normalize_path with
318
+ # the same args, which hurts performance.
319
+ self._normalize_path_cached = functools.lru_cache()(normalize_path)
320
+
321
+ def _permitted(self, path: str) -> bool:
322
+ """
323
+ Return True if the given path is one we are permitted to
324
+ remove/modify, False otherwise.
325
+
326
+ """
327
+ # aka is_local, but caching normalized sys.prefix
328
+ if not running_under_virtualenv():
329
+ return True
330
+ return path.startswith(self._normalize_path_cached(sys.prefix))
331
+
332
+ def add(self, path: str) -> None:
333
+ head, tail = os.path.split(path)
334
+
335
+ # we normalize the head to resolve parent directory symlinks, but not
336
+ # the tail, since we only want to uninstall symlinks, not their targets
337
+ path = os.path.join(self._normalize_path_cached(head), os.path.normcase(tail))
338
+
339
+ if not os.path.exists(path):
340
+ return
341
+ if self._permitted(path):
342
+ self._paths.add(path)
343
+ else:
344
+ self._refuse.add(path)
345
+
346
+ # __pycache__ files can show up after 'installed-files.txt' is created,
347
+ # due to imports
348
+ if os.path.splitext(path)[1] == ".py":
349
+ self.add(cache_from_source(path))
350
+
351
+ def add_pth(self, pth_file: str, entry: str) -> None:
352
+ pth_file = self._normalize_path_cached(pth_file)
353
+ if self._permitted(pth_file):
354
+ if pth_file not in self._pth:
355
+ self._pth[pth_file] = UninstallPthEntries(pth_file)
356
+ self._pth[pth_file].add(entry)
357
+ else:
358
+ self._refuse.add(pth_file)
359
+
360
+ def remove(self, auto_confirm: bool = False, verbose: bool = False) -> None:
361
+ """Remove paths in ``self._paths`` with confirmation (unless
362
+ ``auto_confirm`` is True)."""
363
+
364
+ if not self._paths:
365
+ logger.info(
366
+ "Can't uninstall '%s'. No files were found to uninstall.",
367
+ self._dist.raw_name,
368
+ )
369
+ return
370
+
371
+ dist_name_version = f"{self._dist.raw_name}-{self._dist.version}"
372
+ logger.info("Uninstalling %s:", dist_name_version)
373
+
374
+ with indent_log():
375
+ if auto_confirm or self._allowed_to_proceed(verbose):
376
+ moved = self._moved_paths
377
+
378
+ for_rename = compress_for_rename(self._paths)
379
+
380
+ for path in sorted(compact(for_rename)):
381
+ moved.stash(path)
382
+ logger.verbose("Removing file or directory %s", path)
383
+
384
+ for pth in self._pth.values():
385
+ pth.remove()
386
+
387
+ logger.info("Successfully uninstalled %s", dist_name_version)
388
+
389
+ def _allowed_to_proceed(self, verbose: bool) -> bool:
390
+ """Display which files would be deleted and prompt for confirmation"""
391
+
392
+ def _display(msg: str, paths: Iterable[str]) -> None:
393
+ if not paths:
394
+ return
395
+
396
+ logger.info(msg)
397
+ with indent_log():
398
+ for path in sorted(compact(paths)):
399
+ logger.info(path)
400
+
401
+ if not verbose:
402
+ will_remove, will_skip = compress_for_output_listing(self._paths)
403
+ else:
404
+ # In verbose mode, display all the files that are going to be
405
+ # deleted.
406
+ will_remove = set(self._paths)
407
+ will_skip = set()
408
+
409
+ _display("Would remove:", will_remove)
410
+ _display("Would not remove (might be manually added):", will_skip)
411
+ _display("Would not remove (outside of prefix):", self._refuse)
412
+ if verbose:
413
+ _display("Will actually move:", compress_for_rename(self._paths))
414
+
415
+ return ask("Proceed (Y/n)? ", ("y", "n", "")) != "n"
416
+
417
+ def rollback(self) -> None:
418
+ """Rollback the changes previously made by remove()."""
419
+ if not self._moved_paths.can_rollback:
420
+ logger.error(
421
+ "Can't roll back %s; was not uninstalled",
422
+ self._dist.raw_name,
423
+ )
424
+ return
425
+ logger.info("Rolling back uninstall of %s", self._dist.raw_name)
426
+ self._moved_paths.rollback()
427
+ for pth in self._pth.values():
428
+ pth.rollback()
429
+
430
+ def commit(self) -> None:
431
+ """Remove temporary save dir: rollback will no longer be possible."""
432
+ self._moved_paths.commit()
433
+
434
+ @classmethod
435
+ def from_dist(cls, dist: BaseDistribution) -> "UninstallPathSet":
436
+ dist_location = dist.location
437
+ info_location = dist.info_location
438
+ if dist_location is None:
439
+ logger.info(
440
+ "Not uninstalling %s since it is not installed",
441
+ dist.canonical_name,
442
+ )
443
+ return cls(dist)
444
+
445
+ normalized_dist_location = normalize_path(dist_location)
446
+ if not dist.local:
447
+ logger.info(
448
+ "Not uninstalling %s at %s, outside environment %s",
449
+ dist.canonical_name,
450
+ normalized_dist_location,
451
+ sys.prefix,
452
+ )
453
+ return cls(dist)
454
+
455
+ if normalized_dist_location in {
456
+ p
457
+ for p in {sysconfig.get_path("stdlib"), sysconfig.get_path("platstdlib")}
458
+ if p
459
+ }:
460
+ logger.info(
461
+ "Not uninstalling %s at %s, as it is in the standard library.",
462
+ dist.canonical_name,
463
+ normalized_dist_location,
464
+ )
465
+ return cls(dist)
466
+
467
+ paths_to_remove = cls(dist)
468
+ develop_egg_link = egg_link_path_from_location(dist.raw_name)
469
+
470
+ # Distribution is installed with metadata in a "flat" .egg-info
471
+ # directory. This means it is not a modern .dist-info installation, an
472
+ # egg, or legacy editable.
473
+ setuptools_flat_installation = (
474
+ dist.installed_with_setuptools_egg_info
475
+ and info_location is not None
476
+ and os.path.exists(info_location)
477
+ # If dist is editable and the location points to a ``.egg-info``,
478
+ # we are in fact in the legacy editable case.
479
+ and not info_location.endswith(f"{dist.setuptools_filename}.egg-info")
480
+ )
481
+
482
+ # Uninstall cases order do matter as in the case of 2 installs of the
483
+ # same package, pip needs to uninstall the currently detected version
484
+ if setuptools_flat_installation:
485
+ if info_location is not None:
486
+ paths_to_remove.add(info_location)
487
+ installed_files = dist.iter_declared_entries()
488
+ if installed_files is not None:
489
+ for installed_file in installed_files:
490
+ paths_to_remove.add(os.path.join(dist_location, installed_file))
491
+ # FIXME: need a test for this elif block
492
+ # occurs with --single-version-externally-managed/--record outside
493
+ # of pip
494
+ elif dist.is_file("top_level.txt"):
495
+ try:
496
+ namespace_packages = dist.read_text("namespace_packages.txt")
497
+ except FileNotFoundError:
498
+ namespaces = []
499
+ else:
500
+ namespaces = namespace_packages.splitlines(keepends=False)
501
+ for top_level_pkg in [
502
+ p
503
+ for p in dist.read_text("top_level.txt").splitlines()
504
+ if p and p not in namespaces
505
+ ]:
506
+ path = os.path.join(dist_location, top_level_pkg)
507
+ paths_to_remove.add(path)
508
+ paths_to_remove.add(f"{path}.py")
509
+ paths_to_remove.add(f"{path}.pyc")
510
+ paths_to_remove.add(f"{path}.pyo")
511
+
512
+ elif dist.installed_by_distutils:
513
+ raise UninstallationError(
514
+ "Cannot uninstall {!r}. It is a distutils installed project "
515
+ "and thus we cannot accurately determine which files belong "
516
+ "to it which would lead to only a partial uninstall.".format(
517
+ dist.raw_name,
518
+ )
519
+ )
520
+
521
+ elif dist.installed_as_egg:
522
+ # package installed by easy_install
523
+ # We cannot match on dist.egg_name because it can slightly vary
524
+ # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg
525
+ paths_to_remove.add(dist_location)
526
+ easy_install_egg = os.path.split(dist_location)[1]
527
+ easy_install_pth = os.path.join(
528
+ os.path.dirname(dist_location),
529
+ "easy-install.pth",
530
+ )
531
+ paths_to_remove.add_pth(easy_install_pth, "./" + easy_install_egg)
532
+
533
+ elif dist.installed_with_dist_info:
534
+ for path in uninstallation_paths(dist):
535
+ paths_to_remove.add(path)
536
+
537
+ elif develop_egg_link:
538
+ # PEP 660 modern editable is handled in the ``.dist-info`` case
539
+ # above, so this only covers the setuptools-style editable.
540
+ with open(develop_egg_link) as fh:
541
+ link_pointer = os.path.normcase(fh.readline().strip())
542
+ normalized_link_pointer = paths_to_remove._normalize_path_cached(
543
+ link_pointer
544
+ )
545
+ assert os.path.samefile(
546
+ normalized_link_pointer, normalized_dist_location
547
+ ), (
548
+ f"Egg-link {develop_egg_link} (to {link_pointer}) does not match "
549
+ f"installed location of {dist.raw_name} (at {dist_location})"
550
+ )
551
+ paths_to_remove.add(develop_egg_link)
552
+ easy_install_pth = os.path.join(
553
+ os.path.dirname(develop_egg_link), "easy-install.pth"
554
+ )
555
+ paths_to_remove.add_pth(easy_install_pth, dist_location)
556
+
557
+ else:
558
+ logger.debug(
559
+ "Not sure how to uninstall: %s - Check: %s",
560
+ dist,
561
+ dist_location,
562
+ )
563
+
564
+ if dist.in_usersite:
565
+ bin_dir = get_bin_user()
566
+ else:
567
+ bin_dir = get_bin_prefix()
568
+
569
+ # find distutils scripts= scripts
570
+ try:
571
+ for script in dist.iter_distutils_script_names():
572
+ paths_to_remove.add(os.path.join(bin_dir, script))
573
+ if WINDOWS:
574
+ paths_to_remove.add(os.path.join(bin_dir, f"{script}.bat"))
575
+ except (FileNotFoundError, NotADirectoryError):
576
+ pass
577
+
578
+ # find console_scripts and gui_scripts
579
+ def iter_scripts_to_remove(
580
+ dist: BaseDistribution,
581
+ bin_dir: str,
582
+ ) -> Generator[str, None, None]:
583
+ for entry_point in dist.iter_entry_points():
584
+ if entry_point.group == "console_scripts":
585
+ yield from _script_names(bin_dir, entry_point.name, False)
586
+ elif entry_point.group == "gui_scripts":
587
+ yield from _script_names(bin_dir, entry_point.name, True)
588
+
589
+ for s in iter_scripts_to_remove(dist, bin_dir):
590
+ paths_to_remove.add(s)
591
+
592
+ return paths_to_remove
593
+
594
+
595
+ class UninstallPthEntries:
596
+ def __init__(self, pth_file: str) -> None:
597
+ self.file = pth_file
598
+ self.entries: Set[str] = set()
599
+ self._saved_lines: Optional[List[bytes]] = None
600
+
601
+ def add(self, entry: str) -> None:
602
+ entry = os.path.normcase(entry)
603
+ # On Windows, os.path.normcase converts the entry to use
604
+ # backslashes. This is correct for entries that describe absolute
605
+ # paths outside of site-packages, but all the others use forward
606
+ # slashes.
607
+ # os.path.splitdrive is used instead of os.path.isabs because isabs
608
+ # treats non-absolute paths with drive letter markings like c:foo\bar
609
+ # as absolute paths. It also does not recognize UNC paths if they don't
610
+ # have more than "\\sever\share". Valid examples: "\\server\share\" or
611
+ # "\\server\share\folder".
612
+ if WINDOWS and not os.path.splitdrive(entry)[0]:
613
+ entry = entry.replace("\\", "/")
614
+ self.entries.add(entry)
615
+
616
+ def remove(self) -> None:
617
+ logger.verbose("Removing pth entries from %s:", self.file)
618
+
619
+ # If the file doesn't exist, log a warning and return
620
+ if not os.path.isfile(self.file):
621
+ logger.warning("Cannot remove entries from nonexistent file %s", self.file)
622
+ return
623
+ with open(self.file, "rb") as fh:
624
+ # windows uses '\r\n' with py3k, but uses '\n' with py2.x
625
+ lines = fh.readlines()
626
+ self._saved_lines = lines
627
+ if any(b"\r\n" in line for line in lines):
628
+ endline = "\r\n"
629
+ else:
630
+ endline = "\n"
631
+ # handle missing trailing newline
632
+ if lines and not lines[-1].endswith(endline.encode("utf-8")):
633
+ lines[-1] = lines[-1] + endline.encode("utf-8")
634
+ for entry in self.entries:
635
+ try:
636
+ logger.verbose("Removing entry: %s", entry)
637
+ lines.remove((entry + endline).encode("utf-8"))
638
+ except ValueError:
639
+ pass
640
+ with open(self.file, "wb") as fh:
641
+ fh.writelines(lines)
642
+
643
+ def rollback(self) -> bool:
644
+ if self._saved_lines is None:
645
+ logger.error("Cannot roll back changes to %s, none were made", self.file)
646
+ return False
647
+ logger.debug("Rolling %s back to previous state", self.file)
648
+ with open(self.file, "wb") as fh:
649
+ fh.writelines(self._saved_lines)
650
+ return True
.venv/Lib/site-packages/pip/_internal/resolution/__init__.py ADDED
File without changes
.venv/Lib/site-packages/pip/_internal/resolution/base.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional
2
+
3
+ from pip._internal.req.req_install import InstallRequirement
4
+ from pip._internal.req.req_set import RequirementSet
5
+
6
+ InstallRequirementProvider = Callable[
7
+ [str, Optional[InstallRequirement]], InstallRequirement
8
+ ]
9
+
10
+
11
+ class BaseResolver:
12
+ def resolve(
13
+ self, root_reqs: List[InstallRequirement], check_supported_wheels: bool
14
+ ) -> RequirementSet:
15
+ raise NotImplementedError()
16
+
17
+ def get_installation_order(
18
+ self, req_set: RequirementSet
19
+ ) -> List[InstallRequirement]:
20
+ raise NotImplementedError()
.venv/Lib/site-packages/pip/_internal/resolution/legacy/__init__.py ADDED
File without changes
.venv/Lib/site-packages/pip/_internal/resolution/legacy/resolver.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dependency Resolution
2
+
3
+ The dependency resolution in pip is performed as follows:
4
+
5
+ for top-level requirements:
6
+ a. only one spec allowed per project, regardless of conflicts or not.
7
+ otherwise a "double requirement" exception is raised
8
+ b. they override sub-dependency requirements.
9
+ for sub-dependencies
10
+ a. "first found, wins" (where the order is breadth first)
11
+ """
12
+
13
+ # The following comment should be removed at some point in the future.
14
+ # mypy: strict-optional=False
15
+
16
+ import logging
17
+ import sys
18
+ from collections import defaultdict
19
+ from itertools import chain
20
+ from typing import DefaultDict, Iterable, List, Optional, Set, Tuple
21
+
22
+ from pip._vendor.packaging import specifiers
23
+ from pip._vendor.packaging.requirements import Requirement
24
+
25
+ from pip._internal.cache import WheelCache
26
+ from pip._internal.exceptions import (
27
+ BestVersionAlreadyInstalled,
28
+ DistributionNotFound,
29
+ HashError,
30
+ HashErrors,
31
+ InstallationError,
32
+ NoneMetadataError,
33
+ UnsupportedPythonVersion,
34
+ )
35
+ from pip._internal.index.package_finder import PackageFinder
36
+ from pip._internal.metadata import BaseDistribution
37
+ from pip._internal.models.link import Link
38
+ from pip._internal.models.wheel import Wheel
39
+ from pip._internal.operations.prepare import RequirementPreparer
40
+ from pip._internal.req.req_install import (
41
+ InstallRequirement,
42
+ check_invalid_constraint_type,
43
+ )
44
+ from pip._internal.req.req_set import RequirementSet
45
+ from pip._internal.resolution.base import BaseResolver, InstallRequirementProvider
46
+ from pip._internal.utils import compatibility_tags
47
+ from pip._internal.utils.compatibility_tags import get_supported
48
+ from pip._internal.utils.direct_url_helpers import direct_url_from_link
49
+ from pip._internal.utils.logging import indent_log
50
+ from pip._internal.utils.misc import normalize_version_info
51
+ from pip._internal.utils.packaging import check_requires_python
52
+
53
+ logger = logging.getLogger(__name__)
54
+
55
+ DiscoveredDependencies = DefaultDict[str, List[InstallRequirement]]
56
+
57
+
58
+ def _check_dist_requires_python(
59
+ dist: BaseDistribution,
60
+ version_info: Tuple[int, int, int],
61
+ ignore_requires_python: bool = False,
62
+ ) -> None:
63
+ """
64
+ Check whether the given Python version is compatible with a distribution's
65
+ "Requires-Python" value.
66
+
67
+ :param version_info: A 3-tuple of ints representing the Python
68
+ major-minor-micro version to check.
69
+ :param ignore_requires_python: Whether to ignore the "Requires-Python"
70
+ value if the given Python version isn't compatible.
71
+
72
+ :raises UnsupportedPythonVersion: When the given Python version isn't
73
+ compatible.
74
+ """
75
+ # This idiosyncratically converts the SpecifierSet to str and let
76
+ # check_requires_python then parse it again into SpecifierSet. But this
77
+ # is the legacy resolver so I'm just not going to bother refactoring.
78
+ try:
79
+ requires_python = str(dist.requires_python)
80
+ except FileNotFoundError as e:
81
+ raise NoneMetadataError(dist, str(e))
82
+ try:
83
+ is_compatible = check_requires_python(
84
+ requires_python,
85
+ version_info=version_info,
86
+ )
87
+ except specifiers.InvalidSpecifier as exc:
88
+ logger.warning(
89
+ "Package %r has an invalid Requires-Python: %s", dist.raw_name, exc
90
+ )
91
+ return
92
+
93
+ if is_compatible:
94
+ return
95
+
96
+ version = ".".join(map(str, version_info))
97
+ if ignore_requires_python:
98
+ logger.debug(
99
+ "Ignoring failed Requires-Python check for package %r: %s not in %r",
100
+ dist.raw_name,
101
+ version,
102
+ requires_python,
103
+ )
104
+ return
105
+
106
+ raise UnsupportedPythonVersion(
107
+ "Package {!r} requires a different Python: {} not in {!r}".format(
108
+ dist.raw_name, version, requires_python
109
+ )
110
+ )
111
+
112
+
113
+ class Resolver(BaseResolver):
114
+ """Resolves which packages need to be installed/uninstalled to perform \
115
+ the requested operation without breaking the requirements of any package.
116
+ """
117
+
118
+ _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
119
+
120
+ def __init__(
121
+ self,
122
+ preparer: RequirementPreparer,
123
+ finder: PackageFinder,
124
+ wheel_cache: Optional[WheelCache],
125
+ make_install_req: InstallRequirementProvider,
126
+ use_user_site: bool,
127
+ ignore_dependencies: bool,
128
+ ignore_installed: bool,
129
+ ignore_requires_python: bool,
130
+ force_reinstall: bool,
131
+ upgrade_strategy: str,
132
+ py_version_info: Optional[Tuple[int, ...]] = None,
133
+ ) -> None:
134
+ super().__init__()
135
+ assert upgrade_strategy in self._allowed_strategies
136
+
137
+ if py_version_info is None:
138
+ py_version_info = sys.version_info[:3]
139
+ else:
140
+ py_version_info = normalize_version_info(py_version_info)
141
+
142
+ self._py_version_info = py_version_info
143
+
144
+ self.preparer = preparer
145
+ self.finder = finder
146
+ self.wheel_cache = wheel_cache
147
+
148
+ self.upgrade_strategy = upgrade_strategy
149
+ self.force_reinstall = force_reinstall
150
+ self.ignore_dependencies = ignore_dependencies
151
+ self.ignore_installed = ignore_installed
152
+ self.ignore_requires_python = ignore_requires_python
153
+ self.use_user_site = use_user_site
154
+ self._make_install_req = make_install_req
155
+
156
+ self._discovered_dependencies: DiscoveredDependencies = defaultdict(list)
157
+
158
+ def resolve(
159
+ self, root_reqs: List[InstallRequirement], check_supported_wheels: bool
160
+ ) -> RequirementSet:
161
+ """Resolve what operations need to be done
162
+
163
+ As a side-effect of this method, the packages (and their dependencies)
164
+ are downloaded, unpacked and prepared for installation. This
165
+ preparation is done by ``pip.operations.prepare``.
166
+
167
+ Once PyPI has static dependency metadata available, it would be
168
+ possible to move the preparation to become a step separated from
169
+ dependency resolution.
170
+ """
171
+ requirement_set = RequirementSet(check_supported_wheels=check_supported_wheels)
172
+ for req in root_reqs:
173
+ if req.constraint:
174
+ check_invalid_constraint_type(req)
175
+ self._add_requirement_to_set(requirement_set, req)
176
+
177
+ # Actually prepare the files, and collect any exceptions. Most hash
178
+ # exceptions cannot be checked ahead of time, because
179
+ # _populate_link() needs to be called before we can make decisions
180
+ # based on link type.
181
+ discovered_reqs: List[InstallRequirement] = []
182
+ hash_errors = HashErrors()
183
+ for req in chain(requirement_set.all_requirements, discovered_reqs):
184
+ try:
185
+ discovered_reqs.extend(self._resolve_one(requirement_set, req))
186
+ except HashError as exc:
187
+ exc.req = req
188
+ hash_errors.append(exc)
189
+
190
+ if hash_errors:
191
+ raise hash_errors
192
+
193
+ return requirement_set
194
+
195
+ def _add_requirement_to_set(
196
+ self,
197
+ requirement_set: RequirementSet,
198
+ install_req: InstallRequirement,
199
+ parent_req_name: Optional[str] = None,
200
+ extras_requested: Optional[Iterable[str]] = None,
201
+ ) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]]:
202
+ """Add install_req as a requirement to install.
203
+
204
+ :param parent_req_name: The name of the requirement that needed this
205
+ added. The name is used because when multiple unnamed requirements
206
+ resolve to the same name, we could otherwise end up with dependency
207
+ links that point outside the Requirements set. parent_req must
208
+ already be added. Note that None implies that this is a user
209
+ supplied requirement, vs an inferred one.
210
+ :param extras_requested: an iterable of extras used to evaluate the
211
+ environment markers.
212
+ :return: Additional requirements to scan. That is either [] if
213
+ the requirement is not applicable, or [install_req] if the
214
+ requirement is applicable and has just been added.
215
+ """
216
+ # If the markers do not match, ignore this requirement.
217
+ if not install_req.match_markers(extras_requested):
218
+ logger.info(
219
+ "Ignoring %s: markers '%s' don't match your environment",
220
+ install_req.name,
221
+ install_req.markers,
222
+ )
223
+ return [], None
224
+
225
+ # If the wheel is not supported, raise an error.
226
+ # Should check this after filtering out based on environment markers to
227
+ # allow specifying different wheels based on the environment/OS, in a
228
+ # single requirements file.
229
+ if install_req.link and install_req.link.is_wheel:
230
+ wheel = Wheel(install_req.link.filename)
231
+ tags = compatibility_tags.get_supported()
232
+ if requirement_set.check_supported_wheels and not wheel.supported(tags):
233
+ raise InstallationError(
234
+ "{} is not a supported wheel on this platform.".format(
235
+ wheel.filename
236
+ )
237
+ )
238
+
239
+ # This next bit is really a sanity check.
240
+ assert (
241
+ not install_req.user_supplied or parent_req_name is None
242
+ ), "a user supplied req shouldn't have a parent"
243
+
244
+ # Unnamed requirements are scanned again and the requirement won't be
245
+ # added as a dependency until after scanning.
246
+ if not install_req.name:
247
+ requirement_set.add_unnamed_requirement(install_req)
248
+ return [install_req], None
249
+
250
+ try:
251
+ existing_req: Optional[
252
+ InstallRequirement
253
+ ] = requirement_set.get_requirement(install_req.name)
254
+ except KeyError:
255
+ existing_req = None
256
+
257
+ has_conflicting_requirement = (
258
+ parent_req_name is None
259
+ and existing_req
260
+ and not existing_req.constraint
261
+ and existing_req.extras == install_req.extras
262
+ and existing_req.req
263
+ and install_req.req
264
+ and existing_req.req.specifier != install_req.req.specifier
265
+ )
266
+ if has_conflicting_requirement:
267
+ raise InstallationError(
268
+ "Double requirement given: {} (already in {}, name={!r})".format(
269
+ install_req, existing_req, install_req.name
270
+ )
271
+ )
272
+
273
+ # When no existing requirement exists, add the requirement as a
274
+ # dependency and it will be scanned again after.
275
+ if not existing_req:
276
+ requirement_set.add_named_requirement(install_req)
277
+ # We'd want to rescan this requirement later
278
+ return [install_req], install_req
279
+
280
+ # Assume there's no need to scan, and that we've already
281
+ # encountered this for scanning.
282
+ if install_req.constraint or not existing_req.constraint:
283
+ return [], existing_req
284
+
285
+ does_not_satisfy_constraint = install_req.link and not (
286
+ existing_req.link and install_req.link.path == existing_req.link.path
287
+ )
288
+ if does_not_satisfy_constraint:
289
+ raise InstallationError(
290
+ "Could not satisfy constraints for '{}': "
291
+ "installation from path or url cannot be "
292
+ "constrained to a version".format(install_req.name)
293
+ )
294
+ # If we're now installing a constraint, mark the existing
295
+ # object for real installation.
296
+ existing_req.constraint = False
297
+ # If we're now installing a user supplied requirement,
298
+ # mark the existing object as such.
299
+ if install_req.user_supplied:
300
+ existing_req.user_supplied = True
301
+ existing_req.extras = tuple(
302
+ sorted(set(existing_req.extras) | set(install_req.extras))
303
+ )
304
+ logger.debug(
305
+ "Setting %s extras to: %s",
306
+ existing_req,
307
+ existing_req.extras,
308
+ )
309
+ # Return the existing requirement for addition to the parent and
310
+ # scanning again.
311
+ return [existing_req], existing_req
312
+
313
+ def _is_upgrade_allowed(self, req: InstallRequirement) -> bool:
314
+ if self.upgrade_strategy == "to-satisfy-only":
315
+ return False
316
+ elif self.upgrade_strategy == "eager":
317
+ return True
318
+ else:
319
+ assert self.upgrade_strategy == "only-if-needed"
320
+ return req.user_supplied or req.constraint
321
+
322
+ def _set_req_to_reinstall(self, req: InstallRequirement) -> None:
323
+ """
324
+ Set a requirement to be installed.
325
+ """
326
+ # Don't uninstall the conflict if doing a user install and the
327
+ # conflict is not a user install.
328
+ if not self.use_user_site or req.satisfied_by.in_usersite:
329
+ req.should_reinstall = True
330
+ req.satisfied_by = None
331
+
332
+ def _check_skip_installed(
333
+ self, req_to_install: InstallRequirement
334
+ ) -> Optional[str]:
335
+ """Check if req_to_install should be skipped.
336
+
337
+ This will check if the req is installed, and whether we should upgrade
338
+ or reinstall it, taking into account all the relevant user options.
339
+
340
+ After calling this req_to_install will only have satisfied_by set to
341
+ None if the req_to_install is to be upgraded/reinstalled etc. Any
342
+ other value will be a dist recording the current thing installed that
343
+ satisfies the requirement.
344
+
345
+ Note that for vcs urls and the like we can't assess skipping in this
346
+ routine - we simply identify that we need to pull the thing down,
347
+ then later on it is pulled down and introspected to assess upgrade/
348
+ reinstalls etc.
349
+
350
+ :return: A text reason for why it was skipped, or None.
351
+ """
352
+ if self.ignore_installed:
353
+ return None
354
+
355
+ req_to_install.check_if_exists(self.use_user_site)
356
+ if not req_to_install.satisfied_by:
357
+ return None
358
+
359
+ if self.force_reinstall:
360
+ self._set_req_to_reinstall(req_to_install)
361
+ return None
362
+
363
+ if not self._is_upgrade_allowed(req_to_install):
364
+ if self.upgrade_strategy == "only-if-needed":
365
+ return "already satisfied, skipping upgrade"
366
+ return "already satisfied"
367
+
368
+ # Check for the possibility of an upgrade. For link-based
369
+ # requirements we have to pull the tree down and inspect to assess
370
+ # the version #, so it's handled way down.
371
+ if not req_to_install.link:
372
+ try:
373
+ self.finder.find_requirement(req_to_install, upgrade=True)
374
+ except BestVersionAlreadyInstalled:
375
+ # Then the best version is installed.
376
+ return "already up-to-date"
377
+ except DistributionNotFound:
378
+ # No distribution found, so we squash the error. It will
379
+ # be raised later when we re-try later to do the install.
380
+ # Why don't we just raise here?
381
+ pass
382
+
383
+ self._set_req_to_reinstall(req_to_install)
384
+ return None
385
+
386
+ def _find_requirement_link(self, req: InstallRequirement) -> Optional[Link]:
387
+ upgrade = self._is_upgrade_allowed(req)
388
+ best_candidate = self.finder.find_requirement(req, upgrade)
389
+ if not best_candidate:
390
+ return None
391
+
392
+ # Log a warning per PEP 592 if necessary before returning.
393
+ link = best_candidate.link
394
+ if link.is_yanked:
395
+ reason = link.yanked_reason or "<none given>"
396
+ msg = (
397
+ # Mark this as a unicode string to prevent
398
+ # "UnicodeEncodeError: 'ascii' codec can't encode character"
399
+ # in Python 2 when the reason contains non-ascii characters.
400
+ "The candidate selected for download or install is a "
401
+ "yanked version: {candidate}\n"
402
+ "Reason for being yanked: {reason}"
403
+ ).format(candidate=best_candidate, reason=reason)
404
+ logger.warning(msg)
405
+
406
+ return link
407
+
408
+ def _populate_link(self, req: InstallRequirement) -> None:
409
+ """Ensure that if a link can be found for this, that it is found.
410
+
411
+ Note that req.link may still be None - if the requirement is already
412
+ installed and not needed to be upgraded based on the return value of
413
+ _is_upgrade_allowed().
414
+
415
+ If preparer.require_hashes is True, don't use the wheel cache, because
416
+ cached wheels, always built locally, have different hashes than the
417
+ files downloaded from the index server and thus throw false hash
418
+ mismatches. Furthermore, cached wheels at present have undeterministic
419
+ contents due to file modification times.
420
+ """
421
+ if req.link is None:
422
+ req.link = self._find_requirement_link(req)
423
+
424
+ if self.wheel_cache is None or self.preparer.require_hashes:
425
+ return
426
+ cache_entry = self.wheel_cache.get_cache_entry(
427
+ link=req.link,
428
+ package_name=req.name,
429
+ supported_tags=get_supported(),
430
+ )
431
+ if cache_entry is not None:
432
+ logger.debug("Using cached wheel link: %s", cache_entry.link)
433
+ if req.link is req.original_link and cache_entry.persistent:
434
+ req.cached_wheel_source_link = req.link
435
+ if cache_entry.origin is not None:
436
+ req.download_info = cache_entry.origin
437
+ else:
438
+ # Legacy cache entry that does not have origin.json.
439
+ # download_info may miss the archive_info.hashes field.
440
+ req.download_info = direct_url_from_link(
441
+ req.link, link_is_in_wheel_cache=cache_entry.persistent
442
+ )
443
+ req.link = cache_entry.link
444
+
445
+ def _get_dist_for(self, req: InstallRequirement) -> BaseDistribution:
446
+ """Takes a InstallRequirement and returns a single AbstractDist \
447
+ representing a prepared variant of the same.
448
+ """
449
+ if req.editable:
450
+ return self.preparer.prepare_editable_requirement(req)
451
+
452
+ # satisfied_by is only evaluated by calling _check_skip_installed,
453
+ # so it must be None here.
454
+ assert req.satisfied_by is None
455
+ skip_reason = self._check_skip_installed(req)
456
+
457
+ if req.satisfied_by:
458
+ return self.preparer.prepare_installed_requirement(req, skip_reason)
459
+
460
+ # We eagerly populate the link, since that's our "legacy" behavior.
461
+ self._populate_link(req)
462
+ dist = self.preparer.prepare_linked_requirement(req)
463
+
464
+ # NOTE
465
+ # The following portion is for determining if a certain package is
466
+ # going to be re-installed/upgraded or not and reporting to the user.
467
+ # This should probably get cleaned up in a future refactor.
468
+
469
+ # req.req is only avail after unpack for URL
470
+ # pkgs repeat check_if_exists to uninstall-on-upgrade
471
+ # (#14)
472
+ if not self.ignore_installed:
473
+ req.check_if_exists(self.use_user_site)
474
+
475
+ if req.satisfied_by:
476
+ should_modify = (
477
+ self.upgrade_strategy != "to-satisfy-only"
478
+ or self.force_reinstall
479
+ or self.ignore_installed
480
+ or req.link.scheme == "file"
481
+ )
482
+ if should_modify:
483
+ self._set_req_to_reinstall(req)
484
+ else:
485
+ logger.info(
486
+ "Requirement already satisfied (use --upgrade to upgrade): %s",
487
+ req,
488
+ )
489
+ return dist
490
+
491
+ def _resolve_one(
492
+ self,
493
+ requirement_set: RequirementSet,
494
+ req_to_install: InstallRequirement,
495
+ ) -> List[InstallRequirement]:
496
+ """Prepare a single requirements file.
497
+
498
+ :return: A list of additional InstallRequirements to also install.
499
+ """
500
+ # Tell user what we are doing for this requirement:
501
+ # obtain (editable), skipping, processing (local url), collecting
502
+ # (remote url or package name)
503
+ if req_to_install.constraint or req_to_install.prepared:
504
+ return []
505
+
506
+ req_to_install.prepared = True
507
+
508
+ # Parse and return dependencies
509
+ dist = self._get_dist_for(req_to_install)
510
+ # This will raise UnsupportedPythonVersion if the given Python
511
+ # version isn't compatible with the distribution's Requires-Python.
512
+ _check_dist_requires_python(
513
+ dist,
514
+ version_info=self._py_version_info,
515
+ ignore_requires_python=self.ignore_requires_python,
516
+ )
517
+
518
+ more_reqs: List[InstallRequirement] = []
519
+
520
+ def add_req(subreq: Requirement, extras_requested: Iterable[str]) -> None:
521
+ # This idiosyncratically converts the Requirement to str and let
522
+ # make_install_req then parse it again into Requirement. But this is
523
+ # the legacy resolver so I'm just not going to bother refactoring.
524
+ sub_install_req = self._make_install_req(str(subreq), req_to_install)
525
+ parent_req_name = req_to_install.name
526
+ to_scan_again, add_to_parent = self._add_requirement_to_set(
527
+ requirement_set,
528
+ sub_install_req,
529
+ parent_req_name=parent_req_name,
530
+ extras_requested=extras_requested,
531
+ )
532
+ if parent_req_name and add_to_parent:
533
+ self._discovered_dependencies[parent_req_name].append(add_to_parent)
534
+ more_reqs.extend(to_scan_again)
535
+
536
+ with indent_log():
537
+ # We add req_to_install before its dependencies, so that we
538
+ # can refer to it when adding dependencies.
539
+ if not requirement_set.has_requirement(req_to_install.name):
540
+ # 'unnamed' requirements will get added here
541
+ # 'unnamed' requirements can only come from being directly
542
+ # provided by the user.
543
+ assert req_to_install.user_supplied
544
+ self._add_requirement_to_set(
545
+ requirement_set, req_to_install, parent_req_name=None
546
+ )
547
+
548
+ if not self.ignore_dependencies:
549
+ if req_to_install.extras:
550
+ logger.debug(
551
+ "Installing extra requirements: %r",
552
+ ",".join(req_to_install.extras),
553
+ )
554
+ missing_requested = sorted(
555
+ set(req_to_install.extras) - set(dist.iter_provided_extras())
556
+ )
557
+ for missing in missing_requested:
558
+ logger.warning(
559
+ "%s %s does not provide the extra '%s'",
560
+ dist.raw_name,
561
+ dist.version,
562
+ missing,
563
+ )
564
+
565
+ available_requested = sorted(
566
+ set(dist.iter_provided_extras()) & set(req_to_install.extras)
567
+ )
568
+ for subreq in dist.iter_dependencies(available_requested):
569
+ add_req(subreq, extras_requested=available_requested)
570
+
571
+ return more_reqs
572
+
573
+ def get_installation_order(
574
+ self, req_set: RequirementSet
575
+ ) -> List[InstallRequirement]:
576
+ """Create the installation order.
577
+
578
+ The installation order is topological - requirements are installed
579
+ before the requiring thing. We break cycles at an arbitrary point,
580
+ and make no other guarantees.
581
+ """
582
+ # The current implementation, which we may change at any point
583
+ # installs the user specified things in the order given, except when
584
+ # dependencies must come earlier to achieve topological order.
585
+ order = []
586
+ ordered_reqs: Set[InstallRequirement] = set()
587
+
588
+ def schedule(req: InstallRequirement) -> None:
589
+ if req.satisfied_by or req in ordered_reqs:
590
+ return
591
+ if req.constraint:
592
+ return
593
+ ordered_reqs.add(req)
594
+ for dep in self._discovered_dependencies[req.name]:
595
+ schedule(dep)
596
+ order.append(req)
597
+
598
+ for install_req in req_set.requirements.values():
599
+ schedule(install_req)
600
+ return order
.venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__init__.py ADDED
File without changes
.venv/Lib/site-packages/pip/_internal/resolution/resolvelib/base.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import FrozenSet, Iterable, Optional, Tuple, Union
2
+
3
+ from pip._vendor.packaging.specifiers import SpecifierSet
4
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
5
+ from pip._vendor.packaging.version import LegacyVersion, Version
6
+
7
+ from pip._internal.models.link import Link, links_equivalent
8
+ from pip._internal.req.req_install import InstallRequirement
9
+ from pip._internal.utils.hashes import Hashes
10
+
11
+ CandidateLookup = Tuple[Optional["Candidate"], Optional[InstallRequirement]]
12
+ CandidateVersion = Union[LegacyVersion, Version]
13
+
14
+
15
+ def format_name(project: str, extras: FrozenSet[str]) -> str:
16
+ if not extras:
17
+ return project
18
+ canonical_extras = sorted(canonicalize_name(e) for e in extras)
19
+ return "{}[{}]".format(project, ",".join(canonical_extras))
20
+
21
+
22
+ class Constraint:
23
+ def __init__(
24
+ self, specifier: SpecifierSet, hashes: Hashes, links: FrozenSet[Link]
25
+ ) -> None:
26
+ self.specifier = specifier
27
+ self.hashes = hashes
28
+ self.links = links
29
+
30
+ @classmethod
31
+ def empty(cls) -> "Constraint":
32
+ return Constraint(SpecifierSet(), Hashes(), frozenset())
33
+
34
+ @classmethod
35
+ def from_ireq(cls, ireq: InstallRequirement) -> "Constraint":
36
+ links = frozenset([ireq.link]) if ireq.link else frozenset()
37
+ return Constraint(ireq.specifier, ireq.hashes(trust_internet=False), links)
38
+
39
+ def __bool__(self) -> bool:
40
+ return bool(self.specifier) or bool(self.hashes) or bool(self.links)
41
+
42
+ def __and__(self, other: InstallRequirement) -> "Constraint":
43
+ if not isinstance(other, InstallRequirement):
44
+ return NotImplemented
45
+ specifier = self.specifier & other.specifier
46
+ hashes = self.hashes & other.hashes(trust_internet=False)
47
+ links = self.links
48
+ if other.link:
49
+ links = links.union([other.link])
50
+ return Constraint(specifier, hashes, links)
51
+
52
+ def is_satisfied_by(self, candidate: "Candidate") -> bool:
53
+ # Reject if there are any mismatched URL constraints on this package.
54
+ if self.links and not all(_match_link(link, candidate) for link in self.links):
55
+ return False
56
+ # We can safely always allow prereleases here since PackageFinder
57
+ # already implements the prerelease logic, and would have filtered out
58
+ # prerelease candidates if the user does not expect them.
59
+ return self.specifier.contains(candidate.version, prereleases=True)
60
+
61
+
62
+ class Requirement:
63
+ @property
64
+ def project_name(self) -> NormalizedName:
65
+ """The "project name" of a requirement.
66
+
67
+ This is different from ``name`` if this requirement contains extras,
68
+ in which case ``name`` would contain the ``[...]`` part, while this
69
+ refers to the name of the project.
70
+ """
71
+ raise NotImplementedError("Subclass should override")
72
+
73
+ @property
74
+ def name(self) -> str:
75
+ """The name identifying this requirement in the resolver.
76
+
77
+ This is different from ``project_name`` if this requirement contains
78
+ extras, where ``project_name`` would not contain the ``[...]`` part.
79
+ """
80
+ raise NotImplementedError("Subclass should override")
81
+
82
+ def is_satisfied_by(self, candidate: "Candidate") -> bool:
83
+ return False
84
+
85
+ def get_candidate_lookup(self) -> CandidateLookup:
86
+ raise NotImplementedError("Subclass should override")
87
+
88
+ def format_for_error(self) -> str:
89
+ raise NotImplementedError("Subclass should override")
90
+
91
+
92
+ def _match_link(link: Link, candidate: "Candidate") -> bool:
93
+ if candidate.source_link:
94
+ return links_equivalent(link, candidate.source_link)
95
+ return False
96
+
97
+
98
+ class Candidate:
99
+ @property
100
+ def project_name(self) -> NormalizedName:
101
+ """The "project name" of the candidate.
102
+
103
+ This is different from ``name`` if this candidate contains extras,
104
+ in which case ``name`` would contain the ``[...]`` part, while this
105
+ refers to the name of the project.
106
+ """
107
+ raise NotImplementedError("Override in subclass")
108
+
109
+ @property
110
+ def name(self) -> str:
111
+ """The name identifying this candidate in the resolver.
112
+
113
+ This is different from ``project_name`` if this candidate contains
114
+ extras, where ``project_name`` would not contain the ``[...]`` part.
115
+ """
116
+ raise NotImplementedError("Override in subclass")
117
+
118
+ @property
119
+ def version(self) -> CandidateVersion:
120
+ raise NotImplementedError("Override in subclass")
121
+
122
+ @property
123
+ def is_installed(self) -> bool:
124
+ raise NotImplementedError("Override in subclass")
125
+
126
+ @property
127
+ def is_editable(self) -> bool:
128
+ raise NotImplementedError("Override in subclass")
129
+
130
+ @property
131
+ def source_link(self) -> Optional[Link]:
132
+ raise NotImplementedError("Override in subclass")
133
+
134
+ def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
135
+ raise NotImplementedError("Override in subclass")
136
+
137
+ def get_install_requirement(self) -> Optional[InstallRequirement]:
138
+ raise NotImplementedError("Override in subclass")
139
+
140
+ def format_for_error(self) -> str:
141
+ raise NotImplementedError("Subclass should override")
.venv/Lib/site-packages/pip/_internal/resolution/resolvelib/candidates.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+ from typing import TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Tuple, Union, cast
4
+
5
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
6
+ from pip._vendor.packaging.version import Version
7
+
8
+ from pip._internal.exceptions import (
9
+ HashError,
10
+ InstallationSubprocessError,
11
+ MetadataInconsistent,
12
+ )
13
+ from pip._internal.metadata import BaseDistribution
14
+ from pip._internal.models.link import Link, links_equivalent
15
+ from pip._internal.models.wheel import Wheel
16
+ from pip._internal.req.constructors import (
17
+ install_req_from_editable,
18
+ install_req_from_line,
19
+ )
20
+ from pip._internal.req.req_install import InstallRequirement
21
+ from pip._internal.utils.direct_url_helpers import direct_url_from_link
22
+ from pip._internal.utils.misc import normalize_version_info
23
+
24
+ from .base import Candidate, CandidateVersion, Requirement, format_name
25
+
26
+ if TYPE_CHECKING:
27
+ from .factory import Factory
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ BaseCandidate = Union[
32
+ "AlreadyInstalledCandidate",
33
+ "EditableCandidate",
34
+ "LinkCandidate",
35
+ ]
36
+
37
+ # Avoid conflicting with the PyPI package "Python".
38
+ REQUIRES_PYTHON_IDENTIFIER = cast(NormalizedName, "<Python from Requires-Python>")
39
+
40
+
41
+ def as_base_candidate(candidate: Candidate) -> Optional[BaseCandidate]:
42
+ """The runtime version of BaseCandidate."""
43
+ base_candidate_classes = (
44
+ AlreadyInstalledCandidate,
45
+ EditableCandidate,
46
+ LinkCandidate,
47
+ )
48
+ if isinstance(candidate, base_candidate_classes):
49
+ return candidate
50
+ return None
51
+
52
+
53
+ def make_install_req_from_link(
54
+ link: Link, template: InstallRequirement
55
+ ) -> InstallRequirement:
56
+ assert not template.editable, "template is editable"
57
+ if template.req:
58
+ line = str(template.req)
59
+ else:
60
+ line = link.url
61
+ ireq = install_req_from_line(
62
+ line,
63
+ user_supplied=template.user_supplied,
64
+ comes_from=template.comes_from,
65
+ use_pep517=template.use_pep517,
66
+ isolated=template.isolated,
67
+ constraint=template.constraint,
68
+ global_options=template.global_options,
69
+ hash_options=template.hash_options,
70
+ config_settings=template.config_settings,
71
+ )
72
+ ireq.original_link = template.original_link
73
+ ireq.link = link
74
+ ireq.extras = template.extras
75
+ return ireq
76
+
77
+
78
+ def make_install_req_from_editable(
79
+ link: Link, template: InstallRequirement
80
+ ) -> InstallRequirement:
81
+ assert template.editable, "template not editable"
82
+ ireq = install_req_from_editable(
83
+ link.url,
84
+ user_supplied=template.user_supplied,
85
+ comes_from=template.comes_from,
86
+ use_pep517=template.use_pep517,
87
+ isolated=template.isolated,
88
+ constraint=template.constraint,
89
+ permit_editable_wheels=template.permit_editable_wheels,
90
+ global_options=template.global_options,
91
+ hash_options=template.hash_options,
92
+ config_settings=template.config_settings,
93
+ )
94
+ ireq.extras = template.extras
95
+ return ireq
96
+
97
+
98
+ def _make_install_req_from_dist(
99
+ dist: BaseDistribution, template: InstallRequirement
100
+ ) -> InstallRequirement:
101
+ if template.req:
102
+ line = str(template.req)
103
+ elif template.link:
104
+ line = f"{dist.canonical_name} @ {template.link.url}"
105
+ else:
106
+ line = f"{dist.canonical_name}=={dist.version}"
107
+ ireq = install_req_from_line(
108
+ line,
109
+ user_supplied=template.user_supplied,
110
+ comes_from=template.comes_from,
111
+ use_pep517=template.use_pep517,
112
+ isolated=template.isolated,
113
+ constraint=template.constraint,
114
+ global_options=template.global_options,
115
+ hash_options=template.hash_options,
116
+ config_settings=template.config_settings,
117
+ )
118
+ ireq.satisfied_by = dist
119
+ return ireq
120
+
121
+
122
+ class _InstallRequirementBackedCandidate(Candidate):
123
+ """A candidate backed by an ``InstallRequirement``.
124
+
125
+ This represents a package request with the target not being already
126
+ in the environment, and needs to be fetched and installed. The backing
127
+ ``InstallRequirement`` is responsible for most of the leg work; this
128
+ class exposes appropriate information to the resolver.
129
+
130
+ :param link: The link passed to the ``InstallRequirement``. The backing
131
+ ``InstallRequirement`` will use this link to fetch the distribution.
132
+ :param source_link: The link this candidate "originates" from. This is
133
+ different from ``link`` when the link is found in the wheel cache.
134
+ ``link`` would point to the wheel cache, while this points to the
135
+ found remote link (e.g. from pypi.org).
136
+ """
137
+
138
+ dist: BaseDistribution
139
+ is_installed = False
140
+
141
+ def __init__(
142
+ self,
143
+ link: Link,
144
+ source_link: Link,
145
+ ireq: InstallRequirement,
146
+ factory: "Factory",
147
+ name: Optional[NormalizedName] = None,
148
+ version: Optional[CandidateVersion] = None,
149
+ ) -> None:
150
+ self._link = link
151
+ self._source_link = source_link
152
+ self._factory = factory
153
+ self._ireq = ireq
154
+ self._name = name
155
+ self._version = version
156
+ self.dist = self._prepare()
157
+
158
+ def __str__(self) -> str:
159
+ return f"{self.name} {self.version}"
160
+
161
+ def __repr__(self) -> str:
162
+ return "{class_name}({link!r})".format(
163
+ class_name=self.__class__.__name__,
164
+ link=str(self._link),
165
+ )
166
+
167
+ def __hash__(self) -> int:
168
+ return hash((self.__class__, self._link))
169
+
170
+ def __eq__(self, other: Any) -> bool:
171
+ if isinstance(other, self.__class__):
172
+ return links_equivalent(self._link, other._link)
173
+ return False
174
+
175
+ @property
176
+ def source_link(self) -> Optional[Link]:
177
+ return self._source_link
178
+
179
+ @property
180
+ def project_name(self) -> NormalizedName:
181
+ """The normalised name of the project the candidate refers to"""
182
+ if self._name is None:
183
+ self._name = self.dist.canonical_name
184
+ return self._name
185
+
186
+ @property
187
+ def name(self) -> str:
188
+ return self.project_name
189
+
190
+ @property
191
+ def version(self) -> CandidateVersion:
192
+ if self._version is None:
193
+ self._version = self.dist.version
194
+ return self._version
195
+
196
+ def format_for_error(self) -> str:
197
+ return "{} {} (from {})".format(
198
+ self.name,
199
+ self.version,
200
+ self._link.file_path if self._link.is_file else self._link,
201
+ )
202
+
203
+ def _prepare_distribution(self) -> BaseDistribution:
204
+ raise NotImplementedError("Override in subclass")
205
+
206
+ def _check_metadata_consistency(self, dist: BaseDistribution) -> None:
207
+ """Check for consistency of project name and version of dist."""
208
+ if self._name is not None and self._name != dist.canonical_name:
209
+ raise MetadataInconsistent(
210
+ self._ireq,
211
+ "name",
212
+ self._name,
213
+ dist.canonical_name,
214
+ )
215
+ if self._version is not None and self._version != dist.version:
216
+ raise MetadataInconsistent(
217
+ self._ireq,
218
+ "version",
219
+ str(self._version),
220
+ str(dist.version),
221
+ )
222
+
223
+ def _prepare(self) -> BaseDistribution:
224
+ try:
225
+ dist = self._prepare_distribution()
226
+ except HashError as e:
227
+ # Provide HashError the underlying ireq that caused it. This
228
+ # provides context for the resulting error message to show the
229
+ # offending line to the user.
230
+ e.req = self._ireq
231
+ raise
232
+ except InstallationSubprocessError as exc:
233
+ # The output has been presented already, so don't duplicate it.
234
+ exc.context = "See above for output."
235
+ raise
236
+
237
+ self._check_metadata_consistency(dist)
238
+ return dist
239
+
240
+ def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
241
+ requires = self.dist.iter_dependencies() if with_requires else ()
242
+ for r in requires:
243
+ yield self._factory.make_requirement_from_spec(str(r), self._ireq)
244
+ yield self._factory.make_requires_python_requirement(self.dist.requires_python)
245
+
246
+ def get_install_requirement(self) -> Optional[InstallRequirement]:
247
+ return self._ireq
248
+
249
+
250
+ class LinkCandidate(_InstallRequirementBackedCandidate):
251
+ is_editable = False
252
+
253
+ def __init__(
254
+ self,
255
+ link: Link,
256
+ template: InstallRequirement,
257
+ factory: "Factory",
258
+ name: Optional[NormalizedName] = None,
259
+ version: Optional[CandidateVersion] = None,
260
+ ) -> None:
261
+ source_link = link
262
+ cache_entry = factory.get_wheel_cache_entry(source_link, name)
263
+ if cache_entry is not None:
264
+ logger.debug("Using cached wheel link: %s", cache_entry.link)
265
+ link = cache_entry.link
266
+ ireq = make_install_req_from_link(link, template)
267
+ assert ireq.link == link
268
+ if ireq.link.is_wheel and not ireq.link.is_file:
269
+ wheel = Wheel(ireq.link.filename)
270
+ wheel_name = canonicalize_name(wheel.name)
271
+ assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel"
272
+ # Version may not be present for PEP 508 direct URLs
273
+ if version is not None:
274
+ wheel_version = Version(wheel.version)
275
+ assert version == wheel_version, "{!r} != {!r} for wheel {}".format(
276
+ version, wheel_version, name
277
+ )
278
+
279
+ if cache_entry is not None:
280
+ assert ireq.link.is_wheel
281
+ assert ireq.link.is_file
282
+ if cache_entry.persistent and template.link is template.original_link:
283
+ ireq.cached_wheel_source_link = source_link
284
+ if cache_entry.origin is not None:
285
+ ireq.download_info = cache_entry.origin
286
+ else:
287
+ # Legacy cache entry that does not have origin.json.
288
+ # download_info may miss the archive_info.hashes field.
289
+ ireq.download_info = direct_url_from_link(
290
+ source_link, link_is_in_wheel_cache=cache_entry.persistent
291
+ )
292
+
293
+ super().__init__(
294
+ link=link,
295
+ source_link=source_link,
296
+ ireq=ireq,
297
+ factory=factory,
298
+ name=name,
299
+ version=version,
300
+ )
301
+
302
+ def _prepare_distribution(self) -> BaseDistribution:
303
+ preparer = self._factory.preparer
304
+ return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
305
+
306
+
307
+ class EditableCandidate(_InstallRequirementBackedCandidate):
308
+ is_editable = True
309
+
310
+ def __init__(
311
+ self,
312
+ link: Link,
313
+ template: InstallRequirement,
314
+ factory: "Factory",
315
+ name: Optional[NormalizedName] = None,
316
+ version: Optional[CandidateVersion] = None,
317
+ ) -> None:
318
+ super().__init__(
319
+ link=link,
320
+ source_link=link,
321
+ ireq=make_install_req_from_editable(link, template),
322
+ factory=factory,
323
+ name=name,
324
+ version=version,
325
+ )
326
+
327
+ def _prepare_distribution(self) -> BaseDistribution:
328
+ return self._factory.preparer.prepare_editable_requirement(self._ireq)
329
+
330
+
331
+ class AlreadyInstalledCandidate(Candidate):
332
+ is_installed = True
333
+ source_link = None
334
+
335
+ def __init__(
336
+ self,
337
+ dist: BaseDistribution,
338
+ template: InstallRequirement,
339
+ factory: "Factory",
340
+ ) -> None:
341
+ self.dist = dist
342
+ self._ireq = _make_install_req_from_dist(dist, template)
343
+ self._factory = factory
344
+ self._version = None
345
+
346
+ # This is just logging some messages, so we can do it eagerly.
347
+ # The returned dist would be exactly the same as self.dist because we
348
+ # set satisfied_by in _make_install_req_from_dist.
349
+ # TODO: Supply reason based on force_reinstall and upgrade_strategy.
350
+ skip_reason = "already satisfied"
351
+ factory.preparer.prepare_installed_requirement(self._ireq, skip_reason)
352
+
353
+ def __str__(self) -> str:
354
+ return str(self.dist)
355
+
356
+ def __repr__(self) -> str:
357
+ return "{class_name}({distribution!r})".format(
358
+ class_name=self.__class__.__name__,
359
+ distribution=self.dist,
360
+ )
361
+
362
+ def __hash__(self) -> int:
363
+ return hash((self.__class__, self.name, self.version))
364
+
365
+ def __eq__(self, other: Any) -> bool:
366
+ if isinstance(other, self.__class__):
367
+ return self.name == other.name and self.version == other.version
368
+ return False
369
+
370
+ @property
371
+ def project_name(self) -> NormalizedName:
372
+ return self.dist.canonical_name
373
+
374
+ @property
375
+ def name(self) -> str:
376
+ return self.project_name
377
+
378
+ @property
379
+ def version(self) -> CandidateVersion:
380
+ if self._version is None:
381
+ self._version = self.dist.version
382
+ return self._version
383
+
384
+ @property
385
+ def is_editable(self) -> bool:
386
+ return self.dist.editable
387
+
388
+ def format_for_error(self) -> str:
389
+ return f"{self.name} {self.version} (Installed)"
390
+
391
+ def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
392
+ if not with_requires:
393
+ return
394
+ for r in self.dist.iter_dependencies():
395
+ yield self._factory.make_requirement_from_spec(str(r), self._ireq)
396
+
397
+ def get_install_requirement(self) -> Optional[InstallRequirement]:
398
+ return None
399
+
400
+
401
+ class ExtrasCandidate(Candidate):
402
+ """A candidate that has 'extras', indicating additional dependencies.
403
+
404
+ Requirements can be for a project with dependencies, something like
405
+ foo[extra]. The extras don't affect the project/version being installed
406
+ directly, but indicate that we need additional dependencies. We model that
407
+ by having an artificial ExtrasCandidate that wraps the "base" candidate.
408
+
409
+ The ExtrasCandidate differs from the base in the following ways:
410
+
411
+ 1. It has a unique name, of the form foo[extra]. This causes the resolver
412
+ to treat it as a separate node in the dependency graph.
413
+ 2. When we're getting the candidate's dependencies,
414
+ a) We specify that we want the extra dependencies as well.
415
+ b) We add a dependency on the base candidate.
416
+ See below for why this is needed.
417
+ 3. We return None for the underlying InstallRequirement, as the base
418
+ candidate will provide it, and we don't want to end up with duplicates.
419
+
420
+ The dependency on the base candidate is needed so that the resolver can't
421
+ decide that it should recommend foo[extra1] version 1.0 and foo[extra2]
422
+ version 2.0. Having those candidates depend on foo=1.0 and foo=2.0
423
+ respectively forces the resolver to recognise that this is a conflict.
424
+ """
425
+
426
+ def __init__(
427
+ self,
428
+ base: BaseCandidate,
429
+ extras: FrozenSet[str],
430
+ ) -> None:
431
+ self.base = base
432
+ self.extras = extras
433
+
434
+ def __str__(self) -> str:
435
+ name, rest = str(self.base).split(" ", 1)
436
+ return "{}[{}] {}".format(name, ",".join(self.extras), rest)
437
+
438
+ def __repr__(self) -> str:
439
+ return "{class_name}(base={base!r}, extras={extras!r})".format(
440
+ class_name=self.__class__.__name__,
441
+ base=self.base,
442
+ extras=self.extras,
443
+ )
444
+
445
+ def __hash__(self) -> int:
446
+ return hash((self.base, self.extras))
447
+
448
+ def __eq__(self, other: Any) -> bool:
449
+ if isinstance(other, self.__class__):
450
+ return self.base == other.base and self.extras == other.extras
451
+ return False
452
+
453
+ @property
454
+ def project_name(self) -> NormalizedName:
455
+ return self.base.project_name
456
+
457
+ @property
458
+ def name(self) -> str:
459
+ """The normalised name of the project the candidate refers to"""
460
+ return format_name(self.base.project_name, self.extras)
461
+
462
+ @property
463
+ def version(self) -> CandidateVersion:
464
+ return self.base.version
465
+
466
+ def format_for_error(self) -> str:
467
+ return "{} [{}]".format(
468
+ self.base.format_for_error(), ", ".join(sorted(self.extras))
469
+ )
470
+
471
+ @property
472
+ def is_installed(self) -> bool:
473
+ return self.base.is_installed
474
+
475
+ @property
476
+ def is_editable(self) -> bool:
477
+ return self.base.is_editable
478
+
479
+ @property
480
+ def source_link(self) -> Optional[Link]:
481
+ return self.base.source_link
482
+
483
+ def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
484
+ factory = self.base._factory
485
+
486
+ # Add a dependency on the exact base
487
+ # (See note 2b in the class docstring)
488
+ yield factory.make_requirement_from_candidate(self.base)
489
+ if not with_requires:
490
+ return
491
+
492
+ # The user may have specified extras that the candidate doesn't
493
+ # support. We ignore any unsupported extras here.
494
+ valid_extras = self.extras.intersection(self.base.dist.iter_provided_extras())
495
+ invalid_extras = self.extras.difference(self.base.dist.iter_provided_extras())
496
+ for extra in sorted(invalid_extras):
497
+ logger.warning(
498
+ "%s %s does not provide the extra '%s'",
499
+ self.base.name,
500
+ self.version,
501
+ extra,
502
+ )
503
+
504
+ for r in self.base.dist.iter_dependencies(valid_extras):
505
+ requirement = factory.make_requirement_from_spec(
506
+ str(r), self.base._ireq, valid_extras
507
+ )
508
+ if requirement:
509
+ yield requirement
510
+
511
+ def get_install_requirement(self) -> Optional[InstallRequirement]:
512
+ # We don't return anything here, because we always
513
+ # depend on the base candidate, and we'll get the
514
+ # install requirement from that.
515
+ return None
516
+
517
+
518
+ class RequiresPythonCandidate(Candidate):
519
+ is_installed = False
520
+ source_link = None
521
+
522
+ def __init__(self, py_version_info: Optional[Tuple[int, ...]]) -> None:
523
+ if py_version_info is not None:
524
+ version_info = normalize_version_info(py_version_info)
525
+ else:
526
+ version_info = sys.version_info[:3]
527
+ self._version = Version(".".join(str(c) for c in version_info))
528
+
529
+ # We don't need to implement __eq__() and __ne__() since there is always
530
+ # only one RequiresPythonCandidate in a resolution, i.e. the host Python.
531
+ # The built-in object.__eq__() and object.__ne__() do exactly what we want.
532
+
533
+ def __str__(self) -> str:
534
+ return f"Python {self._version}"
535
+
536
+ @property
537
+ def project_name(self) -> NormalizedName:
538
+ return REQUIRES_PYTHON_IDENTIFIER
539
+
540
+ @property
541
+ def name(self) -> str:
542
+ return REQUIRES_PYTHON_IDENTIFIER
543
+
544
+ @property
545
+ def version(self) -> CandidateVersion:
546
+ return self._version
547
+
548
+ def format_for_error(self) -> str:
549
+ return f"Python {self.version}"
550
+
551
+ def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:
552
+ return ()
553
+
554
+ def get_install_requirement(self) -> Optional[InstallRequirement]:
555
+ return None
.venv/Lib/site-packages/pip/_internal/resolution/resolvelib/factory.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import functools
3
+ import logging
4
+ from typing import (
5
+ TYPE_CHECKING,
6
+ Dict,
7
+ FrozenSet,
8
+ Iterable,
9
+ Iterator,
10
+ List,
11
+ Mapping,
12
+ NamedTuple,
13
+ Optional,
14
+ Sequence,
15
+ Set,
16
+ Tuple,
17
+ TypeVar,
18
+ cast,
19
+ )
20
+
21
+ from pip._vendor.packaging.requirements import InvalidRequirement
22
+ from pip._vendor.packaging.specifiers import SpecifierSet
23
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
24
+ from pip._vendor.resolvelib import ResolutionImpossible
25
+
26
+ from pip._internal.cache import CacheEntry, WheelCache
27
+ from pip._internal.exceptions import (
28
+ DistributionNotFound,
29
+ InstallationError,
30
+ MetadataInconsistent,
31
+ UnsupportedPythonVersion,
32
+ UnsupportedWheel,
33
+ )
34
+ from pip._internal.index.package_finder import PackageFinder
35
+ from pip._internal.metadata import BaseDistribution, get_default_environment
36
+ from pip._internal.models.link import Link
37
+ from pip._internal.models.wheel import Wheel
38
+ from pip._internal.operations.prepare import RequirementPreparer
39
+ from pip._internal.req.constructors import install_req_from_link_and_ireq
40
+ from pip._internal.req.req_install import (
41
+ InstallRequirement,
42
+ check_invalid_constraint_type,
43
+ )
44
+ from pip._internal.resolution.base import InstallRequirementProvider
45
+ from pip._internal.utils.compatibility_tags import get_supported
46
+ from pip._internal.utils.hashes import Hashes
47
+ from pip._internal.utils.packaging import get_requirement
48
+ from pip._internal.utils.virtualenv import running_under_virtualenv
49
+
50
+ from .base import Candidate, CandidateVersion, Constraint, Requirement
51
+ from .candidates import (
52
+ AlreadyInstalledCandidate,
53
+ BaseCandidate,
54
+ EditableCandidate,
55
+ ExtrasCandidate,
56
+ LinkCandidate,
57
+ RequiresPythonCandidate,
58
+ as_base_candidate,
59
+ )
60
+ from .found_candidates import FoundCandidates, IndexCandidateInfo
61
+ from .requirements import (
62
+ ExplicitRequirement,
63
+ RequiresPythonRequirement,
64
+ SpecifierRequirement,
65
+ UnsatisfiableRequirement,
66
+ )
67
+
68
+ if TYPE_CHECKING:
69
+ from typing import Protocol
70
+
71
+ class ConflictCause(Protocol):
72
+ requirement: RequiresPythonRequirement
73
+ parent: Candidate
74
+
75
+
76
+ logger = logging.getLogger(__name__)
77
+
78
+ C = TypeVar("C")
79
+ Cache = Dict[Link, C]
80
+
81
+
82
+ class CollectedRootRequirements(NamedTuple):
83
+ requirements: List[Requirement]
84
+ constraints: Dict[str, Constraint]
85
+ user_requested: Dict[str, int]
86
+
87
+
88
+ class Factory:
89
+ def __init__(
90
+ self,
91
+ finder: PackageFinder,
92
+ preparer: RequirementPreparer,
93
+ make_install_req: InstallRequirementProvider,
94
+ wheel_cache: Optional[WheelCache],
95
+ use_user_site: bool,
96
+ force_reinstall: bool,
97
+ ignore_installed: bool,
98
+ ignore_requires_python: bool,
99
+ py_version_info: Optional[Tuple[int, ...]] = None,
100
+ ) -> None:
101
+ self._finder = finder
102
+ self.preparer = preparer
103
+ self._wheel_cache = wheel_cache
104
+ self._python_candidate = RequiresPythonCandidate(py_version_info)
105
+ self._make_install_req_from_spec = make_install_req
106
+ self._use_user_site = use_user_site
107
+ self._force_reinstall = force_reinstall
108
+ self._ignore_requires_python = ignore_requires_python
109
+
110
+ self._build_failures: Cache[InstallationError] = {}
111
+ self._link_candidate_cache: Cache[LinkCandidate] = {}
112
+ self._editable_candidate_cache: Cache[EditableCandidate] = {}
113
+ self._installed_candidate_cache: Dict[str, AlreadyInstalledCandidate] = {}
114
+ self._extras_candidate_cache: Dict[
115
+ Tuple[int, FrozenSet[str]], ExtrasCandidate
116
+ ] = {}
117
+
118
+ if not ignore_installed:
119
+ env = get_default_environment()
120
+ self._installed_dists = {
121
+ dist.canonical_name: dist
122
+ for dist in env.iter_installed_distributions(local_only=False)
123
+ }
124
+ else:
125
+ self._installed_dists = {}
126
+
127
+ @property
128
+ def force_reinstall(self) -> bool:
129
+ return self._force_reinstall
130
+
131
+ def _fail_if_link_is_unsupported_wheel(self, link: Link) -> None:
132
+ if not link.is_wheel:
133
+ return
134
+ wheel = Wheel(link.filename)
135
+ if wheel.supported(self._finder.target_python.get_tags()):
136
+ return
137
+ msg = f"{link.filename} is not a supported wheel on this platform."
138
+ raise UnsupportedWheel(msg)
139
+
140
+ def _make_extras_candidate(
141
+ self, base: BaseCandidate, extras: FrozenSet[str]
142
+ ) -> ExtrasCandidate:
143
+ cache_key = (id(base), extras)
144
+ try:
145
+ candidate = self._extras_candidate_cache[cache_key]
146
+ except KeyError:
147
+ candidate = ExtrasCandidate(base, extras)
148
+ self._extras_candidate_cache[cache_key] = candidate
149
+ return candidate
150
+
151
+ def _make_candidate_from_dist(
152
+ self,
153
+ dist: BaseDistribution,
154
+ extras: FrozenSet[str],
155
+ template: InstallRequirement,
156
+ ) -> Candidate:
157
+ try:
158
+ base = self._installed_candidate_cache[dist.canonical_name]
159
+ except KeyError:
160
+ base = AlreadyInstalledCandidate(dist, template, factory=self)
161
+ self._installed_candidate_cache[dist.canonical_name] = base
162
+ if not extras:
163
+ return base
164
+ return self._make_extras_candidate(base, extras)
165
+
166
+ def _make_candidate_from_link(
167
+ self,
168
+ link: Link,
169
+ extras: FrozenSet[str],
170
+ template: InstallRequirement,
171
+ name: Optional[NormalizedName],
172
+ version: Optional[CandidateVersion],
173
+ ) -> Optional[Candidate]:
174
+ # TODO: Check already installed candidate, and use it if the link and
175
+ # editable flag match.
176
+
177
+ if link in self._build_failures:
178
+ # We already tried this candidate before, and it does not build.
179
+ # Don't bother trying again.
180
+ return None
181
+
182
+ if template.editable:
183
+ if link not in self._editable_candidate_cache:
184
+ try:
185
+ self._editable_candidate_cache[link] = EditableCandidate(
186
+ link,
187
+ template,
188
+ factory=self,
189
+ name=name,
190
+ version=version,
191
+ )
192
+ except MetadataInconsistent as e:
193
+ logger.info(
194
+ "Discarding [blue underline]%s[/]: [yellow]%s[reset]",
195
+ link,
196
+ e,
197
+ extra={"markup": True},
198
+ )
199
+ self._build_failures[link] = e
200
+ return None
201
+
202
+ base: BaseCandidate = self._editable_candidate_cache[link]
203
+ else:
204
+ if link not in self._link_candidate_cache:
205
+ try:
206
+ self._link_candidate_cache[link] = LinkCandidate(
207
+ link,
208
+ template,
209
+ factory=self,
210
+ name=name,
211
+ version=version,
212
+ )
213
+ except MetadataInconsistent as e:
214
+ logger.info(
215
+ "Discarding [blue underline]%s[/]: [yellow]%s[reset]",
216
+ link,
217
+ e,
218
+ extra={"markup": True},
219
+ )
220
+ self._build_failures[link] = e
221
+ return None
222
+ base = self._link_candidate_cache[link]
223
+
224
+ if not extras:
225
+ return base
226
+ return self._make_extras_candidate(base, extras)
227
+
228
+ def _iter_found_candidates(
229
+ self,
230
+ ireqs: Sequence[InstallRequirement],
231
+ specifier: SpecifierSet,
232
+ hashes: Hashes,
233
+ prefers_installed: bool,
234
+ incompatible_ids: Set[int],
235
+ ) -> Iterable[Candidate]:
236
+ if not ireqs:
237
+ return ()
238
+
239
+ # The InstallRequirement implementation requires us to give it a
240
+ # "template". Here we just choose the first requirement to represent
241
+ # all of them.
242
+ # Hopefully the Project model can correct this mismatch in the future.
243
+ template = ireqs[0]
244
+ assert template.req, "Candidates found on index must be PEP 508"
245
+ name = canonicalize_name(template.req.name)
246
+
247
+ extras: FrozenSet[str] = frozenset()
248
+ for ireq in ireqs:
249
+ assert ireq.req, "Candidates found on index must be PEP 508"
250
+ specifier &= ireq.req.specifier
251
+ hashes &= ireq.hashes(trust_internet=False)
252
+ extras |= frozenset(ireq.extras)
253
+
254
+ def _get_installed_candidate() -> Optional[Candidate]:
255
+ """Get the candidate for the currently-installed version."""
256
+ # If --force-reinstall is set, we want the version from the index
257
+ # instead, so we "pretend" there is nothing installed.
258
+ if self._force_reinstall:
259
+ return None
260
+ try:
261
+ installed_dist = self._installed_dists[name]
262
+ except KeyError:
263
+ return None
264
+ # Don't use the installed distribution if its version does not fit
265
+ # the current dependency graph.
266
+ if not specifier.contains(installed_dist.version, prereleases=True):
267
+ return None
268
+ candidate = self._make_candidate_from_dist(
269
+ dist=installed_dist,
270
+ extras=extras,
271
+ template=template,
272
+ )
273
+ # The candidate is a known incompatibility. Don't use it.
274
+ if id(candidate) in incompatible_ids:
275
+ return None
276
+ return candidate
277
+
278
+ def iter_index_candidate_infos() -> Iterator[IndexCandidateInfo]:
279
+ result = self._finder.find_best_candidate(
280
+ project_name=name,
281
+ specifier=specifier,
282
+ hashes=hashes,
283
+ )
284
+ icans = list(result.iter_applicable())
285
+
286
+ # PEP 592: Yanked releases are ignored unless the specifier
287
+ # explicitly pins a version (via '==' or '===') that can be
288
+ # solely satisfied by a yanked release.
289
+ all_yanked = all(ican.link.is_yanked for ican in icans)
290
+
291
+ def is_pinned(specifier: SpecifierSet) -> bool:
292
+ for sp in specifier:
293
+ if sp.operator == "===":
294
+ return True
295
+ if sp.operator != "==":
296
+ continue
297
+ if sp.version.endswith(".*"):
298
+ continue
299
+ return True
300
+ return False
301
+
302
+ pinned = is_pinned(specifier)
303
+
304
+ # PackageFinder returns earlier versions first, so we reverse.
305
+ for ican in reversed(icans):
306
+ if not (all_yanked and pinned) and ican.link.is_yanked:
307
+ continue
308
+ func = functools.partial(
309
+ self._make_candidate_from_link,
310
+ link=ican.link,
311
+ extras=extras,
312
+ template=template,
313
+ name=name,
314
+ version=ican.version,
315
+ )
316
+ yield ican.version, func
317
+
318
+ return FoundCandidates(
319
+ iter_index_candidate_infos,
320
+ _get_installed_candidate(),
321
+ prefers_installed,
322
+ incompatible_ids,
323
+ )
324
+
325
+ def _iter_explicit_candidates_from_base(
326
+ self,
327
+ base_requirements: Iterable[Requirement],
328
+ extras: FrozenSet[str],
329
+ ) -> Iterator[Candidate]:
330
+ """Produce explicit candidates from the base given an extra-ed package.
331
+
332
+ :param base_requirements: Requirements known to the resolver. The
333
+ requirements are guaranteed to not have extras.
334
+ :param extras: The extras to inject into the explicit requirements'
335
+ candidates.
336
+ """
337
+ for req in base_requirements:
338
+ lookup_cand, _ = req.get_candidate_lookup()
339
+ if lookup_cand is None: # Not explicit.
340
+ continue
341
+ # We've stripped extras from the identifier, and should always
342
+ # get a BaseCandidate here, unless there's a bug elsewhere.
343
+ base_cand = as_base_candidate(lookup_cand)
344
+ assert base_cand is not None, "no extras here"
345
+ yield self._make_extras_candidate(base_cand, extras)
346
+
347
+ def _iter_candidates_from_constraints(
348
+ self,
349
+ identifier: str,
350
+ constraint: Constraint,
351
+ template: InstallRequirement,
352
+ ) -> Iterator[Candidate]:
353
+ """Produce explicit candidates from constraints.
354
+
355
+ This creates "fake" InstallRequirement objects that are basically clones
356
+ of what "should" be the template, but with original_link set to link.
357
+ """
358
+ for link in constraint.links:
359
+ self._fail_if_link_is_unsupported_wheel(link)
360
+ candidate = self._make_candidate_from_link(
361
+ link,
362
+ extras=frozenset(),
363
+ template=install_req_from_link_and_ireq(link, template),
364
+ name=canonicalize_name(identifier),
365
+ version=None,
366
+ )
367
+ if candidate:
368
+ yield candidate
369
+
370
+ def find_candidates(
371
+ self,
372
+ identifier: str,
373
+ requirements: Mapping[str, Iterable[Requirement]],
374
+ incompatibilities: Mapping[str, Iterator[Candidate]],
375
+ constraint: Constraint,
376
+ prefers_installed: bool,
377
+ ) -> Iterable[Candidate]:
378
+ # Collect basic lookup information from the requirements.
379
+ explicit_candidates: Set[Candidate] = set()
380
+ ireqs: List[InstallRequirement] = []
381
+ for req in requirements[identifier]:
382
+ cand, ireq = req.get_candidate_lookup()
383
+ if cand is not None:
384
+ explicit_candidates.add(cand)
385
+ if ireq is not None:
386
+ ireqs.append(ireq)
387
+
388
+ # If the current identifier contains extras, add explicit candidates
389
+ # from entries from extra-less identifier.
390
+ with contextlib.suppress(InvalidRequirement):
391
+ parsed_requirement = get_requirement(identifier)
392
+ explicit_candidates.update(
393
+ self._iter_explicit_candidates_from_base(
394
+ requirements.get(parsed_requirement.name, ()),
395
+ frozenset(parsed_requirement.extras),
396
+ ),
397
+ )
398
+
399
+ # Add explicit candidates from constraints. We only do this if there are
400
+ # known ireqs, which represent requirements not already explicit. If
401
+ # there are no ireqs, we're constraining already-explicit requirements,
402
+ # which is handled later when we return the explicit candidates.
403
+ if ireqs:
404
+ try:
405
+ explicit_candidates.update(
406
+ self._iter_candidates_from_constraints(
407
+ identifier,
408
+ constraint,
409
+ template=ireqs[0],
410
+ ),
411
+ )
412
+ except UnsupportedWheel:
413
+ # If we're constrained to install a wheel incompatible with the
414
+ # target architecture, no candidates will ever be valid.
415
+ return ()
416
+
417
+ # Since we cache all the candidates, incompatibility identification
418
+ # can be made quicker by comparing only the id() values.
419
+ incompat_ids = {id(c) for c in incompatibilities.get(identifier, ())}
420
+
421
+ # If none of the requirements want an explicit candidate, we can ask
422
+ # the finder for candidates.
423
+ if not explicit_candidates:
424
+ return self._iter_found_candidates(
425
+ ireqs,
426
+ constraint.specifier,
427
+ constraint.hashes,
428
+ prefers_installed,
429
+ incompat_ids,
430
+ )
431
+
432
+ return (
433
+ c
434
+ for c in explicit_candidates
435
+ if id(c) not in incompat_ids
436
+ and constraint.is_satisfied_by(c)
437
+ and all(req.is_satisfied_by(c) for req in requirements[identifier])
438
+ )
439
+
440
+ def _make_requirement_from_install_req(
441
+ self, ireq: InstallRequirement, requested_extras: Iterable[str]
442
+ ) -> Optional[Requirement]:
443
+ if not ireq.match_markers(requested_extras):
444
+ logger.info(
445
+ "Ignoring %s: markers '%s' don't match your environment",
446
+ ireq.name,
447
+ ireq.markers,
448
+ )
449
+ return None
450
+ if not ireq.link:
451
+ return SpecifierRequirement(ireq)
452
+ self._fail_if_link_is_unsupported_wheel(ireq.link)
453
+ cand = self._make_candidate_from_link(
454
+ ireq.link,
455
+ extras=frozenset(ireq.extras),
456
+ template=ireq,
457
+ name=canonicalize_name(ireq.name) if ireq.name else None,
458
+ version=None,
459
+ )
460
+ if cand is None:
461
+ # There's no way we can satisfy a URL requirement if the underlying
462
+ # candidate fails to build. An unnamed URL must be user-supplied, so
463
+ # we fail eagerly. If the URL is named, an unsatisfiable requirement
464
+ # can make the resolver do the right thing, either backtrack (and
465
+ # maybe find some other requirement that's buildable) or raise a
466
+ # ResolutionImpossible eventually.
467
+ if not ireq.name:
468
+ raise self._build_failures[ireq.link]
469
+ return UnsatisfiableRequirement(canonicalize_name(ireq.name))
470
+ return self.make_requirement_from_candidate(cand)
471
+
472
+ def collect_root_requirements(
473
+ self, root_ireqs: List[InstallRequirement]
474
+ ) -> CollectedRootRequirements:
475
+ collected = CollectedRootRequirements([], {}, {})
476
+ for i, ireq in enumerate(root_ireqs):
477
+ if ireq.constraint:
478
+ # Ensure we only accept valid constraints
479
+ problem = check_invalid_constraint_type(ireq)
480
+ if problem:
481
+ raise InstallationError(problem)
482
+ if not ireq.match_markers():
483
+ continue
484
+ assert ireq.name, "Constraint must be named"
485
+ name = canonicalize_name(ireq.name)
486
+ if name in collected.constraints:
487
+ collected.constraints[name] &= ireq
488
+ else:
489
+ collected.constraints[name] = Constraint.from_ireq(ireq)
490
+ else:
491
+ req = self._make_requirement_from_install_req(
492
+ ireq,
493
+ requested_extras=(),
494
+ )
495
+ if req is None:
496
+ continue
497
+ if ireq.user_supplied and req.name not in collected.user_requested:
498
+ collected.user_requested[req.name] = i
499
+ collected.requirements.append(req)
500
+ return collected
501
+
502
+ def make_requirement_from_candidate(
503
+ self, candidate: Candidate
504
+ ) -> ExplicitRequirement:
505
+ return ExplicitRequirement(candidate)
506
+
507
+ def make_requirement_from_spec(
508
+ self,
509
+ specifier: str,
510
+ comes_from: Optional[InstallRequirement],
511
+ requested_extras: Iterable[str] = (),
512
+ ) -> Optional[Requirement]:
513
+ ireq = self._make_install_req_from_spec(specifier, comes_from)
514
+ return self._make_requirement_from_install_req(ireq, requested_extras)
515
+
516
+ def make_requires_python_requirement(
517
+ self,
518
+ specifier: SpecifierSet,
519
+ ) -> Optional[Requirement]:
520
+ if self._ignore_requires_python:
521
+ return None
522
+ # Don't bother creating a dependency for an empty Requires-Python.
523
+ if not str(specifier):
524
+ return None
525
+ return RequiresPythonRequirement(specifier, self._python_candidate)
526
+
527
+ def get_wheel_cache_entry(
528
+ self, link: Link, name: Optional[str]
529
+ ) -> Optional[CacheEntry]:
530
+ """Look up the link in the wheel cache.
531
+
532
+ If ``preparer.require_hashes`` is True, don't use the wheel cache,
533
+ because cached wheels, always built locally, have different hashes
534
+ than the files downloaded from the index server and thus throw false
535
+ hash mismatches. Furthermore, cached wheels at present have
536
+ nondeterministic contents due to file modification times.
537
+ """
538
+ if self._wheel_cache is None:
539
+ return None
540
+ return self._wheel_cache.get_cache_entry(
541
+ link=link,
542
+ package_name=name,
543
+ supported_tags=get_supported(),
544
+ )
545
+
546
+ def get_dist_to_uninstall(self, candidate: Candidate) -> Optional[BaseDistribution]:
547
+ # TODO: Are there more cases this needs to return True? Editable?
548
+ dist = self._installed_dists.get(candidate.project_name)
549
+ if dist is None: # Not installed, no uninstallation required.
550
+ return None
551
+
552
+ # We're installing into global site. The current installation must
553
+ # be uninstalled, no matter it's in global or user site, because the
554
+ # user site installation has precedence over global.
555
+ if not self._use_user_site:
556
+ return dist
557
+
558
+ # We're installing into user site. Remove the user site installation.
559
+ if dist.in_usersite:
560
+ return dist
561
+
562
+ # We're installing into user site, but the installed incompatible
563
+ # package is in global site. We can't uninstall that, and would let
564
+ # the new user installation to "shadow" it. But shadowing won't work
565
+ # in virtual environments, so we error out.
566
+ if running_under_virtualenv() and dist.in_site_packages:
567
+ message = (
568
+ f"Will not install to the user site because it will lack "
569
+ f"sys.path precedence to {dist.raw_name} in {dist.location}"
570
+ )
571
+ raise InstallationError(message)
572
+ return None
573
+
574
+ def _report_requires_python_error(
575
+ self, causes: Sequence["ConflictCause"]
576
+ ) -> UnsupportedPythonVersion:
577
+ assert causes, "Requires-Python error reported with no cause"
578
+
579
+ version = self._python_candidate.version
580
+
581
+ if len(causes) == 1:
582
+ specifier = str(causes[0].requirement.specifier)
583
+ message = (
584
+ f"Package {causes[0].parent.name!r} requires a different "
585
+ f"Python: {version} not in {specifier!r}"
586
+ )
587
+ return UnsupportedPythonVersion(message)
588
+
589
+ message = f"Packages require a different Python. {version} not in:"
590
+ for cause in causes:
591
+ package = cause.parent.format_for_error()
592
+ specifier = str(cause.requirement.specifier)
593
+ message += f"\n{specifier!r} (required by {package})"
594
+ return UnsupportedPythonVersion(message)
595
+
596
+ def _report_single_requirement_conflict(
597
+ self, req: Requirement, parent: Optional[Candidate]
598
+ ) -> DistributionNotFound:
599
+ if parent is None:
600
+ req_disp = str(req)
601
+ else:
602
+ req_disp = f"{req} (from {parent.name})"
603
+
604
+ cands = self._finder.find_all_candidates(req.project_name)
605
+ skipped_by_requires_python = self._finder.requires_python_skipped_reasons()
606
+ versions = [str(v) for v in sorted({c.version for c in cands})]
607
+
608
+ if skipped_by_requires_python:
609
+ logger.critical(
610
+ "Ignored the following versions that require a different python "
611
+ "version: %s",
612
+ "; ".join(skipped_by_requires_python) or "none",
613
+ )
614
+ logger.critical(
615
+ "Could not find a version that satisfies the requirement %s "
616
+ "(from versions: %s)",
617
+ req_disp,
618
+ ", ".join(versions) or "none",
619
+ )
620
+ if str(req) == "requirements.txt":
621
+ logger.info(
622
+ "HINT: You are attempting to install a package literally "
623
+ 'named "requirements.txt" (which cannot exist). Consider '
624
+ "using the '-r' flag to install the packages listed in "
625
+ "requirements.txt"
626
+ )
627
+
628
+ return DistributionNotFound(f"No matching distribution found for {req}")
629
+
630
+ def get_installation_error(
631
+ self,
632
+ e: "ResolutionImpossible[Requirement, Candidate]",
633
+ constraints: Dict[str, Constraint],
634
+ ) -> InstallationError:
635
+ assert e.causes, "Installation error reported with no cause"
636
+
637
+ # If one of the things we can't solve is "we need Python X.Y",
638
+ # that is what we report.
639
+ requires_python_causes = [
640
+ cause
641
+ for cause in e.causes
642
+ if isinstance(cause.requirement, RequiresPythonRequirement)
643
+ and not cause.requirement.is_satisfied_by(self._python_candidate)
644
+ ]
645
+ if requires_python_causes:
646
+ # The comprehension above makes sure all Requirement instances are
647
+ # RequiresPythonRequirement, so let's cast for convenience.
648
+ return self._report_requires_python_error(
649
+ cast("Sequence[ConflictCause]", requires_python_causes),
650
+ )
651
+
652
+ # Otherwise, we have a set of causes which can't all be satisfied
653
+ # at once.
654
+
655
+ # The simplest case is when we have *one* cause that can't be
656
+ # satisfied. We just report that case.
657
+ if len(e.causes) == 1:
658
+ req, parent = e.causes[0]
659
+ if req.name not in constraints:
660
+ return self._report_single_requirement_conflict(req, parent)
661
+
662
+ # OK, we now have a list of requirements that can't all be
663
+ # satisfied at once.
664
+
665
+ # A couple of formatting helpers
666
+ def text_join(parts: List[str]) -> str:
667
+ if len(parts) == 1:
668
+ return parts[0]
669
+
670
+ return ", ".join(parts[:-1]) + " and " + parts[-1]
671
+
672
+ def describe_trigger(parent: Candidate) -> str:
673
+ ireq = parent.get_install_requirement()
674
+ if not ireq or not ireq.comes_from:
675
+ return f"{parent.name}=={parent.version}"
676
+ if isinstance(ireq.comes_from, InstallRequirement):
677
+ return str(ireq.comes_from.name)
678
+ return str(ireq.comes_from)
679
+
680
+ triggers = set()
681
+ for req, parent in e.causes:
682
+ if parent is None:
683
+ # This is a root requirement, so we can report it directly
684
+ trigger = req.format_for_error()
685
+ else:
686
+ trigger = describe_trigger(parent)
687
+ triggers.add(trigger)
688
+
689
+ if triggers:
690
+ info = text_join(sorted(triggers))
691
+ else:
692
+ info = "the requested packages"
693
+
694
+ msg = (
695
+ "Cannot install {} because these package versions "
696
+ "have conflicting dependencies.".format(info)
697
+ )
698
+ logger.critical(msg)
699
+ msg = "\nThe conflict is caused by:"
700
+
701
+ relevant_constraints = set()
702
+ for req, parent in e.causes:
703
+ if req.name in constraints:
704
+ relevant_constraints.add(req.name)
705
+ msg = msg + "\n "
706
+ if parent:
707
+ msg = msg + f"{parent.name} {parent.version} depends on "
708
+ else:
709
+ msg = msg + "The user requested "
710
+ msg = msg + req.format_for_error()
711
+ for key in relevant_constraints:
712
+ spec = constraints[key].specifier
713
+ msg += f"\n The user requested (constraint) {key}{spec}"
714
+
715
+ msg = (
716
+ msg
717
+ + "\n\n"
718
+ + "To fix this you could try to:\n"
719
+ + "1. loosen the range of package versions you've specified\n"
720
+ + "2. remove package versions to allow pip attempt to solve "
721
+ + "the dependency conflict\n"
722
+ )
723
+
724
+ logger.info(msg)
725
+
726
+ return DistributionNotFound(
727
+ "ResolutionImpossible: for help visit "
728
+ "https://pip.pypa.io/en/latest/topics/dependency-resolution/"
729
+ "#dealing-with-dependency-conflicts"
730
+ )