Debian Codegraph @

Lib/ensurepip/__init__.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import os
2 import subprocess
3 import sys
4 import sysconfig
5 import tempfile
6 from contextlib import nullcontext
7 from importlib import resources
8 from pathlib import Path
9 from shutil import copy2
10
11
12 __all__ = ["version", "bootstrap"]
13 _PIP_VERSION = "26.1.1"
14
15 # Directory of system wheel packages. Some Linux distribution packaging
16 # policies recommend against bundling dependencies. For example, Fedora
17 # installs wheel packages in the /usr/share/python-wheels/ directory and don't
18 # install the ensurepip._bundled package.
19 _pkg_dir = sysconfig.get_config_var('WHEEL_PKG_DIR')
20 if _pkg_dir:
21 _WHEEL_PKG_DIR = Path(_pkg_dir).resolve()
22 else:
23 _WHEEL_PKG_DIR = None
24
25
26 def _find_wheel_pkg_dir_pip():
27 if _WHEEL_PKG_DIR is None:
28 # NOTE: The compile-time `WHEEL_PKG_DIR` is unset so there is no place
29 # NOTE: for looking up the wheels.
30 return None
31
32 dist_matching_wheels = _WHEEL_PKG_DIR.glob('pip-*.whl')
33 try:
34 last_matching_dist_wheel = sorted(dist_matching_wheels)[-1]
35 except IndexError:
36 # NOTE: `WHEEL_PKG_DIR` does not contain any wheel files for `pip`.
37 return None
38
39 return nullcontext(last_matching_dist_wheel)
40
41
42 def _get_pip_whl_path_ctx():
43 # Prefer pip from the wheel package directory, if present.
44 if (alternative_pip_wheel_path := _find_wheel_pkg_dir_pip()) is not None:
45 return alternative_pip_wheel_path
46
47 return resources.as_file(
48 resources.files('ensurepip')
49 / '_bundled'
50 / f'pip-{_PIP_VERSION}-py3-none-any.whl'
51 )
52
53
54 def _get_pip_version():
55 with _get_pip_whl_path_ctx() as bundled_wheel_path:
56 wheel_name = bundled_wheel_path.name
57 return (
58 # Extract '21.2.4' from 'pip-21.2.4-py3-none-any.whl'
59 wheel_name.
60 removeprefix('pip-').
61 partition('-')[0]
62 )
63
64
65 def _run_pip(args, additional_paths=None):
66 # Run the bootstrapping in a subprocess to avoid leaking any state that happens
67 # after pip has executed. Particularly, this avoids the case when pip holds onto
68 # the files in *additional_paths*, preventing us to remove them at the end of the
69 # invocation.
70 code = f"""
71 import runpy
72 import sys
73 sys.path = {additional_paths or []} + sys.path
74 sys.argv[1:] = {args}
75 runpy.run_module("pip", run_name="__main__", alter_sys=True)
76 """
77
78 cmd = [
79 sys.executable,
80 '-W',
81 'ignore::DeprecationWarning',
82 '-c',
83 code,
84 ]
85 if sys.flags.isolated:
86 # run code in isolated mode if currently running isolated
87 cmd.insert(1, '-I')
88 return subprocess.run(cmd, check=True).returncode
89
90
91 def version():
92 """
93 Returns a string specifying the bundled version of pip.
94 """
95 return _get_pip_version()
96
97
98 def _disable_pip_configuration_settings():
99 # We deliberately ignore all pip environment variables
100 # when invoking pip
101 # See http://bugs.python.org/issue19734 for details
102 keys_to_remove = [k for k in os.environ if k.startswith("PIP_")]
103 for k in keys_to_remove:
104 del os.environ[k]
105 # We also ignore the settings in the default pip configuration file
106 # See http://bugs.python.org/issue20053 for details
107 os.environ['PIP_CONFIG_FILE'] = os.devnull
108
109
110 def bootstrap(*, root=None, upgrade=False, user=False,
111 altinstall=False, default_pip=False,
112 verbosity=0):
113 """
114 Bootstrap pip into the current Python installation (or the given root
115 directory).
116
117 Note that calling this function will alter both sys.path and os.environ.
118 """
119 # Discard the return value
120 _bootstrap(root=root, upgrade=upgrade, user=user,
121 altinstall=altinstall, default_pip=default_pip,
122 verbosity=verbosity)
123
124
125 def _bootstrap(*, root=None, upgrade=False, user=False,
126 altinstall=False, default_pip=False,
127 verbosity=0):
128 """
129 Bootstrap pip into the current Python installation (or the given root
130 directory). Returns pip command status code.
131
132 Note that calling this function will alter both sys.path and os.environ.
133 """
134 if altinstall and default_pip:
135 raise ValueError("Cannot use altinstall and default_pip together")
136
137 sys.audit("ensurepip.bootstrap", root)
138
139 _disable_pip_configuration_settings()
140
141 # By default, installing pip installs all of the
142 # following scripts (X.Y == running Python version):
143 #
144 # pip, pipX, pipX.Y
145 #
146 # pip 1.5+ allows ensurepip to request that some of those be left out
147 if altinstall:
148 # omit pip, pipX
149 os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
150 elif not default_pip:
151 # omit pip
152 os.environ["ENSUREPIP_OPTIONS"] = "install"
153
154 with tempfile.TemporaryDirectory() as tmpdir:
155 # Put our bundled wheels into a temporary directory and construct the
156 # additional paths that need added to sys.path
157 tmpdir_path = Path(tmpdir)
158 with _get_pip_whl_path_ctx() as bundled_wheel_path:
159 tmp_wheel_path = tmpdir_path / bundled_wheel_path.name
160 copy2(bundled_wheel_path, tmp_wheel_path)
161
162 # Construct the arguments to be passed to the pip command
163 args = ["install", "--no-cache-dir", "--no-index", "--find-links", tmpdir]
164 if root:
165 args += ["--root", root]
166 if upgrade:
167 args += ["--upgrade"]
168 if user:
169 args += ["--user"]
170 if verbosity:
171 args += ["-" + "v" * verbosity]
172
173 return _run_pip([*args, "pip"], [os.fsdecode(tmp_wheel_path)])
174
175
176 def _uninstall_helper(*, verbosity=0):
177 """Helper to support a clean default uninstall process on Windows
178
179 Note that calling this function may alter os.environ.
180 """
181 # Nothing to do if pip was never installed, or has been removed
182 try:
183 import pip
184 except ImportError:
185 return
186
187 # If the installed pip version doesn't match the available one,
188 # leave it alone
189 available_version = version()
190 if pip.__version__ != available_version:
191 print(f"ensurepip will only uninstall a matching version "
192 f"({pip.__version__!r} installed, "
193 f"{available_version!r} available)",
194 file=sys.stderr)
195 return
196
197 _disable_pip_configuration_settings()
198
199 # Construct the arguments to be passed to the pip command
200 args = ["uninstall", "-y", "--disable-pip-version-check"]
201 if verbosity:
202 args += ["-" + "v" * verbosity]
203
204 return _run_pip([*args, "pip"])
205
206
207 def _main(argv=None):
208 import argparse
209 parser = argparse.ArgumentParser(color=True)
210 parser.add_argument(
211 "--version",
212 action="version",
213 version="pip {}".format(version()),
214 help="Show the version of pip that is bundled with this Python.",
215 )
216 parser.add_argument(
217 "-v", "--verbose",
218 action="count",
219 default=0,
220 dest="verbosity",
221 help=("Give more output. Option is additive, and can be used up to 3 "
222 "times."),
223 )
224 parser.add_argument(
225 "-U", "--upgrade",
226 action="store_true",
227 default=False,
228 help="Upgrade pip and dependencies, even if already installed.",
229 )
230 parser.add_argument(
231 "--user",
232 action="store_true",
233 default=False,
234 help="Install using the user scheme.",
235 )
236 parser.add_argument(
237 "--root",
238 default=None,
239 help="Install everything relative to this alternate root directory.",
240 )
241 parser.add_argument(
242 "--altinstall",
243 action="store_true",
244 default=False,
245 help=("Make an alternate install, installing only the X.Y versioned "
246 "scripts (Default: pipX, pipX.Y)."),
247 )
248 parser.add_argument(
249 "--default-pip",
250 action="store_true",
251 default=False,
252 help=("Make a default pip install, installing the unqualified pip "
253 "in addition to the versioned scripts."),
254 )
255
256 args = parser.parse_args(argv)
257
258 return _bootstrap(
259 root=args.root,
260 upgrade=args.upgrade,
261 user=args.user,
262 verbosity=args.verbosity,
263 altinstall=args.altinstall,
264 default_pip=args.default_pip,
265 )