prepare.py 27 KB

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