applied-ai-018 commited on
Commit
ddb4969
·
verified ·
1 Parent(s): 438aed8

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. ckpts/universal/global_step80/zero/12.input_layernorm.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step80/zero/12.input_layernorm.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step80/zero/12.input_layernorm.weight/fp32.pt +3 -0
  4. venv/lib/python3.10/site-packages/pip/_internal/distributions/__init__.py +21 -0
  5. venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/base.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/pip/_internal/distributions/base.py +36 -0
  11. venv/lib/python3.10/site-packages/pip/_internal/distributions/installed.py +20 -0
  12. venv/lib/python3.10/site-packages/pip/_internal/distributions/sdist.py +127 -0
  13. venv/lib/python3.10/site-packages/pip/_internal/distributions/wheel.py +31 -0
  14. venv/lib/python3.10/site-packages/pip/_internal/metadata/__init__.py +62 -0
  15. venv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/base.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pip/_internal/metadata/base.py +546 -0
  19. venv/lib/python3.10/site-packages/pip/_internal/metadata/pkg_resources.py +256 -0
  20. venv/lib/python3.10/site-packages/pip/_internal/network/__init__.py +2 -0
  21. venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/auth.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/cache.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/session.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/xmlrpc.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/pip/_internal/network/auth.py +323 -0
  27. venv/lib/python3.10/site-packages/pip/_internal/network/download.py +185 -0
  28. venv/lib/python3.10/site-packages/pip/_internal/network/utils.py +96 -0
  29. venv/lib/python3.10/site-packages/pip/_internal/network/xmlrpc.py +60 -0
  30. venv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/check.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/freeze.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__init__.py +0 -0
  35. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata.py +39 -0
  43. venv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata_editable.py +41 -0
  44. venv/lib/python3.10/site-packages/pip/_internal/operations/build/metadata_legacy.py +74 -0
  45. venv/lib/python3.10/site-packages/pip/_internal/operations/build/wheel.py +37 -0
  46. venv/lib/python3.10/site-packages/pip/_internal/operations/build/wheel_editable.py +46 -0
  47. venv/lib/python3.10/site-packages/pip/_internal/operations/build/wheel_legacy.py +102 -0
  48. venv/lib/python3.10/site-packages/pip/_internal/operations/install/__init__.py +2 -0
  49. venv/lib/python3.10/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/12.input_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f2f9880aa38f0ac76dc56fdb62143e75e377290d8d8d06b01b22d27b7c931d5
3
+ size 9372
ckpts/universal/global_step80/zero/12.input_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80407f4fe500a51387d2c7ba3d86dc340bae15fdf2bec7cba5dae75dbe418845
3
+ size 9387
ckpts/universal/global_step80/zero/12.input_layernorm.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d66ac211ed4d69757ee85be13f8426a6f1fe0eb48d46f164d0e073dc4332cb1e
3
+ size 9293
venv/lib/python3.10/site-packages/pip/_internal/distributions/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pip._internal.distributions.base import AbstractDistribution
2
+ from pip._internal.distributions.sdist import SourceDistribution
3
+ from pip._internal.distributions.wheel import WheelDistribution
4
+ from pip._internal.req.req_install import InstallRequirement
5
+
6
+
7
+ def make_distribution_for_install_requirement(
8
+ install_req: InstallRequirement,
9
+ ) -> AbstractDistribution:
10
+ """Returns a Distribution for the given InstallRequirement"""
11
+ # Editable requirements will always be source distributions. They use the
12
+ # legacy logic until we create a modern standard for them.
13
+ if install_req.editable:
14
+ return SourceDistribution(install_req)
15
+
16
+ # If it's a wheel, it's a WheelDistribution
17
+ if install_req.is_wheel:
18
+ return WheelDistribution(install_req)
19
+
20
+ # Otherwise, a SourceDistribution
21
+ return SourceDistribution(install_req)
venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (795 Bytes). View file
 
venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/base.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-310.pyc ADDED
Binary file (1.23 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-310.pyc ADDED
Binary file (4.44 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/distributions/base.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+ from pip._internal.index.package_finder import PackageFinder
4
+ from pip._internal.metadata.base import BaseDistribution
5
+ from pip._internal.req import InstallRequirement
6
+
7
+
8
+ class AbstractDistribution(metaclass=abc.ABCMeta):
9
+ """A base class for handling installable artifacts.
10
+
11
+ The requirements for anything installable are as follows:
12
+
13
+ - we must be able to determine the requirement name
14
+ (or we can't correctly handle the non-upgrade case).
15
+
16
+ - for packages with setup requirements, we must also be able
17
+ to determine their requirements without installing additional
18
+ packages (for the same reason as run-time dependencies)
19
+
20
+ - we must be able to create a Distribution object exposing the
21
+ above metadata.
22
+ """
23
+
24
+ def __init__(self, req: InstallRequirement) -> None:
25
+ super().__init__()
26
+ self.req = req
27
+
28
+ @abc.abstractmethod
29
+ def get_metadata_distribution(self) -> BaseDistribution:
30
+ raise NotImplementedError()
31
+
32
+ @abc.abstractmethod
33
+ def prepare_distribution_metadata(
34
+ self, finder: PackageFinder, build_isolation: bool
35
+ ) -> None:
36
+ raise NotImplementedError()
venv/lib/python3.10/site-packages/pip/_internal/distributions/installed.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pip._internal.distributions.base import AbstractDistribution
2
+ from pip._internal.index.package_finder import PackageFinder
3
+ from pip._internal.metadata import BaseDistribution
4
+
5
+
6
+ class InstalledDistribution(AbstractDistribution):
7
+ """Represents an installed package.
8
+
9
+ This does not need any preparation as the required information has already
10
+ been computed.
11
+ """
12
+
13
+ def get_metadata_distribution(self) -> BaseDistribution:
14
+ assert self.req.satisfied_by is not None, "not actually installed"
15
+ return self.req.satisfied_by
16
+
17
+ def prepare_distribution_metadata(
18
+ self, finder: PackageFinder, build_isolation: bool
19
+ ) -> None:
20
+ pass
venv/lib/python3.10/site-packages/pip/_internal/distributions/sdist.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Iterable, Set, Tuple
3
+
4
+ from pip._internal.build_env import BuildEnvironment
5
+ from pip._internal.distributions.base import AbstractDistribution
6
+ from pip._internal.exceptions import InstallationError
7
+ from pip._internal.index.package_finder import PackageFinder
8
+ from pip._internal.metadata import BaseDistribution
9
+ from pip._internal.utils.subprocess import runner_with_spinner_message
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class SourceDistribution(AbstractDistribution):
15
+ """Represents a source distribution.
16
+
17
+ The preparation step for these needs metadata for the packages to be
18
+ generated, either using PEP 517 or using the legacy `setup.py egg_info`.
19
+ """
20
+
21
+ def get_metadata_distribution(self) -> BaseDistribution:
22
+ return self.req.get_dist()
23
+
24
+ def prepare_distribution_metadata(
25
+ self, finder: PackageFinder, build_isolation: bool
26
+ ) -> None:
27
+ # Load pyproject.toml, to determine whether PEP 517 is to be used
28
+ self.req.load_pyproject_toml()
29
+
30
+ # Set up the build isolation, if this requirement should be isolated
31
+ should_isolate = self.req.use_pep517 and build_isolation
32
+ if should_isolate:
33
+ # Setup an isolated environment and install the build backend static
34
+ # requirements in it.
35
+ self._prepare_build_backend(finder)
36
+ # Check that if the requirement is editable, it either supports PEP 660 or
37
+ # has a setup.py or a setup.cfg. This cannot be done earlier because we need
38
+ # to setup the build backend to verify it supports build_editable, nor can
39
+ # it be done later, because we want to avoid installing build requirements
40
+ # needlessly. Doing it here also works around setuptools generating
41
+ # UNKNOWN.egg-info when running get_requires_for_build_wheel on a directory
42
+ # without setup.py nor setup.cfg.
43
+ self.req.isolated_editable_sanity_check()
44
+ # Install the dynamic build requirements.
45
+ self._install_build_reqs(finder)
46
+
47
+ self.req.prepare_metadata()
48
+
49
+ def _prepare_build_backend(self, finder: PackageFinder) -> None:
50
+ # Isolate in a BuildEnvironment and install the build-time
51
+ # requirements.
52
+ pyproject_requires = self.req.pyproject_requires
53
+ assert pyproject_requires is not None
54
+
55
+ self.req.build_env = BuildEnvironment()
56
+ self.req.build_env.install_requirements(
57
+ finder, pyproject_requires, "overlay", kind="build dependencies"
58
+ )
59
+ conflicting, missing = self.req.build_env.check_requirements(
60
+ self.req.requirements_to_check
61
+ )
62
+ if conflicting:
63
+ self._raise_conflicts("PEP 517/518 supported requirements", conflicting)
64
+ if missing:
65
+ logger.warning(
66
+ "Missing build requirements in pyproject.toml for %s.",
67
+ self.req,
68
+ )
69
+ logger.warning(
70
+ "The project does not specify a build backend, and "
71
+ "pip cannot fall back to setuptools without %s.",
72
+ " and ".join(map(repr, sorted(missing))),
73
+ )
74
+
75
+ def _get_build_requires_wheel(self) -> Iterable[str]:
76
+ with self.req.build_env:
77
+ runner = runner_with_spinner_message("Getting requirements to build wheel")
78
+ backend = self.req.pep517_backend
79
+ assert backend is not None
80
+ with backend.subprocess_runner(runner):
81
+ return backend.get_requires_for_build_wheel()
82
+
83
+ def _get_build_requires_editable(self) -> Iterable[str]:
84
+ with self.req.build_env:
85
+ runner = runner_with_spinner_message(
86
+ "Getting requirements to build editable"
87
+ )
88
+ backend = self.req.pep517_backend
89
+ assert backend is not None
90
+ with backend.subprocess_runner(runner):
91
+ return backend.get_requires_for_build_editable()
92
+
93
+ def _install_build_reqs(self, finder: PackageFinder) -> None:
94
+ # Install any extra build dependencies that the backend requests.
95
+ # This must be done in a second pass, as the pyproject.toml
96
+ # dependencies must be installed before we can call the backend.
97
+ if (
98
+ self.req.editable
99
+ and self.req.permit_editable_wheels
100
+ and self.req.supports_pyproject_editable()
101
+ ):
102
+ build_reqs = self._get_build_requires_editable()
103
+ else:
104
+ build_reqs = self._get_build_requires_wheel()
105
+ conflicting, missing = self.req.build_env.check_requirements(build_reqs)
106
+ if conflicting:
107
+ self._raise_conflicts("the backend dependencies", conflicting)
108
+ self.req.build_env.install_requirements(
109
+ finder, missing, "normal", kind="backend dependencies"
110
+ )
111
+
112
+ def _raise_conflicts(
113
+ self, conflicting_with: str, conflicting_reqs: Set[Tuple[str, str]]
114
+ ) -> None:
115
+ format_string = (
116
+ "Some build dependencies for {requirement} "
117
+ "conflict with {conflicting_with}: {description}."
118
+ )
119
+ error_message = format_string.format(
120
+ requirement=self.req,
121
+ conflicting_with=conflicting_with,
122
+ description=", ".join(
123
+ f"{installed} is incompatible with {wanted}"
124
+ for installed, wanted in sorted(conflicting_reqs)
125
+ ),
126
+ )
127
+ raise InstallationError(error_message)
venv/lib/python3.10/site-packages/pip/_internal/distributions/wheel.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pip._vendor.packaging.utils import canonicalize_name
2
+
3
+ from pip._internal.distributions.base import AbstractDistribution
4
+ from pip._internal.index.package_finder import PackageFinder
5
+ from pip._internal.metadata import (
6
+ BaseDistribution,
7
+ FilesystemWheel,
8
+ get_wheel_distribution,
9
+ )
10
+
11
+
12
+ class WheelDistribution(AbstractDistribution):
13
+ """Represents a wheel distribution.
14
+
15
+ This does not need any preparation as wheels can be directly unpacked.
16
+ """
17
+
18
+ def get_metadata_distribution(self) -> BaseDistribution:
19
+ """Loads the metadata from the wheel file into memory and returns a
20
+ Distribution that uses it, not relying on the wheel file or
21
+ requirement.
22
+ """
23
+ assert self.req.local_file_path, "Set as part of preparation during download"
24
+ assert self.req.name, "Wheels are never unnamed"
25
+ wheel = FilesystemWheel(self.req.local_file_path)
26
+ return get_wheel_distribution(wheel, canonicalize_name(self.req.name))
27
+
28
+ def prepare_distribution_metadata(
29
+ self, finder: PackageFinder, build_isolation: bool
30
+ ) -> None:
31
+ pass
venv/lib/python3.10/site-packages/pip/_internal/metadata/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
4
+
5
+ __all__ = [
6
+ "BaseDistribution",
7
+ "BaseEnvironment",
8
+ "FilesystemWheel",
9
+ "MemoryWheel",
10
+ "Wheel",
11
+ "get_default_environment",
12
+ "get_environment",
13
+ "get_wheel_distribution",
14
+ ]
15
+
16
+
17
+ def get_default_environment() -> BaseEnvironment:
18
+ """Get the default representation for the current environment.
19
+
20
+ This returns an Environment instance from the chosen backend. The default
21
+ Environment instance should be built from ``sys.path`` and may use caching
22
+ to share instance state accorss calls.
23
+ """
24
+ from .pkg_resources import Environment
25
+
26
+ return Environment.default()
27
+
28
+
29
+ def get_environment(paths: Optional[List[str]]) -> BaseEnvironment:
30
+ """Get a representation of the environment specified by ``paths``.
31
+
32
+ This returns an Environment instance from the chosen backend based on the
33
+ given import paths. The backend must build a fresh instance representing
34
+ the state of installed distributions when this function is called.
35
+ """
36
+ from .pkg_resources import Environment
37
+
38
+ return Environment.from_paths(paths)
39
+
40
+
41
+ def get_directory_distribution(directory: str) -> BaseDistribution:
42
+ """Get the distribution metadata representation in the specified directory.
43
+
44
+ This returns a Distribution instance from the chosen backend based on
45
+ the given on-disk ``.dist-info`` directory.
46
+ """
47
+ from .pkg_resources import Distribution
48
+
49
+ return Distribution.from_directory(directory)
50
+
51
+
52
+ def get_wheel_distribution(wheel: Wheel, canonical_name: str) -> BaseDistribution:
53
+ """Get the representation of the specified wheel's distribution metadata.
54
+
55
+ This returns a Distribution instance from the chosen backend based on
56
+ the given wheel's ``.dist-info`` directory.
57
+
58
+ :param canonical_name: Normalized project name of the given wheel.
59
+ """
60
+ from .pkg_resources import Distribution
61
+
62
+ return Distribution.from_wheel(wheel, canonical_name)
venv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.29 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/base.cpython-310.pyc ADDED
Binary file (20.8 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-310.pyc ADDED
Binary file (9.86 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/metadata/base.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import email.message
3
+ import json
4
+ import logging
5
+ import pathlib
6
+ import re
7
+ import zipfile
8
+ from typing import (
9
+ IO,
10
+ TYPE_CHECKING,
11
+ Collection,
12
+ Container,
13
+ Iterable,
14
+ Iterator,
15
+ List,
16
+ Optional,
17
+ Tuple,
18
+ Union,
19
+ )
20
+
21
+ from pip._vendor.packaging.requirements import Requirement
22
+ from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
23
+ from pip._vendor.packaging.utils import NormalizedName
24
+ from pip._vendor.packaging.version import LegacyVersion, Version
25
+
26
+ from pip._internal.exceptions import NoneMetadataError
27
+ from pip._internal.locations import site_packages, user_site
28
+ from pip._internal.models.direct_url import (
29
+ DIRECT_URL_METADATA_NAME,
30
+ DirectUrl,
31
+ DirectUrlValidationError,
32
+ )
33
+ from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.
34
+ from pip._internal.utils.egg_link import (
35
+ egg_link_path_from_location,
36
+ egg_link_path_from_sys_path,
37
+ )
38
+ from pip._internal.utils.misc import is_local, normalize_path
39
+ from pip._internal.utils.urls import url_to_path
40
+
41
+ if TYPE_CHECKING:
42
+ from typing import Protocol
43
+ else:
44
+ Protocol = object
45
+
46
+ DistributionVersion = Union[LegacyVersion, Version]
47
+
48
+ InfoPath = Union[str, pathlib.PurePosixPath]
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ class BaseEntryPoint(Protocol):
54
+ @property
55
+ def name(self) -> str:
56
+ raise NotImplementedError()
57
+
58
+ @property
59
+ def value(self) -> str:
60
+ raise NotImplementedError()
61
+
62
+ @property
63
+ def group(self) -> str:
64
+ raise NotImplementedError()
65
+
66
+
67
+ def _convert_installed_files_path(
68
+ entry: Tuple[str, ...],
69
+ info: Tuple[str, ...],
70
+ ) -> str:
71
+ """Convert a legacy installed-files.txt path into modern RECORD path.
72
+
73
+ The legacy format stores paths relative to the info directory, while the
74
+ modern format stores paths relative to the package root, e.g. the
75
+ site-packages directory.
76
+
77
+ :param entry: Path parts of the installed-files.txt entry.
78
+ :param info: Path parts of the egg-info directory relative to package root.
79
+ :returns: The converted entry.
80
+
81
+ For best compatibility with symlinks, this does not use ``abspath()`` or
82
+ ``Path.resolve()``, but tries to work with path parts:
83
+
84
+ 1. While ``entry`` starts with ``..``, remove the equal amounts of parts
85
+ from ``info``; if ``info`` is empty, start appending ``..`` instead.
86
+ 2. Join the two directly.
87
+ """
88
+ while entry and entry[0] == "..":
89
+ if not info or info[-1] == "..":
90
+ info += ("..",)
91
+ else:
92
+ info = info[:-1]
93
+ entry = entry[1:]
94
+ return str(pathlib.Path(*info, *entry))
95
+
96
+
97
+ class BaseDistribution(Protocol):
98
+ def __repr__(self) -> str:
99
+ return f"{self.raw_name} {self.version} ({self.location})"
100
+
101
+ def __str__(self) -> str:
102
+ return f"{self.raw_name} {self.version}"
103
+
104
+ @property
105
+ def location(self) -> Optional[str]:
106
+ """Where the distribution is loaded from.
107
+
108
+ A string value is not necessarily a filesystem path, since distributions
109
+ can be loaded from other sources, e.g. arbitrary zip archives. ``None``
110
+ means the distribution is created in-memory.
111
+
112
+ Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
113
+ this is a symbolic link, we want to preserve the relative path between
114
+ it and files in the distribution.
115
+ """
116
+ raise NotImplementedError()
117
+
118
+ @property
119
+ def editable_project_location(self) -> Optional[str]:
120
+ """The project location for editable distributions.
121
+
122
+ This is the directory where pyproject.toml or setup.py is located.
123
+ None if the distribution is not installed in editable mode.
124
+ """
125
+ # TODO: this property is relatively costly to compute, memoize it ?
126
+ direct_url = self.direct_url
127
+ if direct_url:
128
+ if direct_url.is_local_editable():
129
+ return url_to_path(direct_url.url)
130
+ else:
131
+ # Search for an .egg-link file by walking sys.path, as it was
132
+ # done before by dist_is_editable().
133
+ egg_link_path = egg_link_path_from_sys_path(self.raw_name)
134
+ if egg_link_path:
135
+ # TODO: get project location from second line of egg_link file
136
+ # (https://github.com/pypa/pip/issues/10243)
137
+ return self.location
138
+ return None
139
+
140
+ @property
141
+ def installed_location(self) -> Optional[str]:
142
+ """The distribution's "installed" location.
143
+
144
+ This should generally be a ``site-packages`` directory. This is
145
+ usually ``dist.location``, except for legacy develop-installed packages,
146
+ where ``dist.location`` is the source code location, and this is where
147
+ the ``.egg-link`` file is.
148
+
149
+ The returned location is normalized (in particular, with symlinks removed).
150
+ """
151
+ egg_link = egg_link_path_from_location(self.raw_name)
152
+ if egg_link:
153
+ location = egg_link
154
+ elif self.location:
155
+ location = self.location
156
+ else:
157
+ return None
158
+ return normalize_path(location)
159
+
160
+ @property
161
+ def info_location(self) -> Optional[str]:
162
+ """Location of the .[egg|dist]-info directory or file.
163
+
164
+ Similarly to ``location``, a string value is not necessarily a
165
+ filesystem path. ``None`` means the distribution is created in-memory.
166
+
167
+ For a modern .dist-info installation on disk, this should be something
168
+ like ``{location}/{raw_name}-{version}.dist-info``.
169
+
170
+ Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
171
+ this is a symbolic link, we want to preserve the relative path between
172
+ it and other files in the distribution.
173
+ """
174
+ raise NotImplementedError()
175
+
176
+ @property
177
+ def installed_by_distutils(self) -> bool:
178
+ """Whether this distribution is installed with legacy distutils format.
179
+
180
+ A distribution installed with "raw" distutils not patched by setuptools
181
+ uses one single file at ``info_location`` to store metadata. We need to
182
+ treat this specially on uninstallation.
183
+ """
184
+ info_location = self.info_location
185
+ if not info_location:
186
+ return False
187
+ return pathlib.Path(info_location).is_file()
188
+
189
+ @property
190
+ def installed_as_egg(self) -> bool:
191
+ """Whether this distribution is installed as an egg.
192
+
193
+ This usually indicates the distribution was installed by (older versions
194
+ of) easy_install.
195
+ """
196
+ location = self.location
197
+ if not location:
198
+ return False
199
+ return location.endswith(".egg")
200
+
201
+ @property
202
+ def installed_with_setuptools_egg_info(self) -> bool:
203
+ """Whether this distribution is installed with the ``.egg-info`` format.
204
+
205
+ This usually indicates the distribution was installed with setuptools
206
+ with an old pip version or with ``single-version-externally-managed``.
207
+
208
+ Note that this ensure the metadata store is a directory. distutils can
209
+ also installs an ``.egg-info``, but as a file, not a directory. This
210
+ property is *False* for that case. Also see ``installed_by_distutils``.
211
+ """
212
+ info_location = self.info_location
213
+ if not info_location:
214
+ return False
215
+ if not info_location.endswith(".egg-info"):
216
+ return False
217
+ return pathlib.Path(info_location).is_dir()
218
+
219
+ @property
220
+ def installed_with_dist_info(self) -> bool:
221
+ """Whether this distribution is installed with the "modern format".
222
+
223
+ This indicates a "modern" installation, e.g. storing metadata in the
224
+ ``.dist-info`` directory. This applies to installations made by
225
+ setuptools (but through pip, not directly), or anything using the
226
+ standardized build backend interface (PEP 517).
227
+ """
228
+ info_location = self.info_location
229
+ if not info_location:
230
+ return False
231
+ if not info_location.endswith(".dist-info"):
232
+ return False
233
+ return pathlib.Path(info_location).is_dir()
234
+
235
+ @property
236
+ def canonical_name(self) -> NormalizedName:
237
+ raise NotImplementedError()
238
+
239
+ @property
240
+ def version(self) -> DistributionVersion:
241
+ raise NotImplementedError()
242
+
243
+ @property
244
+ def setuptools_filename(self) -> str:
245
+ """Convert a project name to its setuptools-compatible filename.
246
+
247
+ This is a copy of ``pkg_resources.to_filename()`` for compatibility.
248
+ """
249
+ return self.raw_name.replace("-", "_")
250
+
251
+ @property
252
+ def direct_url(self) -> Optional[DirectUrl]:
253
+ """Obtain a DirectUrl from this distribution.
254
+
255
+ Returns None if the distribution has no `direct_url.json` metadata,
256
+ or if `direct_url.json` is invalid.
257
+ """
258
+ try:
259
+ content = self.read_text(DIRECT_URL_METADATA_NAME)
260
+ except FileNotFoundError:
261
+ return None
262
+ try:
263
+ return DirectUrl.from_json(content)
264
+ except (
265
+ UnicodeDecodeError,
266
+ json.JSONDecodeError,
267
+ DirectUrlValidationError,
268
+ ) as e:
269
+ logger.warning(
270
+ "Error parsing %s for %s: %s",
271
+ DIRECT_URL_METADATA_NAME,
272
+ self.canonical_name,
273
+ e,
274
+ )
275
+ return None
276
+
277
+ @property
278
+ def installer(self) -> str:
279
+ try:
280
+ installer_text = self.read_text("INSTALLER")
281
+ except (OSError, ValueError, NoneMetadataError):
282
+ return "" # Fail silently if the installer file cannot be read.
283
+ for line in installer_text.splitlines():
284
+ cleaned_line = line.strip()
285
+ if cleaned_line:
286
+ return cleaned_line
287
+ return ""
288
+
289
+ @property
290
+ def editable(self) -> bool:
291
+ return bool(self.editable_project_location)
292
+
293
+ @property
294
+ def local(self) -> bool:
295
+ """If distribution is installed in the current virtual environment.
296
+
297
+ Always True if we're not in a virtualenv.
298
+ """
299
+ if self.installed_location is None:
300
+ return False
301
+ return is_local(self.installed_location)
302
+
303
+ @property
304
+ def in_usersite(self) -> bool:
305
+ if self.installed_location is None or user_site is None:
306
+ return False
307
+ return self.installed_location.startswith(normalize_path(user_site))
308
+
309
+ @property
310
+ def in_site_packages(self) -> bool:
311
+ if self.installed_location is None or site_packages is None:
312
+ return False
313
+ return self.installed_location.startswith(normalize_path(site_packages))
314
+
315
+ def is_file(self, path: InfoPath) -> bool:
316
+ """Check whether an entry in the info directory is a file."""
317
+ raise NotImplementedError()
318
+
319
+ def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
320
+ """Iterate through a directory in the info directory.
321
+
322
+ Each item yielded would be a path relative to the info directory.
323
+
324
+ :raise FileNotFoundError: If ``name`` does not exist in the directory.
325
+ :raise NotADirectoryError: If ``name`` does not point to a directory.
326
+ """
327
+ raise NotImplementedError()
328
+
329
+ def read_text(self, path: InfoPath) -> str:
330
+ """Read a file in the info directory.
331
+
332
+ :raise FileNotFoundError: If ``name`` does not exist in the directory.
333
+ :raise NoneMetadataError: If ``name`` exists in the info directory, but
334
+ cannot be read.
335
+ """
336
+ raise NotImplementedError()
337
+
338
+ def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
339
+ raise NotImplementedError()
340
+
341
+ @property
342
+ def metadata(self) -> email.message.Message:
343
+ """Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
344
+
345
+ This should return an empty message if the metadata file is unavailable.
346
+
347
+ :raises NoneMetadataError: If the metadata file is available, but does
348
+ not contain valid metadata.
349
+ """
350
+ raise NotImplementedError()
351
+
352
+ @property
353
+ def metadata_version(self) -> Optional[str]:
354
+ """Value of "Metadata-Version:" in distribution metadata, if available."""
355
+ return self.metadata.get("Metadata-Version")
356
+
357
+ @property
358
+ def raw_name(self) -> str:
359
+ """Value of "Name:" in distribution metadata."""
360
+ # The metadata should NEVER be missing the Name: key, but if it somehow
361
+ # does, fall back to the known canonical name.
362
+ return self.metadata.get("Name", self.canonical_name)
363
+
364
+ @property
365
+ def requires_python(self) -> SpecifierSet:
366
+ """Value of "Requires-Python:" in distribution metadata.
367
+
368
+ If the key does not exist or contains an invalid value, an empty
369
+ SpecifierSet should be returned.
370
+ """
371
+ value = self.metadata.get("Requires-Python")
372
+ if value is None:
373
+ return SpecifierSet()
374
+ try:
375
+ # Convert to str to satisfy the type checker; this can be a Header object.
376
+ spec = SpecifierSet(str(value))
377
+ except InvalidSpecifier as e:
378
+ message = "Package %r has an invalid Requires-Python: %s"
379
+ logger.warning(message, self.raw_name, e)
380
+ return SpecifierSet()
381
+ return spec
382
+
383
+ def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
384
+ """Dependencies of this distribution.
385
+
386
+ For modern .dist-info distributions, this is the collection of
387
+ "Requires-Dist:" entries in distribution metadata.
388
+ """
389
+ raise NotImplementedError()
390
+
391
+ def iter_provided_extras(self) -> Iterable[str]:
392
+ """Extras provided by this distribution.
393
+
394
+ For modern .dist-info distributions, this is the collection of
395
+ "Provides-Extra:" entries in distribution metadata.
396
+ """
397
+ raise NotImplementedError()
398
+
399
+ def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:
400
+ try:
401
+ text = self.read_text("RECORD")
402
+ except FileNotFoundError:
403
+ return None
404
+ # This extra Path-str cast normalizes entries.
405
+ return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
406
+
407
+ def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:
408
+ try:
409
+ text = self.read_text("installed-files.txt")
410
+ except FileNotFoundError:
411
+ return None
412
+ paths = (p for p in text.splitlines(keepends=False) if p)
413
+ root = self.location
414
+ info = self.info_location
415
+ if root is None or info is None:
416
+ return paths
417
+ try:
418
+ info_rel = pathlib.Path(info).relative_to(root)
419
+ except ValueError: # info is not relative to root.
420
+ return paths
421
+ if not info_rel.parts: # info *is* root.
422
+ return paths
423
+ return (
424
+ _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
425
+ for p in paths
426
+ )
427
+
428
+ def iter_declared_entries(self) -> Optional[Iterator[str]]:
429
+ """Iterate through file entires declared in this distribution.
430
+
431
+ For modern .dist-info distributions, this is the files listed in the
432
+ ``RECORD`` metadata file. For legacy setuptools distributions, this
433
+ comes from ``installed-files.txt``, with entries normalized to be
434
+ compatible with the format used by ``RECORD``.
435
+
436
+ :return: An iterator for listed entries, or None if the distribution
437
+ contains neither ``RECORD`` nor ``installed-files.txt``.
438
+ """
439
+ return (
440
+ self._iter_declared_entries_from_record()
441
+ or self._iter_declared_entries_from_legacy()
442
+ )
443
+
444
+
445
+ class BaseEnvironment:
446
+ """An environment containing distributions to introspect."""
447
+
448
+ @classmethod
449
+ def default(cls) -> "BaseEnvironment":
450
+ raise NotImplementedError()
451
+
452
+ @classmethod
453
+ def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment":
454
+ raise NotImplementedError()
455
+
456
+ def get_distribution(self, name: str) -> Optional["BaseDistribution"]:
457
+ """Given a requirement name, return the installed distributions.
458
+
459
+ The name may not be normalized. The implementation must canonicalize
460
+ it for lookup.
461
+ """
462
+ raise NotImplementedError()
463
+
464
+ def _iter_distributions(self) -> Iterator["BaseDistribution"]:
465
+ """Iterate through installed distributions.
466
+
467
+ This function should be implemented by subclass, but never called
468
+ directly. Use the public ``iter_distribution()`` instead, which
469
+ implements additional logic to make sure the distributions are valid.
470
+ """
471
+ raise NotImplementedError()
472
+
473
+ def iter_distributions(self) -> Iterator["BaseDistribution"]:
474
+ """Iterate through installed distributions."""
475
+ for dist in self._iter_distributions():
476
+ # Make sure the distribution actually comes from a valid Python
477
+ # packaging distribution. Pip's AdjacentTempDirectory leaves folders
478
+ # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
479
+ # valid project name pattern is taken from PEP 508.
480
+ project_name_valid = re.match(
481
+ r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
482
+ dist.canonical_name,
483
+ flags=re.IGNORECASE,
484
+ )
485
+ if not project_name_valid:
486
+ logger.warning(
487
+ "Ignoring invalid distribution %s (%s)",
488
+ dist.canonical_name,
489
+ dist.location,
490
+ )
491
+ continue
492
+ yield dist
493
+
494
+ def iter_installed_distributions(
495
+ self,
496
+ local_only: bool = True,
497
+ skip: Container[str] = stdlib_pkgs,
498
+ include_editables: bool = True,
499
+ editables_only: bool = False,
500
+ user_only: bool = False,
501
+ ) -> Iterator[BaseDistribution]:
502
+ """Return a list of installed distributions.
503
+
504
+ :param local_only: If True (default), only return installations
505
+ local to the current virtualenv, if in a virtualenv.
506
+ :param skip: An iterable of canonicalized project names to ignore;
507
+ defaults to ``stdlib_pkgs``.
508
+ :param include_editables: If False, don't report editables.
509
+ :param editables_only: If True, only report editables.
510
+ :param user_only: If True, only report installations in the user
511
+ site directory.
512
+ """
513
+ it = self.iter_distributions()
514
+ if local_only:
515
+ it = (d for d in it if d.local)
516
+ if not include_editables:
517
+ it = (d for d in it if not d.editable)
518
+ if editables_only:
519
+ it = (d for d in it if d.editable)
520
+ if user_only:
521
+ it = (d for d in it if d.in_usersite)
522
+ return (d for d in it if d.canonical_name not in skip)
523
+
524
+
525
+ class Wheel(Protocol):
526
+ location: str
527
+
528
+ def as_zipfile(self) -> zipfile.ZipFile:
529
+ raise NotImplementedError()
530
+
531
+
532
+ class FilesystemWheel(Wheel):
533
+ def __init__(self, location: str) -> None:
534
+ self.location = location
535
+
536
+ def as_zipfile(self) -> zipfile.ZipFile:
537
+ return zipfile.ZipFile(self.location, allowZip64=True)
538
+
539
+
540
+ class MemoryWheel(Wheel):
541
+ def __init__(self, location: str, stream: IO[bytes]) -> None:
542
+ self.location = location
543
+ self.stream = stream
544
+
545
+ def as_zipfile(self) -> zipfile.ZipFile:
546
+ return zipfile.ZipFile(self.stream, allowZip64=True)
venv/lib/python3.10/site-packages/pip/_internal/metadata/pkg_resources.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import email.message
2
+ import email.parser
3
+ import logging
4
+ import os
5
+ import pathlib
6
+ import zipfile
7
+ from typing import Collection, Iterable, Iterator, List, Mapping, NamedTuple, Optional
8
+
9
+ from pip._vendor import pkg_resources
10
+ from pip._vendor.packaging.requirements import Requirement
11
+ from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
12
+ from pip._vendor.packaging.version import parse as parse_version
13
+
14
+ from pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel
15
+ from pip._internal.utils.misc import display_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 WheelMetadata:
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) -> "Distribution":
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_wheel(cls, wheel: Wheel, name: str) -> "Distribution":
97
+ """Load the distribution from a given wheel.
98
+
99
+ :raises InvalidWheel: Whenever loading of the wheel causes a
100
+ :py:exc:`zipfile.BadZipFile` exception to be thrown.
101
+ :raises UnsupportedWheel: If the wheel is a valid zip, but malformed
102
+ internally.
103
+ """
104
+ try:
105
+ with wheel.as_zipfile() as zf:
106
+ info_dir, _ = parse_wheel(zf, name)
107
+ metadata_text = {
108
+ path.split("/", 1)[-1]: read_wheel_metadata_file(zf, path)
109
+ for path in zf.namelist()
110
+ if path.startswith(f"{info_dir}/")
111
+ }
112
+ except zipfile.BadZipFile as e:
113
+ raise InvalidWheel(wheel.location, name) from e
114
+ except UnsupportedWheel as e:
115
+ raise UnsupportedWheel(f"{name} has an invalid wheel, {e}")
116
+ dist = pkg_resources.DistInfoDistribution(
117
+ location=wheel.location,
118
+ metadata=WheelMetadata(metadata_text, wheel.location),
119
+ project_name=name,
120
+ )
121
+ return cls(dist)
122
+
123
+ @property
124
+ def location(self) -> Optional[str]:
125
+ return self._dist.location
126
+
127
+ @property
128
+ def info_location(self) -> Optional[str]:
129
+ return self._dist.egg_info
130
+
131
+ @property
132
+ def installed_by_distutils(self) -> bool:
133
+ # A distutils-installed distribution is provided by FileMetadata. This
134
+ # provider has a "path" attribute not present anywhere else. Not the
135
+ # best introspection logic, but pip has been doing this for a long time.
136
+ try:
137
+ return bool(self._dist._provider.path)
138
+ except AttributeError:
139
+ return False
140
+
141
+ @property
142
+ def canonical_name(self) -> NormalizedName:
143
+ return canonicalize_name(self._dist.project_name)
144
+
145
+ @property
146
+ def version(self) -> DistributionVersion:
147
+ return parse_version(self._dist.version)
148
+
149
+ def is_file(self, path: InfoPath) -> bool:
150
+ return self._dist.has_metadata(str(path))
151
+
152
+ def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
153
+ name = str(path)
154
+ if not self._dist.has_metadata(name):
155
+ raise FileNotFoundError(name)
156
+ if not self._dist.isdir(name):
157
+ raise NotADirectoryError(name)
158
+ for child in self._dist.metadata_listdir(name):
159
+ yield pathlib.PurePosixPath(path, child)
160
+
161
+ def read_text(self, path: InfoPath) -> str:
162
+ name = str(path)
163
+ if not self._dist.has_metadata(name):
164
+ raise FileNotFoundError(name)
165
+ content = self._dist.get_metadata(name)
166
+ if content is None:
167
+ raise NoneMetadataError(self, name)
168
+ return content
169
+
170
+ def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
171
+ for group, entries in self._dist.get_entry_map().items():
172
+ for name, entry_point in entries.items():
173
+ name, _, value = str(entry_point).partition("=")
174
+ yield EntryPoint(name=name.strip(), value=value.strip(), group=group)
175
+
176
+ @property
177
+ def metadata(self) -> email.message.Message:
178
+ """
179
+ :raises NoneMetadataError: if the distribution reports `has_metadata()`
180
+ True but `get_metadata()` returns None.
181
+ """
182
+ if isinstance(self._dist, pkg_resources.DistInfoDistribution):
183
+ metadata_name = "METADATA"
184
+ else:
185
+ metadata_name = "PKG-INFO"
186
+ try:
187
+ metadata = self.read_text(metadata_name)
188
+ except FileNotFoundError:
189
+ if self.location:
190
+ displaying_path = display_path(self.location)
191
+ else:
192
+ displaying_path = repr(self.location)
193
+ logger.warning("No metadata found in %s", displaying_path)
194
+ metadata = ""
195
+ feed_parser = email.parser.FeedParser()
196
+ feed_parser.feed(metadata)
197
+ return feed_parser.close()
198
+
199
+ def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
200
+ if extras: # pkg_resources raises on invalid extras, so we sanitize.
201
+ extras = frozenset(extras).intersection(self._dist.extras)
202
+ return self._dist.requires(extras)
203
+
204
+ def iter_provided_extras(self) -> Iterable[str]:
205
+ return self._dist.extras
206
+
207
+
208
+ class Environment(BaseEnvironment):
209
+ def __init__(self, ws: pkg_resources.WorkingSet) -> None:
210
+ self._ws = ws
211
+
212
+ @classmethod
213
+ def default(cls) -> BaseEnvironment:
214
+ return cls(pkg_resources.working_set)
215
+
216
+ @classmethod
217
+ def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:
218
+ return cls(pkg_resources.WorkingSet(paths))
219
+
220
+ def _search_distribution(self, name: str) -> Optional[BaseDistribution]:
221
+ """Find a distribution matching the ``name`` in the environment.
222
+
223
+ This searches from *all* distributions available in the environment, to
224
+ match the behavior of ``pkg_resources.get_distribution()``.
225
+ """
226
+ canonical_name = canonicalize_name(name)
227
+ for dist in self.iter_distributions():
228
+ if dist.canonical_name == canonical_name:
229
+ return dist
230
+ return None
231
+
232
+ def get_distribution(self, name: str) -> Optional[BaseDistribution]:
233
+ # Search the distribution by looking through the working set.
234
+ dist = self._search_distribution(name)
235
+ if dist:
236
+ return dist
237
+
238
+ # If distribution could not be found, call working_set.require to
239
+ # update the working set, and try to find the distribution again.
240
+ # This might happen for e.g. when you install a package twice, once
241
+ # using setup.py develop and again using setup.py install. Now when
242
+ # running pip uninstall twice, the package gets removed from the
243
+ # working set in the first uninstall, so we have to populate the
244
+ # working set again so that pip knows about it and the packages gets
245
+ # picked up and is successfully uninstalled the second time too.
246
+ try:
247
+ # We didn't pass in any version specifiers, so this can never
248
+ # raise pkg_resources.VersionConflict.
249
+ self._ws.require(name)
250
+ except pkg_resources.DistributionNotFound:
251
+ return None
252
+ return self._search_distribution(name)
253
+
254
+ def _iter_distributions(self) -> Iterator[BaseDistribution]:
255
+ for dist in self._ws:
256
+ yield Distribution(dist)
venv/lib/python3.10/site-packages/pip/_internal/network/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Contains purely network-related utilities.
2
+ """
venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/auth.cpython-310.pyc ADDED
Binary file (7.51 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/cache.cpython-310.pyc ADDED
Binary file (2.93 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-310.pyc ADDED
Binary file (8.4 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/session.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/network/__pycache__/xmlrpc.cpython-310.pyc ADDED
Binary file (2.06 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/network/auth.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Network Authentication Helpers
2
+
3
+ Contains interface (MultiDomainBasicAuth) and associated glue code for
4
+ providing credentials in the context of network requests.
5
+ """
6
+
7
+ import urllib.parse
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth
11
+ from pip._vendor.requests.models import Request, Response
12
+ from pip._vendor.requests.utils import get_netrc_auth
13
+
14
+ from pip._internal.utils.logging import getLogger
15
+ from pip._internal.utils.misc import (
16
+ ask,
17
+ ask_input,
18
+ ask_password,
19
+ remove_auth_from_url,
20
+ split_auth_netloc_from_url,
21
+ )
22
+ from pip._internal.vcs.versioncontrol import AuthInfo
23
+
24
+ logger = getLogger(__name__)
25
+
26
+ Credentials = Tuple[str, str, str]
27
+
28
+ try:
29
+ import keyring
30
+ except ImportError:
31
+ keyring = None # type: ignore[assignment]
32
+ except Exception as exc:
33
+ logger.warning(
34
+ "Keyring is skipped due to an exception: %s",
35
+ str(exc),
36
+ )
37
+ keyring = None # type: ignore[assignment]
38
+
39
+
40
+ def get_keyring_auth(url: Optional[str], username: Optional[str]) -> Optional[AuthInfo]:
41
+ """Return the tuple auth for a given url from keyring."""
42
+ global keyring
43
+ if not url or not keyring:
44
+ return None
45
+
46
+ try:
47
+ try:
48
+ get_credential = keyring.get_credential
49
+ except AttributeError:
50
+ pass
51
+ else:
52
+ logger.debug("Getting credentials from keyring for %s", url)
53
+ cred = get_credential(url, username)
54
+ if cred is not None:
55
+ return cred.username, cred.password
56
+ return None
57
+
58
+ if username:
59
+ logger.debug("Getting password from keyring for %s", url)
60
+ password = keyring.get_password(url, username)
61
+ if password:
62
+ return username, password
63
+
64
+ except Exception as exc:
65
+ logger.warning(
66
+ "Keyring is skipped due to an exception: %s",
67
+ str(exc),
68
+ )
69
+ keyring = None # type: ignore[assignment]
70
+ return None
71
+
72
+
73
+ class MultiDomainBasicAuth(AuthBase):
74
+ def __init__(
75
+ self, prompting: bool = True, index_urls: Optional[List[str]] = None
76
+ ) -> None:
77
+ self.prompting = prompting
78
+ self.index_urls = index_urls
79
+ self.passwords: Dict[str, AuthInfo] = {}
80
+ # When the user is prompted to enter credentials and keyring is
81
+ # available, we will offer to save them. If the user accepts,
82
+ # this value is set to the credentials they entered. After the
83
+ # request authenticates, the caller should call
84
+ # ``save_credentials`` to save these.
85
+ self._credentials_to_save: Optional[Credentials] = None
86
+
87
+ def _get_index_url(self, url: str) -> Optional[str]:
88
+ """Return the original index URL matching the requested URL.
89
+
90
+ Cached or dynamically generated credentials may work against
91
+ the original index URL rather than just the netloc.
92
+
93
+ The provided url should have had its username and password
94
+ removed already. If the original index url had credentials then
95
+ they will be included in the return value.
96
+
97
+ Returns None if no matching index was found, or if --no-index
98
+ was specified by the user.
99
+ """
100
+ if not url or not self.index_urls:
101
+ return None
102
+
103
+ for u in self.index_urls:
104
+ prefix = remove_auth_from_url(u).rstrip("/") + "/"
105
+ if url.startswith(prefix):
106
+ return u
107
+ return None
108
+
109
+ def _get_new_credentials(
110
+ self,
111
+ original_url: str,
112
+ allow_netrc: bool = True,
113
+ allow_keyring: bool = False,
114
+ ) -> AuthInfo:
115
+ """Find and return credentials for the specified URL."""
116
+ # Split the credentials and netloc from the url.
117
+ url, netloc, url_user_password = split_auth_netloc_from_url(
118
+ original_url,
119
+ )
120
+
121
+ # Start with the credentials embedded in the url
122
+ username, password = url_user_password
123
+ if username is not None and password is not None:
124
+ logger.debug("Found credentials in url for %s", netloc)
125
+ return url_user_password
126
+
127
+ # Find a matching index url for this request
128
+ index_url = self._get_index_url(url)
129
+ if index_url:
130
+ # Split the credentials from the url.
131
+ index_info = split_auth_netloc_from_url(index_url)
132
+ if index_info:
133
+ index_url, _, index_url_user_password = index_info
134
+ logger.debug("Found index url %s", index_url)
135
+
136
+ # If an index URL was found, try its embedded credentials
137
+ if index_url and index_url_user_password[0] is not None:
138
+ username, password = index_url_user_password
139
+ if username is not None and password is not None:
140
+ logger.debug("Found credentials in index url for %s", netloc)
141
+ return index_url_user_password
142
+
143
+ # Get creds from netrc if we still don't have them
144
+ if allow_netrc:
145
+ netrc_auth = get_netrc_auth(original_url)
146
+ if netrc_auth:
147
+ logger.debug("Found credentials in netrc for %s", netloc)
148
+ return netrc_auth
149
+
150
+ # If we don't have a password and keyring is available, use it.
151
+ if allow_keyring:
152
+ # The index url is more specific than the netloc, so try it first
153
+ # fmt: off
154
+ kr_auth = (
155
+ get_keyring_auth(index_url, username) or
156
+ get_keyring_auth(netloc, username)
157
+ )
158
+ # fmt: on
159
+ if kr_auth:
160
+ logger.debug("Found credentials in keyring for %s", netloc)
161
+ return kr_auth
162
+
163
+ return username, password
164
+
165
+ def _get_url_and_credentials(
166
+ self, original_url: str
167
+ ) -> Tuple[str, Optional[str], Optional[str]]:
168
+ """Return the credentials to use for the provided URL.
169
+
170
+ If allowed, netrc and keyring may be used to obtain the
171
+ correct credentials.
172
+
173
+ Returns (url_without_credentials, username, password). Note
174
+ that even if the original URL contains credentials, this
175
+ function may return a different username and password.
176
+ """
177
+ url, netloc, _ = split_auth_netloc_from_url(original_url)
178
+
179
+ # Try to get credentials from original url
180
+ username, password = self._get_new_credentials(original_url)
181
+
182
+ # If credentials not found, use any stored credentials for this netloc.
183
+ # Do this if either the username or the password is missing.
184
+ # This accounts for the situation in which the user has specified
185
+ # the username in the index url, but the password comes from keyring.
186
+ if (username is None or password is None) and netloc in self.passwords:
187
+ un, pw = self.passwords[netloc]
188
+ # It is possible that the cached credentials are for a different username,
189
+ # in which case the cache should be ignored.
190
+ if username is None or username == un:
191
+ username, password = un, pw
192
+
193
+ if username is not None or password is not None:
194
+ # Convert the username and password if they're None, so that
195
+ # this netloc will show up as "cached" in the conditional above.
196
+ # Further, HTTPBasicAuth doesn't accept None, so it makes sense to
197
+ # cache the value that is going to be used.
198
+ username = username or ""
199
+ password = password or ""
200
+
201
+ # Store any acquired credentials.
202
+ self.passwords[netloc] = (username, password)
203
+
204
+ assert (
205
+ # Credentials were found
206
+ (username is not None and password is not None)
207
+ # Credentials were not found
208
+ or (username is None and password is None)
209
+ ), f"Could not load credentials from url: {original_url}"
210
+
211
+ return url, username, password
212
+
213
+ def __call__(self, req: Request) -> Request:
214
+ # Get credentials for this request
215
+ url, username, password = self._get_url_and_credentials(req.url)
216
+
217
+ # Set the url of the request to the url without any credentials
218
+ req.url = url
219
+
220
+ if username is not None and password is not None:
221
+ # Send the basic auth with this request
222
+ req = HTTPBasicAuth(username, password)(req)
223
+
224
+ # Attach a hook to handle 401 responses
225
+ req.register_hook("response", self.handle_401)
226
+
227
+ return req
228
+
229
+ # Factored out to allow for easy patching in tests
230
+ def _prompt_for_password(
231
+ self, netloc: str
232
+ ) -> Tuple[Optional[str], Optional[str], bool]:
233
+ username = ask_input(f"User for {netloc}: ")
234
+ if not username:
235
+ return None, None, False
236
+ auth = get_keyring_auth(netloc, username)
237
+ if auth and auth[0] is not None and auth[1] is not None:
238
+ return auth[0], auth[1], False
239
+ password = ask_password("Password: ")
240
+ return username, password, True
241
+
242
+ # Factored out to allow for easy patching in tests
243
+ def _should_save_password_to_keyring(self) -> bool:
244
+ if not keyring:
245
+ return False
246
+ return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y"
247
+
248
+ def handle_401(self, resp: Response, **kwargs: Any) -> Response:
249
+ # We only care about 401 responses, anything else we want to just
250
+ # pass through the actual response
251
+ if resp.status_code != 401:
252
+ return resp
253
+
254
+ # We are not able to prompt the user so simply return the response
255
+ if not self.prompting:
256
+ return resp
257
+
258
+ parsed = urllib.parse.urlparse(resp.url)
259
+
260
+ # Query the keyring for credentials:
261
+ username, password = self._get_new_credentials(
262
+ resp.url,
263
+ allow_netrc=False,
264
+ allow_keyring=True,
265
+ )
266
+
267
+ # Prompt the user for a new username and password
268
+ save = False
269
+ if not username and not password:
270
+ username, password, save = self._prompt_for_password(parsed.netloc)
271
+
272
+ # Store the new username and password to use for future requests
273
+ self._credentials_to_save = None
274
+ if username is not None and password is not None:
275
+ self.passwords[parsed.netloc] = (username, password)
276
+
277
+ # Prompt to save the password to keyring
278
+ if save and self._should_save_password_to_keyring():
279
+ self._credentials_to_save = (parsed.netloc, username, password)
280
+
281
+ # Consume content and release the original connection to allow our new
282
+ # request to reuse the same one.
283
+ resp.content
284
+ resp.raw.release_conn()
285
+
286
+ # Add our new username and password to the request
287
+ req = HTTPBasicAuth(username or "", password or "")(resp.request)
288
+ req.register_hook("response", self.warn_on_401)
289
+
290
+ # On successful request, save the credentials that were used to
291
+ # keyring. (Note that if the user responded "no" above, this member
292
+ # is not set and nothing will be saved.)
293
+ if self._credentials_to_save:
294
+ req.register_hook("response", self.save_credentials)
295
+
296
+ # Send our new request
297
+ new_resp = resp.connection.send(req, **kwargs)
298
+ new_resp.history.append(resp)
299
+
300
+ return new_resp
301
+
302
+ def warn_on_401(self, resp: Response, **kwargs: Any) -> None:
303
+ """Response callback to warn about incorrect credentials."""
304
+ if resp.status_code == 401:
305
+ logger.warning(
306
+ "401 Error, Credentials not correct for %s",
307
+ resp.request.url,
308
+ )
309
+
310
+ def save_credentials(self, resp: Response, **kwargs: Any) -> None:
311
+ """Response callback to save credentials on success."""
312
+ assert keyring is not None, "should never reach here without keyring"
313
+ if not keyring:
314
+ return
315
+
316
+ creds = self._credentials_to_save
317
+ self._credentials_to_save = None
318
+ if creds and resp.status_code < 400:
319
+ try:
320
+ logger.info("Saving credentials to keyring")
321
+ keyring.set_password(*creds)
322
+ except Exception:
323
+ logger.exception("Failed to save credentials")
venv/lib/python3.10/site-packages/pip/_internal/network/download.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download files with progress indicators.
2
+ """
3
+ import cgi
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
+ _type, params = cgi.parse_header(content_disposition)
85
+ filename = params.get("filename")
86
+ if filename:
87
+ # We need to sanitize the filename to prevent directory traversal
88
+ # in case the filename contains ".." path parts.
89
+ filename = sanitize_content_filename(filename)
90
+ return filename or default_filename
91
+
92
+
93
+ def _get_http_response_filename(resp: Response, link: Link) -> str:
94
+ """Get an ideal filename from the given HTTP response, falling back to
95
+ the link filename if not provided.
96
+ """
97
+ filename = link.filename # fallback
98
+ # Have a look at the Content-Disposition header for a better guess
99
+ content_disposition = resp.headers.get("content-disposition")
100
+ if content_disposition:
101
+ filename = parse_content_disposition(content_disposition, filename)
102
+ ext: Optional[str] = splitext(filename)[1]
103
+ if not ext:
104
+ ext = mimetypes.guess_extension(resp.headers.get("content-type", ""))
105
+ if ext:
106
+ filename += ext
107
+ if not ext and link.url != resp.url:
108
+ ext = os.path.splitext(resp.url)[1]
109
+ if ext:
110
+ filename += ext
111
+ return filename
112
+
113
+
114
+ def _http_get_download(session: PipSession, link: Link) -> Response:
115
+ target_url = link.url.split("#", 1)[0]
116
+ resp = session.get(target_url, headers=HEADERS, stream=True)
117
+ raise_for_status(resp)
118
+ return resp
119
+
120
+
121
+ class Downloader:
122
+ def __init__(
123
+ self,
124
+ session: PipSession,
125
+ progress_bar: str,
126
+ ) -> None:
127
+ self._session = session
128
+ self._progress_bar = progress_bar
129
+
130
+ def __call__(self, link: Link, location: str) -> Tuple[str, str]:
131
+ """Download the file given by link into location."""
132
+ try:
133
+ resp = _http_get_download(self._session, link)
134
+ except NetworkConnectionError as e:
135
+ assert e.response is not None
136
+ logger.critical(
137
+ "HTTP error %s while getting %s", e.response.status_code, link
138
+ )
139
+ raise
140
+
141
+ filename = _get_http_response_filename(resp, link)
142
+ filepath = os.path.join(location, filename)
143
+
144
+ chunks = _prepare_download(resp, link, self._progress_bar)
145
+ with open(filepath, "wb") as content_file:
146
+ for chunk in chunks:
147
+ content_file.write(chunk)
148
+ content_type = resp.headers.get("Content-Type", "")
149
+ return filepath, content_type
150
+
151
+
152
+ class BatchDownloader:
153
+ def __init__(
154
+ self,
155
+ session: PipSession,
156
+ progress_bar: str,
157
+ ) -> None:
158
+ self._session = session
159
+ self._progress_bar = progress_bar
160
+
161
+ def __call__(
162
+ self, links: Iterable[Link], location: str
163
+ ) -> Iterable[Tuple[Link, Tuple[str, str]]]:
164
+ """Download the files given by links into location."""
165
+ for link in links:
166
+ try:
167
+ resp = _http_get_download(self._session, link)
168
+ except NetworkConnectionError as e:
169
+ assert e.response is not None
170
+ logger.critical(
171
+ "HTTP error %s while getting %s",
172
+ e.response.status_code,
173
+ link,
174
+ )
175
+ raise
176
+
177
+ filename = _get_http_response_filename(resp, link)
178
+ filepath = os.path.join(location, filename)
179
+
180
+ chunks = _prepare_download(resp, link, self._progress_bar)
181
+ with open(filepath, "wb") as content_file:
182
+ for chunk in chunks:
183
+ content_file.write(chunk)
184
+ content_type = resp.headers.get("Content-Type", "")
185
+ yield link, (filepath, content_type)
venv/lib/python3.10/site-packages/pip/_internal/network/utils.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Iterator
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
+ ) -> Iterator[bytes]:
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/python3.10/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/python3.10/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/check.cpython-310.pyc ADDED
Binary file (4.01 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/freeze.cpython-310.pyc ADDED
Binary file (6.19 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-310.pyc ADDED
Binary file (14.9 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (198 Bytes). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-310.pyc ADDED
Binary file (1.43 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-310.pyc ADDED
Binary file (1.22 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-310.pyc ADDED
Binary file (2.76 kB). View file
 
venv/lib/python3.10/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.pep517.wrappers import Pep517HookCaller
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: Pep517HookCaller, 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 Pep517HookCaller 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/python3.10/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.pep517.wrappers import Pep517HookCaller
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: Pep517HookCaller, 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 Pep517HookCaller 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/python3.10/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/python3.10/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.pep517.wrappers import Pep517HookCaller
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: Pep517HookCaller,
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/python3.10/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.pep517.wrappers import HookMissing, Pep517HookCaller
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: Pep517HookCaller,
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/python3.10/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/python3.10/site-packages/pip/_internal/operations/install/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """For modules related to installing packages.
2
+ """
venv/lib/python3.10/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (256 Bytes). View file
 
venv/lib/python3.10/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-310.pyc ADDED
Binary file (1.54 kB). View file