Debian Codegraph @

src/build/env.py

raw
1 from __future__ import annotations
2
3
4 __lazy_modules__ = [
5 'abc',
6 'contextlib',
7 f'{__spec__.parent}._compat.importlib',
8 f'{__spec__.parent}._ctx',
9 f'{__spec__.parent}._exceptions',
10 f'{__spec__.parent}._util',
11 'importlib',
12 'importlib.util',
13 'os',
14 'packaging',
15 'packaging.requirements',
16 'packaging.utils',
17 'platform',
18 'shutil',
19 'subprocess',
20 'sys',
21 'sysconfig',
22 'tempfile',
23 'warnings',
24 ]
25
26 import abc
27 import contextlib
28 import functools
29 import importlib.util
30 import os
31 import platform
32 import shutil
33 import subprocess
34 import sys
35 import sysconfig
36 import tempfile
37 import typing
38 import warnings
39
40 from packaging.requirements import InvalidRequirement, Requirement
41 from packaging.utils import canonicalize_name
42
43 from . import _ctx
44 from ._compat.importlib import metadata as importlib_metadata
45 from ._ctx import run_subprocess
46 from ._exceptions import BuildException, FailedProcessError
47 from ._util import check_dependency
48
49
50 TYPE_CHECKING = False
51
52 if TYPE_CHECKING:
53 from collections.abc import Collection, Mapping
54
55 if sys.version_info < (3, 11):
56 from typing_extensions import Self
57 else:
58 from typing import Self
59
60
61 Installer = typing.Literal['pip', 'uv']
62
63 INSTALLERS = typing.get_args(Installer)
64
65
66 class IsolatedEnv(typing.Protocol):
67 """Isolated build environment ABC."""
68
69 @property
70 @abc.abstractmethod
71 def python_executable(self) -> str:
72 """The Python executable of the isolated environment."""
73
74 @abc.abstractmethod
75 def make_extra_environ(self) -> Mapping[str, str] | None:
76 """Generate additional env vars specific to the isolated environment."""
77
78
79 def _has_dependency(
80 name: str, minimum_version_str: str | None = None, /, **distargs: list[str]
81 ) -> importlib_metadata.Distribution | None:
82 """
83 Given a distribution name, see if it is present and return the distribution
84 if the version is sufficient for build, None if the package is missing or
85 too old.
86 """
87 from packaging.version import Version
88
89 try:
90 distribution = next(iter(importlib_metadata.distributions(name=name, **distargs)))
91 except StopIteration:
92 return None
93
94 if minimum_version_str is None:
95 return distribution
96
97 if Version(distribution.version) < Version(minimum_version_str):
98 return None
99
100 return distribution
101
102
103 class DefaultIsolatedEnv(IsolatedEnv):
104 """
105 Isolated environment which supports several different underlying implementations.
106 """
107
108 def __init__(
109 self,
110 *,
111 installer: Installer = 'pip',
112 path: str | None = None,
113 ) -> None:
114 self.installer: Installer = installer
115 self._requested_path = path
116
117 def __enter__(self) -> Self:
118 if self._requested_path is None:
119 path = tempfile.mkdtemp(prefix='build-env-')
120 else:
121 path = self._requested_path
122 if os.path.exists(path) and not os.path.isdir(path):
123 msg = f'Build environment location is not a directory: {path}'
124 raise BuildException(msg)
125 if os.path.isdir(path):
126 with os.scandir(path) as entries:
127 if next(entries, None) is not None:
128 msg = f'Build environment location is not empty: {path}'
129 raise BuildException(msg)
130 os.makedirs(path, exist_ok=True)
131
132 # Set early so ``__exit__`` can clean up even if the calls below fail.
133 self._path = path
134 try:
135 # Call ``realpath`` to prevent spurious warning from being emitted
136 # that the venv location has changed on Windows for the venv impl.
137 # The username is DOS-encoded in the output of tempfile - the location is the same
138 # but the representation of it is different, which confuses venv.
139 # Ref: https://bugs.python.org/issue46171
140 path = os.path.realpath(path)
141 self._path = path
142
143 self._env_backend: _EnvBackend
144
145 # uv is opt-in only.
146 if self.installer == 'uv':
147 self._env_backend = _UvBackend()
148 else:
149 self._env_backend = _PipBackend()
150
151 _ctx.log(f'Creating isolated environment: {self._env_backend.display_name}...', kind=('step',))
152 self._env_backend.create(self._path)
153
154 except Exception: # cleanup folder if creation fails
155 self.__exit__(*sys.exc_info())
156 raise
157
158 return self
159
160 def __exit__(self, *args: object) -> None:
161 # A temporary location is always cleaned up. A caller-specified location is kept when the build fails so
162 # its environment can be inspected, but removed on success so the same location can be reused.
163 if self._requested_path is None or args[0] is None:
164 shutil.rmtree(self._path, ignore_errors=True)
165
166 @property
167 def path(self) -> str:
168 """The location of the isolated build environment."""
169 return self._path
170
171 @property
172 def python_executable(self) -> str:
173 """The python executable of the isolated build environment."""
174 return self._env_backend.python_executable
175
176 def make_extra_environ(self) -> dict[str, str]:
177 path = os.environ.get('PATH')
178 return {
179 'PATH': os.pathsep.join([self._env_backend.scripts_dir, path])
180 if path is not None
181 else self._env_backend.scripts_dir,
182 # Set PYTHONPATH to empty to override any host value. An empty
183 # PYTHONPATH is treated as unset by CPython's path initialization
184 # (the ``if pythonpath_env:`` check makes it a no-op).
185 'PYTHONPATH': '',
186 }
187
188 def installed_versions(self, requirements: Collection[str]) -> dict[str, str]:
189 """
190 Map the canonical name of each requirement to the version installed in the environment.
191
192 Requirements that resolved to nothing installed are omitted. Reads the distribution metadata
193 directly from the environment's ``purelib`` so no subprocess is spawned in the isolated environment.
194
195 :param requirements: PEP 508 requirement specifications to look up; non-PEP 508 entries (such as local
196 paths or URLs accepted by :meth:`install`) are skipped since their installed name cannot be derived
197 """
198 wanted = {name for requirement in requirements if (name := _canonical_requirement_name(requirement)) is not None}
199 distributions = importlib_metadata.distributions(path=[self._env_backend.purelib])
200 return {
201 name: distribution.version
202 for distribution in distributions
203 if (name := canonicalize_name(distribution.name)) in wanted
204 }
205
206 def install(
207 self,
208 requirements: Collection[str],
209 constraints: Collection[str] = (),
210 *,
211 _fresh: bool = False, # Used internally by CLI to support preset PYTHONPATH
212 ) -> None:
213 """
214 Install packages from PEP 508 requirements in the isolated build environment.
215
216 :param requirements: PEP 508 requirement specification to install
217
218 :note: Passing non-PEP 508 strings will result in undefined behavior, you *should not* rely on it. It is
219 merely an implementation detail, it may change any time without warning.
220 """
221 if not requirements:
222 return
223
224 _ctx.log(
225 'Installing packages in isolated environment:\n' + '\n'.join(f'- {r}' for r in sorted(requirements)),
226 kind=('step',),
227 )
228 self._env_backend.install_dependencies(requirements, constraints, _fresh=_fresh)
229
230
231 def _canonical_requirement_name(requirement: str) -> str | None:
232 try:
233 return canonicalize_name(Requirement(requirement).name)
234 except InvalidRequirement:
235 return None
236
237
238 class _EnvBackend(typing.Protocol): # pragma: no cover
239 python_executable: str
240 scripts_dir: str
241 purelib: str
242
243 def create(self, path: str) -> None: ...
244
245 def install_dependencies(
246 self,
247 requirements: Collection[str],
248 constraints: Collection[str],
249 *,
250 _fresh: bool = False,
251 ) -> None: ...
252
253 @property
254 def display_name(self) -> str: ...
255
256
257 @functools.cache
258 def _has_keyring_cli() -> bool:
259 return shutil.which('keyring') is not None
260
261
262 def _pip_env() -> dict[str, str] | None:
263 if 'PIP_KEYRING_PROVIDER' not in os.environ and _has_keyring_cli():
264 return {**os.environ, 'PIP_KEYRING_PROVIDER': 'subprocess'}
265 return None
266
267
268 class _PipBackend(_EnvBackend):
269 def __init__(self) -> None:
270 self._create_with_virtualenv = not self._has_valid_outer_pip and self._has_virtualenv
271
272 @functools.cached_property
273 def _has_valid_outer_pip(self) -> bool | None:
274 """
275 This checks for a valid global pip. Returns None if pip is missing, False
276 if pip is too old or debundled, and True if it can be used.
277 """
278
279 # Version to have added the `--python` option.
280 # `pip install --python` is nonfunctional on Gentoo debundled pip.
281 if dist := _has_dependency('pip', '22.3'): # pragma: no cover
282 files = dist.files
283 if files:
284 return any(str(f).startswith('pip/_vendor') for f in files)
285 # The distribution package manager deleted the RECORD file,
286 # generally to force pip to be unable to uninstall itself
287 # Only try this on 3.12+ since it can have side effects before 3.12
288 # due to _distutils_hack and pip interacting.
289 if sys.version_info >= (3, 12):
290 with warnings.catch_warnings():
291 warnings.simplefilter('ignore')
292 if importlib.util.find_spec('pip._vendor') is not None:
293 return True
294 return False
295
296 return None # pragma: no cover
297
298 @functools.cached_property
299 def _has_virtualenv(self) -> bool:
300 """
301 virtualenv might be incompatible if it was installed separately
302 from build. This verifies that virtualenv and all of its
303 dependencies are installed as required by build.
304 """
305 name = 'virtualenv'
306
307 return importlib.util.find_spec(name) is not None and not any(
308 Requirement(d[1]).name == name for d in check_dependency(f'build[{name}]') if len(d) > 1
309 )
310
311 @staticmethod
312 def _get_minimum_pip_version_str() -> str:
313 if platform.system() == 'Darwin':
314 release, _, machine = platform.mac_ver()
315 major = release.split('.', 1)[0]
316 if major and int(major) >= 11:
317 # macOS 11+ name scheme change requires 20.3. Intel macOS 11.0 can be
318 # told to report 10.16 for backwards compatibility; but that also fixes
319 # earlier versions of pip so this is only needed for 11+.
320 is_apple_silicon_python = machine != 'x86_64'
321 return '21.0.1' if is_apple_silicon_python else '20.3.0'
322
323 # PEP-517 and manylinux1 was first implemented in 19.1
324 return '19.1.0'
325
326 def create(self, path: str) -> None:
327 if self._create_with_virtualenv:
328 import packaging.version
329 import virtualenv
330
331 from ._compat import importlib
332
333 virtualenv_ver = packaging.version.Version(importlib.metadata.version('virtualenv'))
334
335 opts = [
336 path,
337 '--activators',
338 '',
339 '--no-setuptools',
340 '--no-periodic-update',
341 ]
342
343 if virtualenv_ver < packaging.version.Version('20.31.0'):
344 opts.append('--no-wheel')
345
346 result = virtualenv.cli_run(opts, setup_logging=False)
347
348 # The creator attributes are `pathlib.Path`s.
349 self.python_executable = str(result.creator.exe)
350 self.scripts_dir = str(result.creator.script_dir)
351 self.purelib = str(result.creator.purelib)
352
353 else:
354 import venv
355
356 with_pip = not self._has_valid_outer_pip
357
358 try:
359 venv.EnvBuilder(symlinks=_fs_supports_symlink(), with_pip=with_pip).create(path)
360 except subprocess.CalledProcessError as exc:
361 _ctx.log_subprocess_error(exc)
362 raise FailedProcessError(exc, 'Failed to create venv. Maybe try installing virtualenv.') from None
363
364 self.python_executable, self.scripts_dir, purelib = _find_executable_and_scripts(path)
365 self.purelib = purelib
366
367 if with_pip:
368 minimum_pip_version_str = self._get_minimum_pip_version_str()
369 if not _has_dependency(
370 'pip',
371 minimum_pip_version_str,
372 path=[purelib],
373 ):
374 run_subprocess(
375 [self.python_executable, '-Im', 'pip', 'install', '--no-input', f'pip>={minimum_pip_version_str}'],
376 env=_pip_env(),
377 )
378
379 # Uninstall setuptools from the build env to prevent depending on it implicitly.
380 # Pythons 3.12 and up do not install setuptools, check if it exists first.
381 if _has_dependency(
382 'setuptools',
383 path=[purelib],
384 ):
385 run_subprocess(
386 [self.python_executable, '-Im', 'pip', 'uninstall', '--no-input', '-y', 'setuptools'],
387 env=_pip_env(),
388 )
389
390 def install_dependencies(
391 self,
392 requirements: Collection[str],
393 constraints: Collection[str],
394 *,
395 _fresh: bool = False,
396 ) -> None:
397 with contextlib.ExitStack() as exit_stack:
398 if self._has_valid_outer_pip:
399 cmd = [sys.executable, '-m', 'pip', '--python', self.python_executable]
400 else:
401 cmd = [self.python_executable, '-Im', 'pip']
402
403 if (verbosity := _ctx.verbosity) > 1:
404 cmd += [f'-{"v" * (verbosity - 1)}']
405
406 cmd += ['install']
407 if _fresh:
408 cmd += ['--ignore-installed']
409 cmd += ['--use-pep517', '--no-warn-script-location', '--no-compile', '--no-input']
410
411 # pip does not honour environment markers in command line arguments
412 # but it does from requirement files.
413 with tempfile.NamedTemporaryFile(
414 'w', prefix='build-requirements-', suffix='.txt', delete=False, encoding='utf-8'
415 ) as requirement_file:
416 requirement_file.write('\n'.join(requirements))
417 exit_stack.callback(functools.partial(os.unlink, requirement_file.name))
418
419 cmd += ['-r', os.path.abspath(requirement_file.name)]
420
421 if constraints:
422 with tempfile.NamedTemporaryFile(
423 'w', prefix='build-constraints-', suffix='.txt', delete=False, encoding='utf-8'
424 ) as constraint_file:
425 constraint_file.write('\n'.join(constraints))
426 exit_stack.callback(functools.partial(os.unlink, constraint_file.name))
427
428 cmd += ['-c', os.path.abspath(constraint_file.name)]
429
430 run_subprocess(cmd, env=_pip_env())
431
432 @property
433 def display_name(self) -> str:
434 return 'virtualenv+pip' if self._create_with_virtualenv else 'venv+pip'
435
436
437 class _UvBackend(_EnvBackend):
438 def create(self, path: str) -> None:
439 import venv
440
441 self._env_path = path
442
443 try:
444 import uv
445
446 self._uv_bin = uv.find_uv_bin()
447 except (ModuleNotFoundError, FileNotFoundError):
448 uv_bin = shutil.which(os.environ.get('UV') or 'uv')
449 if uv_bin is None:
450 msg = 'uv executable not found'
451 raise RuntimeError(msg) from None
452
453 _ctx.log(f'Using external uv from {uv_bin}')
454 self._uv_bin = uv_bin
455
456 venv.EnvBuilder(symlinks=_fs_supports_symlink(), with_pip=False).create(self._env_path)
457 self.python_executable, self.scripts_dir, self.purelib = _find_executable_and_scripts(self._env_path)
458
459 def install_dependencies( # pragma: no cover -- uv tests are skipped on PyPy, covered on CPython
460 self,
461 requirements: Collection[str],
462 constraints: Collection[str],
463 *,
464 _fresh: bool = False,
465 ) -> None:
466 with contextlib.ExitStack() as exit_stack:
467 cmd = [self._uv_bin, 'pip']
468
469 if (verbosity := _ctx.verbosity) > 1:
470 cmd += [f'-{"v" * min(2, verbosity - 1)}']
471
472 cmd += ['install', *requirements, '--python', self.python_executable]
473
474 if constraints:
475 with tempfile.NamedTemporaryFile(
476 'w', prefix='build-constraints-', suffix='.txt', delete=False, encoding='utf-8'
477 ) as constraint_file:
478 constraint_file.write('\n'.join(constraints))
479 exit_stack.callback(functools.partial(os.unlink, constraint_file.name))
480
481 cmd += ['-c', os.path.abspath(constraint_file.name)]
482
483 env = {k: v for k, v in os.environ.items() if k != 'PYTHONPATH'}
484 env['VIRTUAL_ENV'] = self._env_path
485 if 'UV_KEYRING_PROVIDER' not in os.environ and _has_keyring_cli():
486 env['UV_KEYRING_PROVIDER'] = 'subprocess'
487 run_subprocess(cmd, env=env)
488
489 @property
490 def display_name(self) -> str:
491 return 'venv+uv'
492
493
494 @functools.cache
495 def _fs_supports_symlink() -> bool:
496 """Return True if symlinks are supported"""
497 # Using definition used by venv.main()
498 if os.name != 'nt':
499 return True # pragma: win32 no cover
500
501 # Windows may support symlinks (setting in Windows 10)
502 with tempfile.NamedTemporaryFile(prefix='build-symlink-') as tmp_file: # pragma: win32 cover
503 dest = f'{tmp_file.name}-b'
504 try:
505 os.symlink(tmp_file.name, dest)
506 os.unlink(dest)
507 except (OSError, NotImplementedError, AttributeError):
508 return False
509 return True
510
511
512 def _find_executable_and_scripts(path: str) -> tuple[str, str, str]:
513 """
514 Detect the Python executable and script folder of a virtual environment.
515
516 :param path: The location of the virtual environment
517 :return: The Python executable, script folder, and purelib folder
518 """
519 config_vars = sysconfig.get_config_vars().copy() # globally cached, copy before altering it
520 config_vars['base'] = path
521 scheme_names = sysconfig.get_scheme_names()
522 if 'venv' in scheme_names:
523 # Python distributors with custom default installation scheme can set a
524 # scheme that can't be used to expand the paths in a venv.
525 # This can happen if build itself is not installed in a venv.
526 # The distributors are encouraged to set a "venv" scheme to be used for this.
527 # See https://bugs.python.org/issue45413
528 # and https://github.com/pypa/virtualenv/issues/2208
529 paths = sysconfig.get_paths(scheme='venv', vars=config_vars) # pragma: no cover
530 elif 'posix_local' in scheme_names:
531 # The Python that ships on Debian/Ubuntu varies the default scheme to
532 # install to /usr/local
533 # But it does not (yet) set the "venv" scheme.
534 # If we're the Debian "posix_local" scheme is available, but "venv"
535 # is not, we use "posix_prefix" instead which is venv-compatible there.
536 paths = sysconfig.get_paths(scheme='posix_prefix', vars=config_vars)
537 elif 'osx_framework_library' in scheme_names:
538 # The Python that ships with the macOS developer tools varies the
539 # default scheme depending on whether the ``sys.prefix`` is part of a framework.
540 # But it does not (yet) set the "venv" scheme.
541 # If the Apple-custom "osx_framework_library" scheme is available but "venv"
542 # is not, we use "posix_prefix" instead which is venv-compatible there.
543 paths = sysconfig.get_paths(scheme='posix_prefix', vars=config_vars)
544 else:
545 paths = sysconfig.get_paths(vars=config_vars)
546
547 executable = os.path.join(paths['scripts'], 'python.exe' if os.name == 'nt' else 'python')
548 if not os.path.exists(executable):
549 msg = f'Virtual environment creation failed, executable {executable} missing'
550 raise RuntimeError(msg)
551
552 return executable, paths['scripts'], paths['purelib']
553
554
555 __all__ = [
556 'DefaultIsolatedEnv',
557 'IsolatedEnv',
558 ]