wheel_builder.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. """Orchestrator for building wheels from InstallRequirements.
  2. """
  3. import logging
  4. import os.path
  5. import re
  6. import shutil
  7. import zipfile
  8. from pip._vendor.packaging.utils import canonicalize_name, canonicalize_version
  9. from pip._vendor.packaging.version import InvalidVersion, Version
  10. from pip._vendor.pkg_resources import Distribution
  11. from pip._internal.exceptions import InvalidWheelFilename, UnsupportedWheel
  12. from pip._internal.models.link import Link
  13. from pip._internal.models.wheel import Wheel
  14. from pip._internal.operations.build.wheel import build_wheel_pep517
  15. from pip._internal.operations.build.wheel_legacy import build_wheel_legacy
  16. from pip._internal.utils.logging import indent_log
  17. from pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed
  18. from pip._internal.utils.setuptools_build import make_setuptools_clean_args
  19. from pip._internal.utils.subprocess import call_subprocess
  20. from pip._internal.utils.temp_dir import TempDirectory
  21. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  22. from pip._internal.utils.urls import path_to_url
  23. from pip._internal.utils.wheel import pkg_resources_distribution_for_wheel
  24. from pip._internal.vcs import vcs
  25. if MYPY_CHECK_RUNNING:
  26. from typing import Any, Callable, Iterable, List, Optional, Tuple
  27. from pip._internal.cache import WheelCache
  28. from pip._internal.req.req_install import InstallRequirement
  29. BinaryAllowedPredicate = Callable[[InstallRequirement], bool]
  30. BuildResult = Tuple[List[InstallRequirement], List[InstallRequirement]]
  31. logger = logging.getLogger(__name__)
  32. _egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.IGNORECASE)
  33. def _contains_egg_info(s):
  34. # type: (str) -> bool
  35. """Determine whether the string looks like an egg_info.
  36. :param s: The string to parse. E.g. foo-2.1
  37. """
  38. return bool(_egg_info_re.search(s))
  39. def _should_build(
  40. req, # type: InstallRequirement
  41. need_wheel, # type: bool
  42. check_binary_allowed, # type: BinaryAllowedPredicate
  43. ):
  44. # type: (...) -> bool
  45. """Return whether an InstallRequirement should be built into a wheel."""
  46. if req.constraint:
  47. # never build requirements that are merely constraints
  48. return False
  49. if req.is_wheel:
  50. if need_wheel:
  51. logger.info(
  52. 'Skipping %s, due to already being wheel.', req.name,
  53. )
  54. return False
  55. if need_wheel:
  56. # i.e. pip wheel, not pip install
  57. return True
  58. # From this point, this concerns the pip install command only
  59. # (need_wheel=False).
  60. if req.editable or not req.source_dir:
  61. return False
  62. if not check_binary_allowed(req):
  63. logger.info(
  64. "Skipping wheel build for %s, due to binaries "
  65. "being disabled for it.", req.name,
  66. )
  67. return False
  68. if not req.use_pep517 and not is_wheel_installed():
  69. # we don't build legacy requirements if wheel is not installed
  70. logger.info(
  71. "Using legacy 'setup.py install' for %s, "
  72. "since package 'wheel' is not installed.", req.name,
  73. )
  74. return False
  75. return True
  76. def should_build_for_wheel_command(
  77. req, # type: InstallRequirement
  78. ):
  79. # type: (...) -> bool
  80. return _should_build(
  81. req, need_wheel=True, check_binary_allowed=_always_true
  82. )
  83. def should_build_for_install_command(
  84. req, # type: InstallRequirement
  85. check_binary_allowed, # type: BinaryAllowedPredicate
  86. ):
  87. # type: (...) -> bool
  88. return _should_build(
  89. req, need_wheel=False, check_binary_allowed=check_binary_allowed
  90. )
  91. def _should_cache(
  92. req, # type: InstallRequirement
  93. ):
  94. # type: (...) -> Optional[bool]
  95. """
  96. Return whether a built InstallRequirement can be stored in the persistent
  97. wheel cache, assuming the wheel cache is available, and _should_build()
  98. has determined a wheel needs to be built.
  99. """
  100. if req.editable or not req.source_dir:
  101. # never cache editable requirements
  102. return False
  103. if req.link and req.link.is_vcs:
  104. # VCS checkout. Do not cache
  105. # unless it points to an immutable commit hash.
  106. assert not req.editable
  107. assert req.source_dir
  108. vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)
  109. assert vcs_backend
  110. if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):
  111. return True
  112. return False
  113. assert req.link
  114. base, ext = req.link.splitext()
  115. if _contains_egg_info(base):
  116. return True
  117. # Otherwise, do not cache.
  118. return False
  119. def _get_cache_dir(
  120. req, # type: InstallRequirement
  121. wheel_cache, # type: WheelCache
  122. ):
  123. # type: (...) -> str
  124. """Return the persistent or temporary cache directory where the built
  125. wheel need to be stored.
  126. """
  127. cache_available = bool(wheel_cache.cache_dir)
  128. assert req.link
  129. if cache_available and _should_cache(req):
  130. cache_dir = wheel_cache.get_path_for_link(req.link)
  131. else:
  132. cache_dir = wheel_cache.get_ephem_path_for_link(req.link)
  133. return cache_dir
  134. def _always_true(_):
  135. # type: (Any) -> bool
  136. return True
  137. def _get_metadata_version(dist):
  138. # type: (Distribution) -> Optional[Version]
  139. for line in dist.get_metadata_lines(dist.PKG_INFO):
  140. if line.lower().startswith("metadata-version:"):
  141. value = line.split(":", 1)[-1].strip()
  142. try:
  143. return Version(value)
  144. except InvalidVersion:
  145. msg = "Invalid Metadata-Version: {}".format(value)
  146. raise UnsupportedWheel(msg)
  147. raise UnsupportedWheel("Missing Metadata-Version")
  148. def _verify_one(req, wheel_path):
  149. # type: (InstallRequirement, str) -> None
  150. canonical_name = canonicalize_name(req.name)
  151. w = Wheel(os.path.basename(wheel_path))
  152. if canonicalize_name(w.name) != canonical_name:
  153. raise InvalidWheelFilename(
  154. "Wheel has unexpected file name: expected {!r}, "
  155. "got {!r}".format(canonical_name, w.name),
  156. )
  157. with zipfile.ZipFile(wheel_path, allowZip64=True) as zf:
  158. dist = pkg_resources_distribution_for_wheel(
  159. zf, canonical_name, wheel_path,
  160. )
  161. if canonicalize_version(dist.version) != canonicalize_version(w.version):
  162. raise InvalidWheelFilename(
  163. "Wheel has unexpected file name: expected {!r}, "
  164. "got {!r}".format(dist.version, w.version),
  165. )
  166. if (_get_metadata_version(dist) >= Version("1.2")
  167. and not isinstance(dist.parsed_version, Version)):
  168. raise UnsupportedWheel(
  169. "Metadata 1.2 mandates PEP 440 version, "
  170. "but {!r} is not".format(dist.version)
  171. )
  172. def _build_one(
  173. req, # type: InstallRequirement
  174. output_dir, # type: str
  175. verify, # type: bool
  176. build_options, # type: List[str]
  177. global_options, # type: List[str]
  178. ):
  179. # type: (...) -> Optional[str]
  180. """Build one wheel.
  181. :return: The filename of the built wheel, or None if the build failed.
  182. """
  183. try:
  184. ensure_dir(output_dir)
  185. except OSError as e:
  186. logger.warning(
  187. "Building wheel for %s failed: %s",
  188. req.name, e,
  189. )
  190. return None
  191. # Install build deps into temporary directory (PEP 518)
  192. with req.build_env:
  193. wheel_path = _build_one_inside_env(
  194. req, output_dir, build_options, global_options
  195. )
  196. if wheel_path and verify:
  197. try:
  198. _verify_one(req, wheel_path)
  199. except (InvalidWheelFilename, UnsupportedWheel) as e:
  200. logger.warning("Built wheel for %s is invalid: %s", req.name, e)
  201. return None
  202. return wheel_path
  203. def _build_one_inside_env(
  204. req, # type: InstallRequirement
  205. output_dir, # type: str
  206. build_options, # type: List[str]
  207. global_options, # type: List[str]
  208. ):
  209. # type: (...) -> Optional[str]
  210. with TempDirectory(kind="wheel") as temp_dir:
  211. assert req.name
  212. if req.use_pep517:
  213. assert req.metadata_directory
  214. wheel_path = build_wheel_pep517(
  215. name=req.name,
  216. backend=req.pep517_backend,
  217. metadata_directory=req.metadata_directory,
  218. build_options=build_options,
  219. tempd=temp_dir.path,
  220. )
  221. else:
  222. wheel_path = build_wheel_legacy(
  223. name=req.name,
  224. setup_py_path=req.setup_py_path,
  225. source_dir=req.unpacked_source_directory,
  226. global_options=global_options,
  227. build_options=build_options,
  228. tempd=temp_dir.path,
  229. )
  230. if wheel_path is not None:
  231. wheel_name = os.path.basename(wheel_path)
  232. dest_path = os.path.join(output_dir, wheel_name)
  233. try:
  234. wheel_hash, length = hash_file(wheel_path)
  235. shutil.move(wheel_path, dest_path)
  236. logger.info('Created wheel for %s: '
  237. 'filename=%s size=%d sha256=%s',
  238. req.name, wheel_name, length,
  239. wheel_hash.hexdigest())
  240. logger.info('Stored in directory: %s', output_dir)
  241. return dest_path
  242. except Exception as e:
  243. logger.warning(
  244. "Building wheel for %s failed: %s",
  245. req.name, e,
  246. )
  247. # Ignore return, we can't do anything else useful.
  248. if not req.use_pep517:
  249. _clean_one_legacy(req, global_options)
  250. return None
  251. def _clean_one_legacy(req, global_options):
  252. # type: (InstallRequirement, List[str]) -> bool
  253. clean_args = make_setuptools_clean_args(
  254. req.setup_py_path,
  255. global_options=global_options,
  256. )
  257. logger.info('Running setup.py clean for %s', req.name)
  258. try:
  259. call_subprocess(clean_args, cwd=req.source_dir)
  260. return True
  261. except Exception:
  262. logger.error('Failed cleaning build dir for %s', req.name)
  263. return False
  264. def build(
  265. requirements, # type: Iterable[InstallRequirement]
  266. wheel_cache, # type: WheelCache
  267. verify, # type: bool
  268. build_options, # type: List[str]
  269. global_options, # type: List[str]
  270. ):
  271. # type: (...) -> BuildResult
  272. """Build wheels.
  273. :return: The list of InstallRequirement that succeeded to build and
  274. the list of InstallRequirement that failed to build.
  275. """
  276. if not requirements:
  277. return [], []
  278. # Build the wheels.
  279. logger.info(
  280. 'Building wheels for collected packages: %s',
  281. ', '.join(req.name for req in requirements), # type: ignore
  282. )
  283. with indent_log():
  284. build_successes, build_failures = [], []
  285. for req in requirements:
  286. cache_dir = _get_cache_dir(req, wheel_cache)
  287. wheel_file = _build_one(
  288. req, cache_dir, verify, build_options, global_options
  289. )
  290. if wheel_file:
  291. # Update the link for this.
  292. req.link = Link(path_to_url(wheel_file))
  293. req.local_file_path = req.link.file_path
  294. assert req.link.is_wheel
  295. build_successes.append(req)
  296. else:
  297. build_failures.append(req)
  298. # notify success/failure
  299. if build_successes:
  300. logger.info(
  301. 'Successfully built %s',
  302. ' '.join([req.name for req in build_successes]), # type: ignore
  303. )
  304. if build_failures:
  305. logger.info(
  306. 'Failed to build %s',
  307. ' '.join([req.name for req in build_failures]), # type: ignore
  308. )
  309. # Return a list of requirements that failed to build
  310. return build_successes, build_failures