m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

730 lines
28 KiB

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