prepare.py 27 KB

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