prepare.py 28 KB

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