prepare.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. """Prepares a distribution for installation
  2. """
  3. # The following comment should be removed at some point in the future.
  4. # mypy: strict-optional=False
  5. import logging
  6. import mimetypes
  7. import os
  8. import shutil
  9. from typing import Dict, Iterable, List, Optional
  10. from pip._vendor.packaging.utils import canonicalize_name
  11. from pip._internal.distributions import make_distribution_for_install_requirement
  12. from pip._internal.distributions.installed import InstalledDistribution
  13. from pip._internal.exceptions import (
  14. DirectoryUrlHashUnsupported,
  15. HashMismatch,
  16. HashUnpinned,
  17. InstallationError,
  18. NetworkConnectionError,
  19. PreviousBuildDirError,
  20. VcsHashUnsupported,
  21. )
  22. from pip._internal.index.package_finder import PackageFinder
  23. from pip._internal.metadata import BaseDistribution
  24. from pip._internal.models.direct_url import ArchiveInfo
  25. from pip._internal.models.link import Link
  26. from pip._internal.models.wheel import Wheel
  27. from pip._internal.network.download import BatchDownloader, Downloader
  28. from pip._internal.network.lazy_wheel import (
  29. HTTPRangeRequestUnsupported,
  30. dist_from_wheel_url,
  31. )
  32. from pip._internal.network.session import PipSession
  33. from pip._internal.operations.build.build_tracker import BuildTracker
  34. from pip._internal.req.req_install import InstallRequirement
  35. from pip._internal.utils.direct_url_helpers import (
  36. direct_url_for_editable,
  37. direct_url_from_link,
  38. )
  39. from pip._internal.utils.hashes import Hashes, MissingHashes
  40. from pip._internal.utils.logging import indent_log
  41. from pip._internal.utils.misc import (
  42. display_path,
  43. hash_file,
  44. hide_url,
  45. is_installable_dir,
  46. )
  47. from pip._internal.utils.temp_dir import TempDirectory
  48. from pip._internal.utils.unpacking import unpack_file
  49. from pip._internal.vcs import vcs
  50. logger = logging.getLogger(__name__)
  51. def _get_prepared_distribution(
  52. req: InstallRequirement,
  53. build_tracker: BuildTracker,
  54. finder: PackageFinder,
  55. build_isolation: bool,
  56. check_build_deps: bool,
  57. ) -> BaseDistribution:
  58. """Prepare a distribution for installation."""
  59. abstract_dist = make_distribution_for_install_requirement(req)
  60. with build_tracker.track(req):
  61. abstract_dist.prepare_distribution_metadata(
  62. finder, build_isolation, check_build_deps
  63. )
  64. return abstract_dist.get_metadata_distribution()
  65. def unpack_vcs_link(link: Link, location: str, verbosity: int) -> None:
  66. vcs_backend = vcs.get_backend_for_scheme(link.scheme)
  67. assert vcs_backend is not None
  68. vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity)
  69. class File:
  70. def __init__(self, path: str, content_type: Optional[str]) -> None:
  71. self.path = path
  72. if content_type is None:
  73. self.content_type = mimetypes.guess_type(path)[0]
  74. else:
  75. self.content_type = content_type
  76. def get_http_url(
  77. link: Link,
  78. download: Downloader,
  79. download_dir: Optional[str] = None,
  80. hashes: Optional[Hashes] = None,
  81. ) -> File:
  82. temp_dir = TempDirectory(kind="unpack", globally_managed=True)
  83. # If a download dir is specified, is the file already downloaded there?
  84. already_downloaded_path = None
  85. if download_dir:
  86. already_downloaded_path = _check_download_dir(link, download_dir, hashes)
  87. if already_downloaded_path:
  88. from_path = already_downloaded_path
  89. content_type = None
  90. else:
  91. # let's download to a tmp dir
  92. from_path, content_type = download(link, temp_dir.path)
  93. if hashes:
  94. hashes.check_against_path(from_path)
  95. return File(from_path, content_type)
  96. def get_file_url(
  97. link: Link, download_dir: Optional[str] = None, hashes: Optional[Hashes] = None
  98. ) -> File:
  99. """Get file and optionally check its hash."""
  100. # If a download dir is specified, is the file already there and valid?
  101. already_downloaded_path = None
  102. if download_dir:
  103. already_downloaded_path = _check_download_dir(link, download_dir, hashes)
  104. if already_downloaded_path:
  105. from_path = already_downloaded_path
  106. else:
  107. from_path = link.file_path
  108. # If --require-hashes is off, `hashes` is either empty, the
  109. # link's embedded hash, or MissingHashes; it is required to
  110. # match. If --require-hashes is on, we are satisfied by any
  111. # hash in `hashes` matching: a URL-based or an option-based
  112. # one; no internet-sourced hash will be in `hashes`.
  113. if hashes:
  114. hashes.check_against_path(from_path)
  115. return File(from_path, None)
  116. def unpack_url(
  117. link: Link,
  118. location: str,
  119. download: Downloader,
  120. verbosity: int,
  121. download_dir: Optional[str] = None,
  122. hashes: Optional[Hashes] = None,
  123. ) -> Optional[File]:
  124. """Unpack link into location, downloading if required.
  125. :param hashes: A Hashes object, one of whose embedded hashes must match,
  126. or HashMismatch will be raised. If the Hashes is empty, no matches are
  127. required, and unhashable types of requirements (like VCS ones, which
  128. would ordinarily raise HashUnsupported) are allowed.
  129. """
  130. # non-editable vcs urls
  131. if link.is_vcs:
  132. unpack_vcs_link(link, location, verbosity=verbosity)
  133. return None
  134. assert not link.is_existing_dir()
  135. # file urls
  136. if link.is_file:
  137. file = get_file_url(link, download_dir, hashes=hashes)
  138. # http urls
  139. else:
  140. file = get_http_url(
  141. link,
  142. download,
  143. download_dir,
  144. hashes=hashes,
  145. )
  146. # unpack the archive to the build dir location. even when only downloading
  147. # archives, they have to be unpacked to parse dependencies, except wheels
  148. if not link.is_wheel:
  149. unpack_file(file.path, location, file.content_type)
  150. return file
  151. def _check_download_dir(
  152. link: Link, download_dir: str, hashes: Optional[Hashes]
  153. ) -> Optional[str]:
  154. """Check download_dir for previously downloaded file with correct hash
  155. If a correct file is found return its path else None
  156. """
  157. download_path = os.path.join(download_dir, link.filename)
  158. if not os.path.exists(download_path):
  159. return None
  160. # If already downloaded, does its hash match?
  161. logger.info("File was already downloaded %s", download_path)
  162. if hashes:
  163. try:
  164. hashes.check_against_path(download_path)
  165. except HashMismatch:
  166. logger.warning(
  167. "Previously-downloaded file %s has bad hash. Re-downloading.",
  168. download_path,
  169. )
  170. os.unlink(download_path)
  171. return None
  172. return download_path
  173. class RequirementPreparer:
  174. """Prepares a Requirement"""
  175. def __init__(
  176. self,
  177. build_dir: str,
  178. download_dir: Optional[str],
  179. src_dir: str,
  180. build_isolation: bool,
  181. check_build_deps: bool,
  182. build_tracker: BuildTracker,
  183. session: PipSession,
  184. progress_bar: str,
  185. finder: PackageFinder,
  186. require_hashes: bool,
  187. use_user_site: bool,
  188. lazy_wheel: bool,
  189. verbosity: int,
  190. ) -> None:
  191. super().__init__()
  192. self.src_dir = src_dir
  193. self.build_dir = build_dir
  194. self.build_tracker = build_tracker
  195. self._session = session
  196. self._download = Downloader(session, progress_bar)
  197. self._batch_download = BatchDownloader(session, progress_bar)
  198. self.finder = finder
  199. # Where still-packed archives should be written to. If None, they are
  200. # not saved, and are deleted immediately after unpacking.
  201. self.download_dir = download_dir
  202. # Is build isolation allowed?
  203. self.build_isolation = build_isolation
  204. # Should check build dependencies?
  205. self.check_build_deps = check_build_deps
  206. # Should hash-checking be required?
  207. self.require_hashes = require_hashes
  208. # Should install in user site-packages?
  209. self.use_user_site = use_user_site
  210. # Should wheels be downloaded lazily?
  211. self.use_lazy_wheel = lazy_wheel
  212. # How verbose should underlying tooling be?
  213. self.verbosity = verbosity
  214. # Memoized downloaded files, as mapping of url: path.
  215. self._downloaded: Dict[str, str] = {}
  216. # Previous "header" printed for a link-based InstallRequirement
  217. self._previous_requirement_header = ("", "")
  218. def _log_preparing_link(self, req: InstallRequirement) -> None:
  219. """Provide context for the requirement being prepared."""
  220. if req.link.is_file and not req.original_link_is_in_wheel_cache:
  221. message = "Processing %s"
  222. information = str(display_path(req.link.file_path))
  223. else:
  224. message = "Collecting %s"
  225. information = str(req.req or req)
  226. if (message, information) != self._previous_requirement_header:
  227. self._previous_requirement_header = (message, information)
  228. logger.info(message, information)
  229. if req.original_link_is_in_wheel_cache:
  230. with indent_log():
  231. logger.info("Using cached %s", req.link.filename)
  232. def _ensure_link_req_src_dir(
  233. self, req: InstallRequirement, parallel_builds: bool
  234. ) -> None:
  235. """Ensure source_dir of a linked InstallRequirement."""
  236. # Since source_dir is only set for editable requirements.
  237. if req.link.is_wheel:
  238. # We don't need to unpack wheels, so no need for a source
  239. # directory.
  240. return
  241. assert req.source_dir is None
  242. if req.link.is_existing_dir():
  243. # build local directories in-tree
  244. req.source_dir = req.link.file_path
  245. return
  246. # We always delete unpacked sdists after pip runs.
  247. req.ensure_has_source_dir(
  248. self.build_dir,
  249. autodelete=True,
  250. parallel_builds=parallel_builds,
  251. )
  252. # If a checkout exists, it's unwise to keep going. version
  253. # inconsistencies are logged later, but do not fail the
  254. # installation.
  255. # FIXME: this won't upgrade when there's an existing
  256. # package unpacked in `req.source_dir`
  257. # TODO: this check is now probably dead code
  258. if is_installable_dir(req.source_dir):
  259. raise PreviousBuildDirError(
  260. "pip can't proceed with requirements '{}' due to a"
  261. "pre-existing build directory ({}). This is likely "
  262. "due to a previous installation that failed . pip is "
  263. "being responsible and not assuming it can delete this. "
  264. "Please delete it and try again.".format(req, req.source_dir)
  265. )
  266. def _get_linked_req_hashes(self, req: InstallRequirement) -> Hashes:
  267. # By the time this is called, the requirement's link should have
  268. # been checked so we can tell what kind of requirements req is
  269. # and raise some more informative errors than otherwise.
  270. # (For example, we can raise VcsHashUnsupported for a VCS URL
  271. # rather than HashMissing.)
  272. if not self.require_hashes:
  273. return req.hashes(trust_internet=True)
  274. # We could check these first 2 conditions inside unpack_url
  275. # and save repetition of conditions, but then we would
  276. # report less-useful error messages for unhashable
  277. # requirements, complaining that there's no hash provided.
  278. if req.link.is_vcs:
  279. raise VcsHashUnsupported()
  280. if req.link.is_existing_dir():
  281. raise DirectoryUrlHashUnsupported()
  282. # Unpinned packages are asking for trouble when a new version
  283. # is uploaded. This isn't a security check, but it saves users
  284. # a surprising hash mismatch in the future.
  285. # file:/// URLs aren't pinnable, so don't complain about them
  286. # not being pinned.
  287. if req.original_link is None and not req.is_pinned:
  288. raise HashUnpinned()
  289. # If known-good hashes are missing for this requirement,
  290. # shim it with a facade object that will provoke hash
  291. # computation and then raise a HashMissing exception
  292. # showing the user what the hash should be.
  293. return req.hashes(trust_internet=False) or MissingHashes()
  294. def _fetch_metadata_using_lazy_wheel(
  295. self,
  296. link: Link,
  297. ) -> Optional[BaseDistribution]:
  298. """Fetch metadata using lazy wheel, if possible."""
  299. if not self.use_lazy_wheel:
  300. return None
  301. if self.require_hashes:
  302. logger.debug("Lazy wheel is not used as hash checking is required")
  303. return None
  304. if link.is_file or not link.is_wheel:
  305. logger.debug(
  306. "Lazy wheel is not used as %r does not points to a remote wheel",
  307. link,
  308. )
  309. return None
  310. wheel = Wheel(link.filename)
  311. name = canonicalize_name(wheel.name)
  312. logger.info(
  313. "Obtaining dependency information from %s %s",
  314. name,
  315. wheel.version,
  316. )
  317. url = link.url.split("#", 1)[0]
  318. try:
  319. return dist_from_wheel_url(name, url, self._session)
  320. except HTTPRangeRequestUnsupported:
  321. logger.debug("%s does not support range requests", url)
  322. return None
  323. def _complete_partial_requirements(
  324. self,
  325. partially_downloaded_reqs: Iterable[InstallRequirement],
  326. parallel_builds: bool = False,
  327. ) -> None:
  328. """Download any requirements which were only fetched by metadata."""
  329. # Download to a temporary directory. These will be copied over as
  330. # needed for downstream 'download', 'wheel', and 'install' commands.
  331. temp_dir = TempDirectory(kind="unpack", globally_managed=True).path
  332. # Map each link to the requirement that owns it. This allows us to set
  333. # `req.local_file_path` on the appropriate requirement after passing
  334. # all the links at once into BatchDownloader.
  335. links_to_fully_download: Dict[Link, InstallRequirement] = {}
  336. for req in partially_downloaded_reqs:
  337. assert req.link
  338. links_to_fully_download[req.link] = req
  339. batch_download = self._batch_download(
  340. links_to_fully_download.keys(),
  341. temp_dir,
  342. )
  343. for link, (filepath, _) in batch_download:
  344. logger.debug("Downloading link %s to %s", link, filepath)
  345. req = links_to_fully_download[link]
  346. req.local_file_path = filepath
  347. # This step is necessary to ensure all lazy wheels are processed
  348. # successfully by the 'download', 'wheel', and 'install' commands.
  349. for req in partially_downloaded_reqs:
  350. self._prepare_linked_requirement(req, parallel_builds)
  351. def prepare_linked_requirement(
  352. self, req: InstallRequirement, parallel_builds: bool = False
  353. ) -> BaseDistribution:
  354. """Prepare a requirement to be obtained from req.link."""
  355. assert req.link
  356. link = req.link
  357. self._log_preparing_link(req)
  358. with indent_log():
  359. # Check if the relevant file is already available
  360. # in the download directory
  361. file_path = None
  362. if self.download_dir is not None and link.is_wheel:
  363. hashes = self._get_linked_req_hashes(req)
  364. file_path = _check_download_dir(req.link, self.download_dir, hashes)
  365. if file_path is not None:
  366. # The file is already available, so mark it as downloaded
  367. self._downloaded[req.link.url] = file_path
  368. else:
  369. # The file is not available, attempt to fetch only metadata
  370. wheel_dist = self._fetch_metadata_using_lazy_wheel(link)
  371. if wheel_dist is not None:
  372. req.needs_more_preparation = True
  373. return wheel_dist
  374. # None of the optimizations worked, fully prepare the requirement
  375. return self._prepare_linked_requirement(req, parallel_builds)
  376. def prepare_linked_requirements_more(
  377. self, reqs: Iterable[InstallRequirement], parallel_builds: bool = False
  378. ) -> None:
  379. """Prepare linked requirements more, if needed."""
  380. reqs = [req for req in reqs if req.needs_more_preparation]
  381. for req in reqs:
  382. # Determine if any of these requirements were already downloaded.
  383. if self.download_dir is not None and req.link.is_wheel:
  384. hashes = self._get_linked_req_hashes(req)
  385. file_path = _check_download_dir(req.link, self.download_dir, hashes)
  386. if file_path is not None:
  387. self._downloaded[req.link.url] = file_path
  388. req.needs_more_preparation = False
  389. # Prepare requirements we found were already downloaded for some
  390. # reason. The other downloads will be completed separately.
  391. partially_downloaded_reqs: List[InstallRequirement] = []
  392. for req in reqs:
  393. if req.needs_more_preparation:
  394. partially_downloaded_reqs.append(req)
  395. else:
  396. self._prepare_linked_requirement(req, parallel_builds)
  397. # TODO: separate this part out from RequirementPreparer when the v1
  398. # resolver can be removed!
  399. self._complete_partial_requirements(
  400. partially_downloaded_reqs,
  401. parallel_builds=parallel_builds,
  402. )
  403. def _prepare_linked_requirement(
  404. self, req: InstallRequirement, parallel_builds: bool
  405. ) -> BaseDistribution:
  406. assert req.link
  407. link = req.link
  408. self._ensure_link_req_src_dir(req, parallel_builds)
  409. hashes = self._get_linked_req_hashes(req)
  410. if link.is_existing_dir():
  411. local_file = None
  412. elif link.url not in self._downloaded:
  413. try:
  414. local_file = unpack_url(
  415. link,
  416. req.source_dir,
  417. self._download,
  418. self.verbosity,
  419. self.download_dir,
  420. hashes,
  421. )
  422. except NetworkConnectionError as exc:
  423. raise InstallationError(
  424. "Could not install requirement {} because of HTTP "
  425. "error {} for URL {}".format(req, exc, link)
  426. )
  427. else:
  428. file_path = self._downloaded[link.url]
  429. if hashes:
  430. hashes.check_against_path(file_path)
  431. local_file = File(file_path, content_type=None)
  432. # If download_info is set, we got it from the wheel cache.
  433. if req.download_info is None:
  434. # Editables don't go through this function (see
  435. # prepare_editable_requirement).
  436. assert not req.editable
  437. req.download_info = direct_url_from_link(link, req.source_dir)
  438. # Make sure we have a hash in download_info. If we got it as part of the
  439. # URL, it will have been verified and we can rely on it. Otherwise we
  440. # compute it from the downloaded file.
  441. if (
  442. isinstance(req.download_info.info, ArchiveInfo)
  443. and not req.download_info.info.hash
  444. and local_file
  445. ):
  446. hash = hash_file(local_file.path)[0].hexdigest()
  447. req.download_info.info.hash = f"sha256={hash}"
  448. # For use in later processing,
  449. # preserve the file path on the requirement.
  450. if local_file:
  451. req.local_file_path = local_file.path
  452. dist = _get_prepared_distribution(
  453. req,
  454. self.build_tracker,
  455. self.finder,
  456. self.build_isolation,
  457. self.check_build_deps,
  458. )
  459. return dist
  460. def save_linked_requirement(self, req: InstallRequirement) -> None:
  461. assert self.download_dir is not None
  462. assert req.link is not None
  463. link = req.link
  464. if link.is_vcs or (link.is_existing_dir() and req.editable):
  465. # Make a .zip of the source_dir we already created.
  466. req.archive(self.download_dir)
  467. return
  468. if link.is_existing_dir():
  469. logger.debug(
  470. "Not copying link to destination directory "
  471. "since it is a directory: %s",
  472. link,
  473. )
  474. return
  475. if req.local_file_path is None:
  476. # No distribution was downloaded for this requirement.
  477. return
  478. download_location = os.path.join(self.download_dir, link.filename)
  479. if not os.path.exists(download_location):
  480. shutil.copy(req.local_file_path, download_location)
  481. download_path = display_path(download_location)
  482. logger.info("Saved %s", download_path)
  483. def prepare_editable_requirement(
  484. self,
  485. req: InstallRequirement,
  486. ) -> BaseDistribution:
  487. """Prepare an editable requirement."""
  488. assert req.editable, "cannot prepare a non-editable req as editable"
  489. logger.info("Obtaining %s", req)
  490. with indent_log():
  491. if self.require_hashes:
  492. raise InstallationError(
  493. "The editable requirement {} cannot be installed when "
  494. "requiring hashes, because there is no single file to "
  495. "hash.".format(req)
  496. )
  497. req.ensure_has_source_dir(self.src_dir)
  498. req.update_editable()
  499. assert req.source_dir
  500. req.download_info = direct_url_for_editable(req.unpacked_source_directory)
  501. dist = _get_prepared_distribution(
  502. req,
  503. self.build_tracker,
  504. self.finder,
  505. self.build_isolation,
  506. self.check_build_deps,
  507. )
  508. req.check_if_exists(self.use_user_site)
  509. return dist
  510. def prepare_installed_requirement(
  511. self,
  512. req: InstallRequirement,
  513. skip_reason: str,
  514. ) -> BaseDistribution:
  515. """Prepare an already-installed requirement."""
  516. assert req.satisfied_by, "req should have been satisfied but isn't"
  517. assert skip_reason is not None, (
  518. "did not get skip reason skipped but req.satisfied_by "
  519. "is set to {}".format(req.satisfied_by)
  520. )
  521. logger.info(
  522. "Requirement %s: %s (%s)", skip_reason, req, req.satisfied_by.version
  523. )
  524. with indent_log():
  525. if self.require_hashes:
  526. logger.debug(
  527. "Since it is already installed, we are trusting this "
  528. "package without checking its hash. To ensure a "
  529. "completely repeatable environment, install into an "
  530. "empty virtualenv."
  531. )
  532. return InstalledDistribution(req).get_metadata_distribution()