Debian Codegraph @

lib-python/3/ensurepip/__init__.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 import collections
2 import os
3 import os.path
4 import subprocess
5 import sys
6 import sysconfig
7 import tempfile
8 from importlib import resources
9
10
11 __all__ = ["version", "bootstrap"]
12 _PACKAGE_NAMES = ('setuptools', 'pip')
13 _SETUPTOOLS_VERSION = "79.0.1"
14 _PIP_VERSION = "24.0"
15 _PROJECTS = [
16 ("setuptools", _SETUPTOOLS_VERSION, "py3"),
17 ("pip", _PIP_VERSION, "py3"),
18 ]
19
20 # Packages bundled in ensurepip._bundled have wheel_name set.
21 # Packages from WHEEL_PKG_DIR have wheel_path set.
22 _Package = collections.namedtuple('Package',
23 ('version', 'wheel_name', 'wheel_path'))
24
25 # Directory of system wheel packages. Some Linux distribution packaging
26 # policies recommend against bundling dependencies. For example, Fedora
27 # installs wheel packages in the /usr/share/python-wheels/ directory and don't
28 # install the ensurepip._bundled package.
29 _WHEEL_PKG_DIR = sysconfig.get_config_var('WHEEL_PKG_DIR')
30
31
32 def _find_packages(path):
33 packages = {}
34 try:
35 filenames = os.listdir(path)
36 except OSError:
37 # Ignore: path doesn't exist or permission error
38 filenames = ()
39 # Make the code deterministic if a directory contains multiple wheel files
40 # of the same package, but don't attempt to implement correct version
41 # comparison since this case should not happen.
42 filenames = sorted(filenames)
43 for filename in filenames:
44 # filename is like 'pip-21.2.4-py3-none-any.whl'
45 if not filename.endswith(".whl"):
46 continue
47 for name in _PACKAGE_NAMES:
48 prefix = name + '-'
49 if filename.startswith(prefix):
50 break
51 else:
52 continue
53
54 # Extract '21.2.4' from 'pip-21.2.4-py3-none-any.whl'
55 version = filename.removeprefix(prefix).partition('-')[0]
56 wheel_path = os.path.join(path, filename)
57 packages[name] = _Package(version, None, wheel_path)
58 return packages
59
60
61 def _get_packages():
62 global _PACKAGES, _WHEEL_PKG_DIR
63 if _PACKAGES is not None:
64 return _PACKAGES
65
66 packages = {}
67 for name, version, py_tag in _PROJECTS:
68 wheel_name = f"{name}-{version}-{py_tag}-none-any.whl"
69 packages[name] = _Package(version, wheel_name, None)
70 if _WHEEL_PKG_DIR:
71 dir_packages = _find_packages(_WHEEL_PKG_DIR)
72 # only used the wheel package directory if all packages are found there
73 if all(name in dir_packages for name in _PACKAGE_NAMES):
74 packages = dir_packages
75 _PACKAGES = packages
76 return packages
77 _PACKAGES = None
78
79
•80 def _ensurepip_is_disabled_in_debian_for_system():
81 # Detect if ensurepip is being executed inside of a python-virtualenv
82 # environment and return early if so.
83 if hasattr(sys, 'real_prefix'):
84 return
85
86 # Detect if ensurepip is being executed inside of a stdlib venv
87 # environment and return early if so.
88 if sys.prefix != getattr(sys, "base_prefix", sys.prefix):
89 return
90
91 # If we've gotten here, then we are running inside of the system Python
92 # and we don't want to use ensurepip to install into the system Python
93 # so instead we'll redirect the user to using dpkg and apt-get.
94 print('''\
95 ensurepip is disabled in Debian/Ubuntu for the system python.
96
97 Python modules for the system python are usually handled by dpkg and apt-get.
98
99 apt-get install python3-<module name>
100
101 Install the python3-pip package to use pip itself. Using pip together
102 with the system python might have unexpected results for any system installed
103 module, so use it on your own risk, or make sure to only use it in virtual
104 environments.
105 ''')
106 sys.exit(1)
107
108
109 def _run_pip(args, additional_paths=None):
110 # Run the bootstrapping in a subprocess to avoid leaking any state that happens
111 # after pip has executed. Particularly, this avoids the case when pip holds onto
112 # the files in *additional_paths*, preventing us to remove them at the end of the
113 # invocation.
114 code = f"""
115 import runpy
116 import sys
117 sys.path = {additional_paths or []} + sys.path
118 sys.argv[1:] = {args}
119 runpy.run_module("pip", run_name="__main__", alter_sys=True)
120 """
121
122 cmd = [
123 sys.executable,
124 '-W',
125 'ignore::DeprecationWarning',
126 '-c',
127 code,
128 ]
129 if sys.flags.isolated:
130 # run code in isolated mode if currently running isolated
131 cmd.insert(1, '-I')
132 return subprocess.run(cmd, check=True).returncode
133
134
135 def version():
136 """
137 Returns a string specifying the bundled version of pip.
138 """
139 return _get_packages()['pip'].version
140
141
142 def _disable_pip_configuration_settings():
143 # We deliberately ignore all pip environment variables
144 # when invoking pip
145 # See http://bugs.python.org/issue19734 for details
146 keys_to_remove = [k for k in os.environ if k.startswith("PIP_")]
147 for k in keys_to_remove:
148 del os.environ[k]
149 # We also ignore the settings in the default pip configuration file
150 # See http://bugs.python.org/issue20053 for details
151 os.environ['PIP_CONFIG_FILE'] = os.devnull
152
153
154 def bootstrap(*, root=None, upgrade=False, user=False,
155 altinstall=False, default_pip=False,
156 verbosity=0):
157 """
158 Bootstrap pip into the current Python installation (or the given root
159 directory).
160
161 Note that calling this function will alter both sys.path and os.environ.
162 """
163 # Discard the return value
164 _bootstrap(root=root, upgrade=upgrade, user=user,
165 altinstall=altinstall, default_pip=default_pip,
166 verbosity=verbosity)
167
168
169 def _bootstrap(*, root=None, upgrade=False, user=False,
170 altinstall=False, default_pip=False,
171 verbosity=0):
172 """
173 Bootstrap pip into the current Python installation (or the given root
174 directory). Returns pip command status code.
175
176 Note that calling this function will alter both sys.path and os.environ.
177 """
•178
179 # Ensure that we are only running this inside of a virtual environment
180 # of some kind.
181 _ensurepip_is_disabled_in_debian_for_system()
182
183 if altinstall and default_pip:
184 raise ValueError("Cannot use altinstall and default_pip together")
185
186 sys.audit("ensurepip.bootstrap", root)
187
188 _disable_pip_configuration_settings()
189
190 # By default, installing pip and setuptools installs all of the
191 # following scripts (X.Y == running Python version):
192 #
193 # pip, pipX, pipX.Y, easy_install, easy_install-X.Y
194 #
195 # pip 1.5+ allows ensurepip to request that some of those be left out
196 if altinstall:
197 # omit pip, pipX and easy_install
198 os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
199 elif not default_pip:
200 # omit pip and easy_install
201 os.environ["ENSUREPIP_OPTIONS"] = "install"
202
203 with tempfile.TemporaryDirectory() as tmpdir:
204 # Put our bundled wheels into a temporary directory and construct the
205 # additional paths that need added to sys.path
206 additional_paths = []
207 for name, package in _get_packages().items():
208 if package.wheel_name:
209 # Use bundled wheel package
210 wheel_name = package.wheel_name
211 wheel_path = resources.files("ensurepip") / "_bundled" / wheel_name
212 whl = wheel_path.read_bytes()
213 else:
214 # Use the wheel package directory
215 with open(package.wheel_path, "rb") as fp:
216 whl = fp.read()
217 wheel_name = os.path.basename(package.wheel_path)
218
219 filename = os.path.join(tmpdir, wheel_name)
220 with open(filename, "wb") as fp:
221 fp.write(whl)
222
223 additional_paths.append(filename)
224
225 # Construct the arguments to be passed to the pip command
226 args = ["install", "--no-cache-dir", "--no-index", "--find-links", tmpdir]
227 if root:
228 args += ["--root", root]
229 if upgrade:
230 args += ["--upgrade"]
231 if user:
232 args += ["--user"]
233 if verbosity:
234 args += ["-" + "v" * verbosity]
235
236 return _run_pip([*args, *_PACKAGE_NAMES], additional_paths)
237
238 def _uninstall_helper(*, verbosity=0):
239 """Helper to support a clean default uninstall process on Windows
240
241 Note that calling this function may alter os.environ.
242 """
243 # Nothing to do if pip was never installed, or has been removed
244 try:
245 import pip
246 except ImportError:
247 return
248
249 # If the installed pip version doesn't match the available one,
250 # leave it alone
251 available_version = version()
252 if pip.__version__ != available_version:
253 print(f"ensurepip will only uninstall a matching version "
254 f"({pip.__version__!r} installed, "
255 f"{available_version!r} available)",
256 file=sys.stderr)
257 return
258
259 _disable_pip_configuration_settings()
260
261 # Construct the arguments to be passed to the pip command
262 args = ["uninstall", "-y", "--disable-pip-version-check"]
263 if verbosity:
264 args += ["-" + "v" * verbosity]
265
266 return _run_pip([*args, *reversed(_PACKAGE_NAMES)])
267
268
269 def _main(argv=None):
270 import argparse
271 parser = argparse.ArgumentParser(prog="python -m ensurepip")
272 parser.add_argument(
273 "--version",
274 action="version",
275 version="pip {}".format(version()),
276 help="Show the version of pip that is bundled with this Python.",
277 )
278 parser.add_argument(
279 "-v", "--verbose",
280 action="count",
281 default=0,
282 dest="verbosity",
283 help=("Give more output. Option is additive, and can be used up to 3 "
284 "times."),
285 )
286 parser.add_argument(
287 "-U", "--upgrade",
288 action="store_true",
289 default=False,
290 help="Upgrade pip and dependencies, even if already installed.",
291 )
292 parser.add_argument(
293 "--user",
294 action="store_true",
295 default=False,
296 help="Install using the user scheme.",
297 )
298 parser.add_argument(
299 "--root",
300 default=None,
301 help="Install everything relative to this alternate root directory.",
302 )
303 parser.add_argument(
304 "--altinstall",
305 action="store_true",
306 default=False,
307 help=("Make an alternate install, installing only the X.Y versioned "
308 "scripts (Default: pipX, pipX.Y, easy_install-X.Y)."),
309 )
310 parser.add_argument(
311 "--default-pip",
312 action="store_true",
313 default=False,
314 help=("Make a default pip install, installing the unqualified pip "
315 "and easy_install in addition to the versioned scripts."),
316 )
317
318 args = parser.parse_args(argv)
319
320 return _bootstrap(
321 root=args.root,
322 upgrade=args.upgrade,
323 user=args.user,
324 verbosity=args.verbosity,
325 altinstall=args.altinstall,
326 default_pip=args.default_pip,
327 )