pip/src/pip/_internal/build_env.py

305 lines
10 KiB
Python
Raw Normal View History

2018-01-22 22:23:56 +01:00
"""Build Environment used for isolation during sdist building
"""
import contextlib
import logging
2018-01-22 22:23:56 +01:00
import os
import pathlib
import sys
import textwrap
import zipfile
from collections import OrderedDict
2018-01-22 22:23:56 +01:00
from sysconfig import get_paths
from types import TracebackType
from typing import TYPE_CHECKING, Generator, Iterable, List, Optional, Set, Tuple, Type
2018-01-22 22:23:56 +01:00
from pip._vendor.certifi import where
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.packaging.version import Version
from pip import __file__ as pip_location
from pip._internal.cli.spinners import open_spinner
2021-02-19 10:14:11 +01:00
from pip._internal.locations import get_platlib, get_prefixed_libs, get_purelib
from pip._internal.metadata import get_default_environment, get_environment
2019-09-30 07:45:24 +02:00
from pip._internal.utils.subprocess import call_subprocess
from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
2018-01-22 22:23:56 +01:00
if TYPE_CHECKING:
from pip._internal.index.package_finder import PackageFinder
logger = logging.getLogger(__name__)
class _Prefix:
2021-07-24 06:13:10 +02:00
def __init__(self, path: str) -> None:
self.path = path
self.setup = False
self.bin_dir = get_paths(
2021-08-13 15:23:45 +02:00
"nt" if os.name == "nt" else "posix_prefix",
vars={"base": path, "platbase": path},
)["scripts"]
2021-02-19 10:14:11 +01:00
self.lib_dirs = get_prefixed_libs(path)
@contextlib.contextmanager
def _create_standalone_pip() -> Generator[str, None, None]:
2021-03-05 22:01:12 +01:00
"""Create a "standalone pip" zip file.
2021-03-06 14:10:06 +01:00
The zip file's content is identical to the currently-running pip.
2021-03-05 22:01:12 +01:00
It will be used to install requirements into the build environment.
"""
source = pathlib.Path(pip_location).resolve().parent
2021-03-06 14:10:06 +01:00
# Return the current instance if `source` is not a directory. We can't build
# a zip from this, and it likely means the instance is already standalone.
if not source.is_dir():
2021-03-06 14:10:06 +01:00
yield str(source)
return
2021-03-05 19:26:56 +01:00
with TempDirectory(kind="standalone-pip") as tmp_dir:
2021-03-06 14:10:06 +01:00
pip_zip = os.path.join(tmp_dir.path, "__env_pip__.zip")
kwargs = {}
if sys.version_info >= (3, 8):
kwargs["strict_timestamps"] = False
with zipfile.ZipFile(pip_zip, "w", **kwargs) as zf:
for child in source.rglob("*"):
2021-03-06 13:55:02 +01:00
zf.write(child, child.relative_to(source.parent).as_posix())
yield os.path.join(pip_zip, "pip")
class BuildEnvironment:
2021-08-13 15:23:45 +02:00
"""Creates and manages an isolated environment to install build deps"""
2018-01-22 22:23:56 +01:00
2021-07-24 06:13:10 +02:00
def __init__(self) -> None:
2021-08-13 15:23:45 +02:00
temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
2018-01-22 22:23:56 +01:00
2021-02-10 09:46:25 +01:00
self._prefixes = OrderedDict(
(name, _Prefix(os.path.join(temp_dir.path, name)))
2021-08-13 15:23:45 +02:00
for name in ("normal", "overlay")
2021-02-10 09:46:25 +01:00
)
2021-07-24 06:13:10 +02:00
self._bin_dirs: List[str] = []
self._lib_dirs: List[str] = []
for prefix in reversed(list(self._prefixes.values())):
self._bin_dirs.append(prefix.bin_dir)
self._lib_dirs.extend(prefix.lib_dirs)
# Customize site to:
# - ensure .pth files are honored
# - prevent access to system site packages
system_sites = {
2021-02-19 10:14:11 +01:00
os.path.normcase(site) for site in (get_purelib(), get_platlib())
}
2021-08-13 15:23:45 +02:00
self._site_dir = os.path.join(temp_dir.path, "site")
if not os.path.exists(self._site_dir):
os.mkdir(self._site_dir)
with open(
os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8"
) as fp:
2021-08-13 15:23:45 +02:00
fp.write(
textwrap.dedent(
"""
import os, site, sys
# First, drop system-sites related paths.
original_sys_path = sys.path[:]
known_paths = set()
for path in {system_sites!r}:
site.addsitedir(path, known_paths=known_paths)
system_paths = set(
os.path.normcase(path)
for path in sys.path[len(original_sys_path):]
)
original_sys_path = [
path for path in original_sys_path
if os.path.normcase(path) not in system_paths
]
sys.path = original_sys_path
# Second, add lib directories.
# ensuring .pth file are processed.
for path in {lib_dirs!r}:
assert not path in sys.path
site.addsitedir(path)
2021-08-13 15:23:45 +02:00
"""
).format(system_sites=system_sites, lib_dirs=self._lib_dirs)
)
2021-07-24 06:13:10 +02:00
def __enter__(self) -> None:
self._save_env = {
name: os.environ.get(name, None)
2021-08-13 15:23:45 +02:00
for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH")
}
path = self._bin_dirs[:]
2021-08-13 15:23:45 +02:00
old_path = self._save_env["PATH"]
if old_path:
path.extend(old_path.split(os.pathsep))
pythonpath = [self._site_dir]
2021-08-13 15:23:45 +02:00
os.environ.update(
{
"PATH": os.pathsep.join(path),
"PYTHONNOUSERSITE": "1",
"PYTHONPATH": os.pathsep.join(pythonpath),
}
)
2018-01-22 22:23:56 +01:00
def __exit__(
self,
2021-07-24 06:13:10 +02:00
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
2021-08-13 15:23:45 +02:00
exc_tb: Optional[TracebackType],
2021-07-24 06:13:10 +02:00
) -> None:
for varname, old_value in self._save_env.items():
if old_value is None:
os.environ.pop(varname, None)
else:
os.environ[varname] = old_value
2021-07-24 06:13:10 +02:00
def check_requirements(
self, reqs: Iterable[str]
) -> Tuple[Set[Tuple[str, str]], Set[str]]:
"""Return 2 sets:
2021-08-13 15:23:45 +02:00
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = set()
if reqs:
env = (
get_environment(self._lib_dirs)
if hasattr(self, "_lib_dirs")
else get_default_environment()
)
for req_str in reqs:
req = Requirement(req_str)
# We're explicitly evaluating with an empty extra value, since build
# environments are not provided any mechanism to select specific extras.
if req.marker is not None and not req.marker.evaluate({"extra": ""}):
continue
dist = env.get_distribution(req.name)
if not dist:
missing.add(req_str)
continue
if isinstance(dist.version, Version):
installed_req_str = f"{req.name}=={dist.version}"
else:
installed_req_str = f"{req.name}==={dist.version}"
if dist.version not in req.specifier:
conflicting.add((installed_req_str, req_str))
# FIXME: Consider direct URL?
return conflicting, missing
def install_requirements(
self,
2021-07-24 06:13:10 +02:00
finder: "PackageFinder",
requirements: Iterable[str],
prefix_as_string: str,
*,
kind: str,
2021-07-24 06:13:10 +02:00
) -> None:
prefix = self._prefixes[prefix_as_string]
assert not prefix.setup
prefix.setup = True
if not requirements:
return
with contextlib.ExitStack() as ctx:
2021-11-07 12:41:02 +01:00
pip_runnable = ctx.enter_context(_create_standalone_pip())
2021-03-05 19:27:40 +01:00
self._install_requirements(
pip_runnable,
finder,
requirements,
prefix,
kind=kind,
)
2021-03-05 19:27:40 +01:00
@staticmethod
def _install_requirements(
pip_runnable: str,
2021-03-05 19:27:40 +01:00
finder: "PackageFinder",
requirements: Iterable[str],
prefix: _Prefix,
*,
kind: str,
2021-03-05 19:27:40 +01:00
) -> None:
2021-07-24 06:13:10 +02:00
args: List[str] = [
2021-08-13 15:23:45 +02:00
sys.executable,
pip_runnable,
"install",
"--ignore-installed",
"--no-user",
"--prefix",
prefix.path,
"--no-warn-script-location",
2021-07-24 06:13:10 +02:00
]
2021-03-05 19:27:40 +01:00
if logger.getEffectiveLevel() <= logging.DEBUG:
2021-08-13 15:23:45 +02:00
args.append("-v")
for format_control in ("no_binary", "only_binary"):
2021-03-05 19:27:40 +01:00
formats = getattr(finder.format_control, format_control)
2021-08-13 15:23:45 +02:00
args.extend(
(
"--" + format_control.replace("_", "-"),
",".join(sorted(formats or {":none:"})),
)
)
2021-03-05 19:27:40 +01:00
index_urls = finder.index_urls
if index_urls:
2021-08-13 15:23:45 +02:00
args.extend(["-i", index_urls[0]])
2021-03-05 19:27:40 +01:00
for extra_index in index_urls[1:]:
2021-08-13 15:23:45 +02:00
args.extend(["--extra-index-url", extra_index])
2021-03-05 19:27:40 +01:00
else:
2021-08-13 15:23:45 +02:00
args.append("--no-index")
2021-03-05 19:27:40 +01:00
for link in finder.find_links:
2021-08-13 15:23:45 +02:00
args.extend(["--find-links", link])
2021-03-05 19:27:40 +01:00
for host in finder.trusted_hosts:
2021-08-13 15:23:45 +02:00
args.extend(["--trusted-host", host])
2021-03-05 19:27:40 +01:00
if finder.allow_all_prereleases:
2021-08-13 15:23:45 +02:00
args.append("--pre")
2021-03-05 19:27:40 +01:00
if finder.prefer_binary:
2021-08-13 15:23:45 +02:00
args.append("--prefer-binary")
args.append("--")
2021-03-05 19:27:40 +01:00
args.extend(requirements)
2021-03-06 13:55:02 +01:00
extra_environ = {"_PIP_STANDALONE_CERT": where()}
with open_spinner(f"Installing {kind}") as spinner:
call_subprocess(
args,
command_desc=f"pip subprocess to install {kind}",
spinner=spinner,
extra_environ=extra_environ,
)
2021-03-05 19:27:40 +01:00
class NoOpBuildEnvironment(BuildEnvironment):
2021-08-13 15:23:45 +02:00
"""A no-op drop-in replacement for BuildEnvironment"""
2021-07-24 06:13:10 +02:00
def __init__(self) -> None:
pass
2021-07-24 06:13:10 +02:00
def __enter__(self) -> None:
pass
def __exit__(
self,
2021-07-24 06:13:10 +02:00
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
2021-08-13 15:23:45 +02:00
exc_tb: Optional[TracebackType],
2021-07-24 06:13:10 +02:00
) -> None:
pass
2021-07-24 06:13:10 +02:00
def cleanup(self) -> None:
pass
def install_requirements(
self,
2021-07-24 06:13:10 +02:00
finder: "PackageFinder",
requirements: Iterable[str],
prefix_as_string: str,
*,
kind: str,
2021-07-24 06:13:10 +02:00
) -> None:
raise NotImplementedError()