build_env.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """Build Environment used for isolation during sdist building
  2. """
  3. # The following comment should be removed at some point in the future.
  4. # mypy: strict-optional=False
  5. # mypy: disallow-untyped-defs=False
  6. import logging
  7. import os
  8. import sys
  9. import textwrap
  10. from collections import OrderedDict
  11. from distutils.sysconfig import get_python_lib
  12. from sysconfig import get_paths
  13. from pip._vendor.pkg_resources import Requirement, VersionConflict, WorkingSet
  14. from pip import __file__ as pip_location
  15. from pip._internal.cli.spinners import open_spinner
  16. from pip._internal.utils.subprocess import call_subprocess
  17. from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
  18. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  19. if MYPY_CHECK_RUNNING:
  20. from typing import Tuple, Set, Iterable, Optional, List
  21. from pip._internal.index.package_finder import PackageFinder
  22. logger = logging.getLogger(__name__)
  23. class _Prefix:
  24. def __init__(self, path):
  25. # type: (str) -> None
  26. self.path = path
  27. self.setup = False
  28. self.bin_dir = get_paths(
  29. 'nt' if os.name == 'nt' else 'posix_prefix',
  30. vars={'base': path, 'platbase': path}
  31. )['scripts']
  32. # Note: prefer distutils' sysconfig to get the
  33. # library paths so PyPy is correctly supported.
  34. purelib = get_python_lib(plat_specific=False, prefix=path)
  35. platlib = get_python_lib(plat_specific=True, prefix=path)
  36. if purelib == platlib:
  37. self.lib_dirs = [purelib]
  38. else:
  39. self.lib_dirs = [purelib, platlib]
  40. class BuildEnvironment(object):
  41. """Creates and manages an isolated environment to install build deps
  42. """
  43. def __init__(self):
  44. # type: () -> None
  45. temp_dir = TempDirectory(
  46. kind=tempdir_kinds.BUILD_ENV, globally_managed=True
  47. )
  48. self._prefixes = OrderedDict((
  49. (name, _Prefix(os.path.join(temp_dir.path, name)))
  50. for name in ('normal', 'overlay')
  51. ))
  52. self._bin_dirs = [] # type: List[str]
  53. self._lib_dirs = [] # type: List[str]
  54. for prefix in reversed(list(self._prefixes.values())):
  55. self._bin_dirs.append(prefix.bin_dir)
  56. self._lib_dirs.extend(prefix.lib_dirs)
  57. # Customize site to:
  58. # - ensure .pth files are honored
  59. # - prevent access to system site packages
  60. system_sites = {
  61. os.path.normcase(site) for site in (
  62. get_python_lib(plat_specific=False),
  63. get_python_lib(plat_specific=True),
  64. )
  65. }
  66. self._site_dir = os.path.join(temp_dir.path, 'site')
  67. if not os.path.exists(self._site_dir):
  68. os.mkdir(self._site_dir)
  69. with open(os.path.join(self._site_dir, 'sitecustomize.py'), 'w') as fp:
  70. fp.write(textwrap.dedent(
  71. '''
  72. import os, site, sys
  73. # First, drop system-sites related paths.
  74. original_sys_path = sys.path[:]
  75. known_paths = set()
  76. for path in {system_sites!r}:
  77. site.addsitedir(path, known_paths=known_paths)
  78. system_paths = set(
  79. os.path.normcase(path)
  80. for path in sys.path[len(original_sys_path):]
  81. )
  82. original_sys_path = [
  83. path for path in original_sys_path
  84. if os.path.normcase(path) not in system_paths
  85. ]
  86. sys.path = original_sys_path
  87. # Second, add lib directories.
  88. # ensuring .pth file are processed.
  89. for path in {lib_dirs!r}:
  90. assert not path in sys.path
  91. site.addsitedir(path)
  92. '''
  93. ).format(system_sites=system_sites, lib_dirs=self._lib_dirs))
  94. def __enter__(self):
  95. self._save_env = {
  96. name: os.environ.get(name, None)
  97. for name in ('PATH', 'PYTHONNOUSERSITE', 'PYTHONPATH')
  98. }
  99. path = self._bin_dirs[:]
  100. old_path = self._save_env['PATH']
  101. if old_path:
  102. path.extend(old_path.split(os.pathsep))
  103. pythonpath = [self._site_dir]
  104. os.environ.update({
  105. 'PATH': os.pathsep.join(path),
  106. 'PYTHONNOUSERSITE': '1',
  107. 'PYTHONPATH': os.pathsep.join(pythonpath),
  108. })
  109. def __exit__(self, exc_type, exc_val, exc_tb):
  110. for varname, old_value in self._save_env.items():
  111. if old_value is None:
  112. os.environ.pop(varname, None)
  113. else:
  114. os.environ[varname] = old_value
  115. def check_requirements(self, reqs):
  116. # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
  117. """Return 2 sets:
  118. - conflicting requirements: set of (installed, wanted) reqs tuples
  119. - missing requirements: set of reqs
  120. """
  121. missing = set()
  122. conflicting = set()
  123. if reqs:
  124. ws = WorkingSet(self._lib_dirs)
  125. for req in reqs:
  126. try:
  127. if ws.find(Requirement.parse(req)) is None:
  128. missing.add(req)
  129. except VersionConflict as e:
  130. conflicting.add((str(e.args[0].as_requirement()),
  131. str(e.args[1])))
  132. return conflicting, missing
  133. def install_requirements(
  134. self,
  135. finder, # type: PackageFinder
  136. requirements, # type: Iterable[str]
  137. prefix_as_string, # type: str
  138. message # type: Optional[str]
  139. ):
  140. # type: (...) -> None
  141. prefix = self._prefixes[prefix_as_string]
  142. assert not prefix.setup
  143. prefix.setup = True
  144. if not requirements:
  145. return
  146. args = [
  147. sys.executable, os.path.dirname(pip_location), 'install',
  148. '--ignore-installed', '--no-user', '--prefix', prefix.path,
  149. '--no-warn-script-location',
  150. ] # type: List[str]
  151. if logger.getEffectiveLevel() <= logging.DEBUG:
  152. args.append('-v')
  153. for format_control in ('no_binary', 'only_binary'):
  154. formats = getattr(finder.format_control, format_control)
  155. args.extend(('--' + format_control.replace('_', '-'),
  156. ','.join(sorted(formats or {':none:'}))))
  157. index_urls = finder.index_urls
  158. if index_urls:
  159. args.extend(['-i', index_urls[0]])
  160. for extra_index in index_urls[1:]:
  161. args.extend(['--extra-index-url', extra_index])
  162. else:
  163. args.append('--no-index')
  164. for link in finder.find_links:
  165. args.extend(['--find-links', link])
  166. for host in finder.trusted_hosts:
  167. args.extend(['--trusted-host', host])
  168. if finder.allow_all_prereleases:
  169. args.append('--pre')
  170. args.append('--')
  171. args.extend(requirements)
  172. with open_spinner(message) as spinner:
  173. call_subprocess(args, spinner=spinner)
  174. class NoOpBuildEnvironment(BuildEnvironment):
  175. """A no-op drop-in replacement for BuildEnvironment
  176. """
  177. def __init__(self):
  178. pass
  179. def __enter__(self):
  180. pass
  181. def __exit__(self, exc_type, exc_val, exc_tb):
  182. pass
  183. def cleanup(self):
  184. pass
  185. def install_requirements(self, finder, requirements, prefix, message):
  186. raise NotImplementedError()