package_finder.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. """Routines related to PyPI, indexes"""
  2. from __future__ import annotations
  3. import enum
  4. import functools
  5. import itertools
  6. import logging
  7. import re
  8. from collections.abc import Iterable
  9. from dataclasses import dataclass
  10. from typing import (
  11. TYPE_CHECKING,
  12. Optional,
  13. Union,
  14. )
  15. from pip._vendor.packaging import specifiers
  16. from pip._vendor.packaging.tags import Tag
  17. from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
  18. from pip._vendor.packaging.version import InvalidVersion, _BaseVersion
  19. from pip._vendor.packaging.version import parse as parse_version
  20. from pip._internal.exceptions import (
  21. BestVersionAlreadyInstalled,
  22. DistributionNotFound,
  23. InvalidWheelFilename,
  24. UnsupportedWheel,
  25. )
  26. from pip._internal.index.collector import LinkCollector, parse_links
  27. from pip._internal.models.candidate import InstallationCandidate
  28. from pip._internal.models.format_control import FormatControl
  29. from pip._internal.models.link import Link
  30. from pip._internal.models.search_scope import SearchScope
  31. from pip._internal.models.selection_prefs import SelectionPreferences
  32. from pip._internal.models.target_python import TargetPython
  33. from pip._internal.models.wheel import Wheel
  34. from pip._internal.req import InstallRequirement
  35. from pip._internal.utils._log import getLogger
  36. from pip._internal.utils.filetypes import WHEEL_EXTENSION
  37. from pip._internal.utils.hashes import Hashes
  38. from pip._internal.utils.logging import indent_log
  39. from pip._internal.utils.misc import build_netloc
  40. from pip._internal.utils.packaging import check_requires_python
  41. from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS
  42. if TYPE_CHECKING:
  43. from typing_extensions import TypeGuard
  44. __all__ = ["FormatControl", "BestCandidateResult", "PackageFinder"]
  45. logger = getLogger(__name__)
  46. BuildTag = Union[tuple[()], tuple[int, str]]
  47. CandidateSortingKey = tuple[int, int, int, _BaseVersion, Optional[int], BuildTag]
  48. def _check_link_requires_python(
  49. link: Link,
  50. version_info: tuple[int, int, int],
  51. ignore_requires_python: bool = False,
  52. ) -> bool:
  53. """
  54. Return whether the given Python version is compatible with a link's
  55. "Requires-Python" value.
  56. :param version_info: A 3-tuple of ints representing the Python
  57. major-minor-micro version to check.
  58. :param ignore_requires_python: Whether to ignore the "Requires-Python"
  59. value if the given Python version isn't compatible.
  60. """
  61. try:
  62. is_compatible = check_requires_python(
  63. link.requires_python,
  64. version_info=version_info,
  65. )
  66. except specifiers.InvalidSpecifier:
  67. logger.debug(
  68. "Ignoring invalid Requires-Python (%r) for link: %s",
  69. link.requires_python,
  70. link,
  71. )
  72. else:
  73. if not is_compatible:
  74. version = ".".join(map(str, version_info))
  75. if not ignore_requires_python:
  76. logger.verbose(
  77. "Link requires a different Python (%s not in: %r): %s",
  78. version,
  79. link.requires_python,
  80. link,
  81. )
  82. return False
  83. logger.debug(
  84. "Ignoring failed Requires-Python check (%s not in: %r) for link: %s",
  85. version,
  86. link.requires_python,
  87. link,
  88. )
  89. return True
  90. class LinkType(enum.Enum):
  91. candidate = enum.auto()
  92. different_project = enum.auto()
  93. yanked = enum.auto()
  94. format_unsupported = enum.auto()
  95. format_invalid = enum.auto()
  96. platform_mismatch = enum.auto()
  97. requires_python_mismatch = enum.auto()
  98. class LinkEvaluator:
  99. """
  100. Responsible for evaluating links for a particular project.
  101. """
  102. _py_version_re = re.compile(r"-py([123]\.?[0-9]?)$")
  103. # Don't include an allow_yanked default value to make sure each call
  104. # site considers whether yanked releases are allowed. This also causes
  105. # that decision to be made explicit in the calling code, which helps
  106. # people when reading the code.
  107. def __init__(
  108. self,
  109. project_name: str,
  110. canonical_name: NormalizedName,
  111. formats: frozenset[str],
  112. target_python: TargetPython,
  113. allow_yanked: bool,
  114. ignore_requires_python: bool | None = None,
  115. ) -> None:
  116. """
  117. :param project_name: The user supplied package name.
  118. :param canonical_name: The canonical package name.
  119. :param formats: The formats allowed for this package. Should be a set
  120. with 'binary' or 'source' or both in it.
  121. :param target_python: The target Python interpreter to use when
  122. evaluating link compatibility. This is used, for example, to
  123. check wheel compatibility, as well as when checking the Python
  124. version, e.g. the Python version embedded in a link filename
  125. (or egg fragment) and against an HTML link's optional PEP 503
  126. "data-requires-python" attribute.
  127. :param allow_yanked: Whether files marked as yanked (in the sense
  128. of PEP 592) are permitted to be candidates for install.
  129. :param ignore_requires_python: Whether to ignore incompatible
  130. PEP 503 "data-requires-python" values in HTML links. Defaults
  131. to False.
  132. """
  133. if ignore_requires_python is None:
  134. ignore_requires_python = False
  135. self._allow_yanked = allow_yanked
  136. self._canonical_name = canonical_name
  137. self._ignore_requires_python = ignore_requires_python
  138. self._formats = formats
  139. self._target_python = target_python
  140. self.project_name = project_name
  141. def evaluate_link(self, link: Link) -> tuple[LinkType, str]:
  142. """
  143. Determine whether a link is a candidate for installation.
  144. :return: A tuple (result, detail), where *result* is an enum
  145. representing whether the evaluation found a candidate, or the reason
  146. why one is not found. If a candidate is found, *detail* will be the
  147. candidate's version string; if one is not found, it contains the
  148. reason the link fails to qualify.
  149. """
  150. version = None
  151. if link.is_yanked and not self._allow_yanked:
  152. reason = link.yanked_reason or "<none given>"
  153. return (LinkType.yanked, f"yanked for reason: {reason}")
  154. if link.egg_fragment:
  155. egg_info = link.egg_fragment
  156. ext = link.ext
  157. else:
  158. egg_info, ext = link.splitext()
  159. if not ext:
  160. return (LinkType.format_unsupported, "not a file")
  161. if ext not in SUPPORTED_EXTENSIONS:
  162. return (
  163. LinkType.format_unsupported,
  164. f"unsupported archive format: {ext}",
  165. )
  166. if "binary" not in self._formats and ext == WHEEL_EXTENSION:
  167. reason = f"No binaries permitted for {self.project_name}"
  168. return (LinkType.format_unsupported, reason)
  169. if "macosx10" in link.path and ext == ".zip":
  170. return (LinkType.format_unsupported, "macosx10 one")
  171. if ext == WHEEL_EXTENSION:
  172. try:
  173. wheel = Wheel(link.filename)
  174. except InvalidWheelFilename:
  175. return (
  176. LinkType.format_invalid,
  177. "invalid wheel filename",
  178. )
  179. if wheel.name != self._canonical_name:
  180. reason = f"wrong project name (not {self.project_name})"
  181. return (LinkType.different_project, reason)
  182. supported_tags = self._target_python.get_unsorted_tags()
  183. if not wheel.supported(supported_tags):
  184. # Include the wheel's tags in the reason string to
  185. # simplify troubleshooting compatibility issues.
  186. file_tags = ", ".join(wheel.get_formatted_file_tags())
  187. reason = (
  188. f"none of the wheel's tags ({file_tags}) are compatible "
  189. f"(run pip debug --verbose to show compatible tags)"
  190. )
  191. return (LinkType.platform_mismatch, reason)
  192. version = wheel.version
  193. # This should be up by the self.ok_binary check, but see issue 2700.
  194. if "source" not in self._formats and ext != WHEEL_EXTENSION:
  195. reason = f"No sources permitted for {self.project_name}"
  196. return (LinkType.format_unsupported, reason)
  197. if not version:
  198. version = _extract_version_from_fragment(
  199. egg_info,
  200. self._canonical_name,
  201. )
  202. if not version:
  203. reason = f"Missing project version for {self.project_name}"
  204. return (LinkType.format_invalid, reason)
  205. match = self._py_version_re.search(version)
  206. if match:
  207. version = version[: match.start()]
  208. py_version = match.group(1)
  209. if py_version != self._target_python.py_version:
  210. return (
  211. LinkType.platform_mismatch,
  212. "Python version is incorrect",
  213. )
  214. supports_python = _check_link_requires_python(
  215. link,
  216. version_info=self._target_python.py_version_info,
  217. ignore_requires_python=self._ignore_requires_python,
  218. )
  219. if not supports_python:
  220. requires_python = link.requires_python
  221. if requires_python:
  222. def get_version_sort_key(v: str) -> tuple[int, ...]:
  223. return tuple(int(s) for s in v.split(".") if s.isdigit())
  224. requires_python = ",".join(
  225. sorted(
  226. (str(s) for s in specifiers.SpecifierSet(requires_python)),
  227. key=get_version_sort_key,
  228. )
  229. )
  230. reason = f"{version} Requires-Python {requires_python}"
  231. return (LinkType.requires_python_mismatch, reason)
  232. logger.debug("Found link %s, version: %s", link, version)
  233. return (LinkType.candidate, version)
  234. def filter_unallowed_hashes(
  235. candidates: list[InstallationCandidate],
  236. hashes: Hashes | None,
  237. project_name: str,
  238. ) -> list[InstallationCandidate]:
  239. """
  240. Filter out candidates whose hashes aren't allowed, and return a new
  241. list of candidates.
  242. If at least one candidate has an allowed hash, then all candidates with
  243. either an allowed hash or no hash specified are returned. Otherwise,
  244. the given candidates are returned.
  245. Including the candidates with no hash specified when there is a match
  246. allows a warning to be logged if there is a more preferred candidate
  247. with no hash specified. Returning all candidates in the case of no
  248. matches lets pip report the hash of the candidate that would otherwise
  249. have been installed (e.g. permitting the user to more easily update
  250. their requirements file with the desired hash).
  251. """
  252. if not hashes:
  253. logger.debug(
  254. "Given no hashes to check %s links for project %r: "
  255. "discarding no candidates",
  256. len(candidates),
  257. project_name,
  258. )
  259. # Make sure we're not returning back the given value.
  260. return list(candidates)
  261. matches_or_no_digest = []
  262. # Collect the non-matches for logging purposes.
  263. non_matches = []
  264. match_count = 0
  265. for candidate in candidates:
  266. link = candidate.link
  267. if not link.has_hash:
  268. pass
  269. elif link.is_hash_allowed(hashes=hashes):
  270. match_count += 1
  271. else:
  272. non_matches.append(candidate)
  273. continue
  274. matches_or_no_digest.append(candidate)
  275. if match_count:
  276. filtered = matches_or_no_digest
  277. else:
  278. # Make sure we're not returning back the given value.
  279. filtered = list(candidates)
  280. if len(filtered) == len(candidates):
  281. discard_message = "discarding no candidates"
  282. else:
  283. discard_message = "discarding {} non-matches:\n {}".format(
  284. len(non_matches),
  285. "\n ".join(str(candidate.link) for candidate in non_matches),
  286. )
  287. logger.debug(
  288. "Checked %s links for project %r against %s hashes "
  289. "(%s matches, %s no digest): %s",
  290. len(candidates),
  291. project_name,
  292. hashes.digest_count,
  293. match_count,
  294. len(matches_or_no_digest) - match_count,
  295. discard_message,
  296. )
  297. return filtered
  298. @dataclass
  299. class CandidatePreferences:
  300. """
  301. Encapsulates some of the preferences for filtering and sorting
  302. InstallationCandidate objects.
  303. """
  304. prefer_binary: bool = False
  305. allow_all_prereleases: bool = False
  306. @dataclass(frozen=True)
  307. class BestCandidateResult:
  308. """A collection of candidates, returned by `PackageFinder.find_best_candidate`.
  309. This class is only intended to be instantiated by CandidateEvaluator's
  310. `compute_best_candidate()` method.
  311. :param all_candidates: A sequence of all available candidates found.
  312. :param applicable_candidates: The applicable candidates.
  313. :param best_candidate: The most preferred candidate found, or None
  314. if no applicable candidates were found.
  315. """
  316. all_candidates: list[InstallationCandidate]
  317. applicable_candidates: list[InstallationCandidate]
  318. best_candidate: InstallationCandidate | None
  319. def __post_init__(self) -> None:
  320. assert set(self.applicable_candidates) <= set(self.all_candidates)
  321. if self.best_candidate is None:
  322. assert not self.applicable_candidates
  323. else:
  324. assert self.best_candidate in self.applicable_candidates
  325. class CandidateEvaluator:
  326. """
  327. Responsible for filtering and sorting candidates for installation based
  328. on what tags are valid.
  329. """
  330. @classmethod
  331. def create(
  332. cls,
  333. project_name: str,
  334. target_python: TargetPython | None = None,
  335. prefer_binary: bool = False,
  336. allow_all_prereleases: bool = False,
  337. specifier: specifiers.BaseSpecifier | None = None,
  338. hashes: Hashes | None = None,
  339. ) -> CandidateEvaluator:
  340. """Create a CandidateEvaluator object.
  341. :param target_python: The target Python interpreter to use when
  342. checking compatibility. If None (the default), a TargetPython
  343. object will be constructed from the running Python.
  344. :param specifier: An optional object implementing `filter`
  345. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  346. versions.
  347. :param hashes: An optional collection of allowed hashes.
  348. """
  349. if target_python is None:
  350. target_python = TargetPython()
  351. if specifier is None:
  352. specifier = specifiers.SpecifierSet()
  353. supported_tags = target_python.get_sorted_tags()
  354. return cls(
  355. project_name=project_name,
  356. supported_tags=supported_tags,
  357. specifier=specifier,
  358. prefer_binary=prefer_binary,
  359. allow_all_prereleases=allow_all_prereleases,
  360. hashes=hashes,
  361. )
  362. def __init__(
  363. self,
  364. project_name: str,
  365. supported_tags: list[Tag],
  366. specifier: specifiers.BaseSpecifier,
  367. prefer_binary: bool = False,
  368. allow_all_prereleases: bool = False,
  369. hashes: Hashes | None = None,
  370. ) -> None:
  371. """
  372. :param supported_tags: The PEP 425 tags supported by the target
  373. Python in order of preference (most preferred first).
  374. """
  375. self._allow_all_prereleases = allow_all_prereleases
  376. self._hashes = hashes
  377. self._prefer_binary = prefer_binary
  378. self._project_name = project_name
  379. self._specifier = specifier
  380. self._supported_tags = supported_tags
  381. # Since the index of the tag in the _supported_tags list is used
  382. # as a priority, precompute a map from tag to index/priority to be
  383. # used in wheel.find_most_preferred_tag.
  384. self._wheel_tag_preferences = {
  385. tag: idx for idx, tag in enumerate(supported_tags)
  386. }
  387. def get_applicable_candidates(
  388. self,
  389. candidates: list[InstallationCandidate],
  390. ) -> list[InstallationCandidate]:
  391. """
  392. Return the applicable candidates from a list of candidates.
  393. """
  394. # Using None infers from the specifier instead.
  395. allow_prereleases = self._allow_all_prereleases or None
  396. specifier = self._specifier
  397. # We turn the version object into a str here because otherwise
  398. # when we're debundled but setuptools isn't, Python will see
  399. # packaging.version.Version and
  400. # pkg_resources._vendor.packaging.version.Version as different
  401. # types. This way we'll use a str as a common data interchange
  402. # format. If we stop using the pkg_resources provided specifier
  403. # and start using our own, we can drop the cast to str().
  404. candidates_and_versions = [(c, str(c.version)) for c in candidates]
  405. versions = set(
  406. specifier.filter(
  407. (v for _, v in candidates_and_versions),
  408. prereleases=allow_prereleases,
  409. )
  410. )
  411. applicable_candidates = [c for c, v in candidates_and_versions if v in versions]
  412. filtered_applicable_candidates = filter_unallowed_hashes(
  413. candidates=applicable_candidates,
  414. hashes=self._hashes,
  415. project_name=self._project_name,
  416. )
  417. return sorted(filtered_applicable_candidates, key=self._sort_key)
  418. def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey:
  419. """
  420. Function to pass as the `key` argument to a call to sorted() to sort
  421. InstallationCandidates by preference.
  422. Returns a tuple such that tuples sorting as greater using Python's
  423. default comparison operator are more preferred.
  424. The preference is as follows:
  425. First and foremost, candidates with allowed (matching) hashes are
  426. always preferred over candidates without matching hashes. This is
  427. because e.g. if the only candidate with an allowed hash is yanked,
  428. we still want to use that candidate.
  429. Second, excepting hash considerations, candidates that have been
  430. yanked (in the sense of PEP 592) are always less preferred than
  431. candidates that haven't been yanked. Then:
  432. If not finding wheels, they are sorted by version only.
  433. If finding wheels, then the sort order is by version, then:
  434. 1. existing installs
  435. 2. wheels ordered via Wheel.support_index_min(self._supported_tags)
  436. 3. source archives
  437. If prefer_binary was set, then all wheels are sorted above sources.
  438. Note: it was considered to embed this logic into the Link
  439. comparison operators, but then different sdist links
  440. with the same version, would have to be considered equal
  441. """
  442. valid_tags = self._supported_tags
  443. support_num = len(valid_tags)
  444. build_tag: BuildTag = ()
  445. binary_preference = 0
  446. link = candidate.link
  447. if link.is_wheel:
  448. # can raise InvalidWheelFilename
  449. wheel = Wheel(link.filename)
  450. try:
  451. pri = -(
  452. wheel.find_most_preferred_tag(
  453. valid_tags, self._wheel_tag_preferences
  454. )
  455. )
  456. except ValueError:
  457. raise UnsupportedWheel(
  458. f"{wheel.filename} is not a supported wheel for this platform. It "
  459. "can't be sorted."
  460. )
  461. if self._prefer_binary:
  462. binary_preference = 1
  463. build_tag = wheel.build_tag
  464. else: # sdist
  465. pri = -(support_num)
  466. has_allowed_hash = int(link.is_hash_allowed(self._hashes))
  467. yank_value = -1 * int(link.is_yanked) # -1 for yanked.
  468. return (
  469. has_allowed_hash,
  470. yank_value,
  471. binary_preference,
  472. candidate.version,
  473. pri,
  474. build_tag,
  475. )
  476. def sort_best_candidate(
  477. self,
  478. candidates: list[InstallationCandidate],
  479. ) -> InstallationCandidate | None:
  480. """
  481. Return the best candidate per the instance's sort order, or None if
  482. no candidate is acceptable.
  483. """
  484. if not candidates:
  485. return None
  486. best_candidate = max(candidates, key=self._sort_key)
  487. return best_candidate
  488. def compute_best_candidate(
  489. self,
  490. candidates: list[InstallationCandidate],
  491. ) -> BestCandidateResult:
  492. """
  493. Compute and return a `BestCandidateResult` instance.
  494. """
  495. applicable_candidates = self.get_applicable_candidates(candidates)
  496. best_candidate = self.sort_best_candidate(applicable_candidates)
  497. return BestCandidateResult(
  498. candidates,
  499. applicable_candidates=applicable_candidates,
  500. best_candidate=best_candidate,
  501. )
  502. class PackageFinder:
  503. """This finds packages.
  504. This is meant to match easy_install's technique for looking for
  505. packages, by reading pages and looking for appropriate links.
  506. """
  507. def __init__(
  508. self,
  509. link_collector: LinkCollector,
  510. target_python: TargetPython,
  511. allow_yanked: bool,
  512. format_control: FormatControl | None = None,
  513. candidate_prefs: CandidatePreferences | None = None,
  514. ignore_requires_python: bool | None = None,
  515. ) -> None:
  516. """
  517. This constructor is primarily meant to be used by the create() class
  518. method and from tests.
  519. :param format_control: A FormatControl object, used to control
  520. the selection of source packages / binary packages when consulting
  521. the index and links.
  522. :param candidate_prefs: Options to use when creating a
  523. CandidateEvaluator object.
  524. """
  525. if candidate_prefs is None:
  526. candidate_prefs = CandidatePreferences()
  527. format_control = format_control or FormatControl(set(), set())
  528. self._allow_yanked = allow_yanked
  529. self._candidate_prefs = candidate_prefs
  530. self._ignore_requires_python = ignore_requires_python
  531. self._link_collector = link_collector
  532. self._target_python = target_python
  533. self.format_control = format_control
  534. # These are boring links that have already been logged somehow.
  535. self._logged_links: set[tuple[Link, LinkType, str]] = set()
  536. # Cache of the result of finding candidates
  537. self._all_candidates: dict[str, list[InstallationCandidate]] = {}
  538. self._best_candidates: dict[
  539. tuple[str, specifiers.BaseSpecifier | None, Hashes | None],
  540. BestCandidateResult,
  541. ] = {}
  542. # Don't include an allow_yanked default value to make sure each call
  543. # site considers whether yanked releases are allowed. This also causes
  544. # that decision to be made explicit in the calling code, which helps
  545. # people when reading the code.
  546. @classmethod
  547. def create(
  548. cls,
  549. link_collector: LinkCollector,
  550. selection_prefs: SelectionPreferences,
  551. target_python: TargetPython | None = None,
  552. ) -> PackageFinder:
  553. """Create a PackageFinder.
  554. :param selection_prefs: The candidate selection preferences, as a
  555. SelectionPreferences object.
  556. :param target_python: The target Python interpreter to use when
  557. checking compatibility. If None (the default), a TargetPython
  558. object will be constructed from the running Python.
  559. """
  560. if target_python is None:
  561. target_python = TargetPython()
  562. candidate_prefs = CandidatePreferences(
  563. prefer_binary=selection_prefs.prefer_binary,
  564. allow_all_prereleases=selection_prefs.allow_all_prereleases,
  565. )
  566. return cls(
  567. candidate_prefs=candidate_prefs,
  568. link_collector=link_collector,
  569. target_python=target_python,
  570. allow_yanked=selection_prefs.allow_yanked,
  571. format_control=selection_prefs.format_control,
  572. ignore_requires_python=selection_prefs.ignore_requires_python,
  573. )
  574. @property
  575. def target_python(self) -> TargetPython:
  576. return self._target_python
  577. @property
  578. def search_scope(self) -> SearchScope:
  579. return self._link_collector.search_scope
  580. @search_scope.setter
  581. def search_scope(self, search_scope: SearchScope) -> None:
  582. self._link_collector.search_scope = search_scope
  583. @property
  584. def find_links(self) -> list[str]:
  585. return self._link_collector.find_links
  586. @property
  587. def index_urls(self) -> list[str]:
  588. return self.search_scope.index_urls
  589. @property
  590. def proxy(self) -> str | None:
  591. return self._link_collector.session.pip_proxy
  592. @property
  593. def trusted_hosts(self) -> Iterable[str]:
  594. for host_port in self._link_collector.session.pip_trusted_origins:
  595. yield build_netloc(*host_port)
  596. @property
  597. def custom_cert(self) -> str | None:
  598. # session.verify is either a boolean (use default bundle/no SSL
  599. # verification) or a string path to a custom CA bundle to use. We only
  600. # care about the latter.
  601. verify = self._link_collector.session.verify
  602. return verify if isinstance(verify, str) else None
  603. @property
  604. def client_cert(self) -> str | None:
  605. cert = self._link_collector.session.cert
  606. assert not isinstance(cert, tuple), "pip only supports PEM client certs"
  607. return cert
  608. @property
  609. def allow_all_prereleases(self) -> bool:
  610. return self._candidate_prefs.allow_all_prereleases
  611. def set_allow_all_prereleases(self) -> None:
  612. self._candidate_prefs.allow_all_prereleases = True
  613. @property
  614. def prefer_binary(self) -> bool:
  615. return self._candidate_prefs.prefer_binary
  616. def set_prefer_binary(self) -> None:
  617. self._candidate_prefs.prefer_binary = True
  618. def requires_python_skipped_reasons(self) -> list[str]:
  619. reasons = {
  620. detail
  621. for _, result, detail in self._logged_links
  622. if result == LinkType.requires_python_mismatch
  623. }
  624. return sorted(reasons)
  625. def make_link_evaluator(self, project_name: str) -> LinkEvaluator:
  626. canonical_name = canonicalize_name(project_name)
  627. formats = self.format_control.get_allowed_formats(canonical_name)
  628. return LinkEvaluator(
  629. project_name=project_name,
  630. canonical_name=canonical_name,
  631. formats=formats,
  632. target_python=self._target_python,
  633. allow_yanked=self._allow_yanked,
  634. ignore_requires_python=self._ignore_requires_python,
  635. )
  636. def _sort_links(self, links: Iterable[Link]) -> list[Link]:
  637. """
  638. Returns elements of links in order, non-egg links first, egg links
  639. second, while eliminating duplicates
  640. """
  641. eggs, no_eggs = [], []
  642. seen: set[Link] = set()
  643. for link in links:
  644. if link not in seen:
  645. seen.add(link)
  646. if link.egg_fragment:
  647. eggs.append(link)
  648. else:
  649. no_eggs.append(link)
  650. return no_eggs + eggs
  651. def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None:
  652. entry = (link, result, detail)
  653. if entry not in self._logged_links:
  654. # Put the link at the end so the reason is more visible and because
  655. # the link string is usually very long.
  656. logger.debug("Skipping link: %s: %s", detail, link)
  657. self._logged_links.add(entry)
  658. def get_install_candidate(
  659. self, link_evaluator: LinkEvaluator, link: Link
  660. ) -> InstallationCandidate | None:
  661. """
  662. If the link is a candidate for install, convert it to an
  663. InstallationCandidate and return it. Otherwise, return None.
  664. """
  665. result, detail = link_evaluator.evaluate_link(link)
  666. if result != LinkType.candidate:
  667. self._log_skipped_link(link, result, detail)
  668. return None
  669. try:
  670. return InstallationCandidate(
  671. name=link_evaluator.project_name,
  672. link=link,
  673. version=detail,
  674. )
  675. except InvalidVersion:
  676. return None
  677. def evaluate_links(
  678. self, link_evaluator: LinkEvaluator, links: Iterable[Link]
  679. ) -> list[InstallationCandidate]:
  680. """
  681. Convert links that are candidates to InstallationCandidate objects.
  682. """
  683. candidates = []
  684. for link in self._sort_links(links):
  685. candidate = self.get_install_candidate(link_evaluator, link)
  686. if candidate is not None:
  687. candidates.append(candidate)
  688. return candidates
  689. def process_project_url(
  690. self, project_url: Link, link_evaluator: LinkEvaluator
  691. ) -> list[InstallationCandidate]:
  692. logger.debug(
  693. "Fetching project page and analyzing links: %s",
  694. project_url,
  695. )
  696. index_response = self._link_collector.fetch_response(project_url)
  697. if index_response is None:
  698. return []
  699. page_links = list(parse_links(index_response))
  700. with indent_log():
  701. package_links = self.evaluate_links(
  702. link_evaluator,
  703. links=page_links,
  704. )
  705. return package_links
  706. def find_all_candidates(self, project_name: str) -> list[InstallationCandidate]:
  707. """Find all available InstallationCandidate for project_name
  708. This checks index_urls and find_links.
  709. All versions found are returned as an InstallationCandidate list.
  710. See LinkEvaluator.evaluate_link() for details on which files
  711. are accepted.
  712. """
  713. if project_name in self._all_candidates:
  714. return self._all_candidates[project_name]
  715. link_evaluator = self.make_link_evaluator(project_name)
  716. collected_sources = self._link_collector.collect_sources(
  717. project_name=project_name,
  718. candidates_from_page=functools.partial(
  719. self.process_project_url,
  720. link_evaluator=link_evaluator,
  721. ),
  722. )
  723. page_candidates_it = itertools.chain.from_iterable(
  724. source.page_candidates()
  725. for sources in collected_sources
  726. for source in sources
  727. if source is not None
  728. )
  729. page_candidates = list(page_candidates_it)
  730. file_links_it = itertools.chain.from_iterable(
  731. source.file_links()
  732. for sources in collected_sources
  733. for source in sources
  734. if source is not None
  735. )
  736. file_candidates = self.evaluate_links(
  737. link_evaluator,
  738. sorted(file_links_it, reverse=True),
  739. )
  740. if logger.isEnabledFor(logging.DEBUG) and file_candidates:
  741. paths = []
  742. for candidate in file_candidates:
  743. assert candidate.link.url # we need to have a URL
  744. try:
  745. paths.append(candidate.link.file_path)
  746. except Exception:
  747. paths.append(candidate.link.url) # it's not a local file
  748. logger.debug("Local files found: %s", ", ".join(paths))
  749. # This is an intentional priority ordering
  750. self._all_candidates[project_name] = file_candidates + page_candidates
  751. return self._all_candidates[project_name]
  752. def make_candidate_evaluator(
  753. self,
  754. project_name: str,
  755. specifier: specifiers.BaseSpecifier | None = None,
  756. hashes: Hashes | None = None,
  757. ) -> CandidateEvaluator:
  758. """Create a CandidateEvaluator object to use."""
  759. candidate_prefs = self._candidate_prefs
  760. return CandidateEvaluator.create(
  761. project_name=project_name,
  762. target_python=self._target_python,
  763. prefer_binary=candidate_prefs.prefer_binary,
  764. allow_all_prereleases=candidate_prefs.allow_all_prereleases,
  765. specifier=specifier,
  766. hashes=hashes,
  767. )
  768. def find_best_candidate(
  769. self,
  770. project_name: str,
  771. specifier: specifiers.BaseSpecifier | None = None,
  772. hashes: Hashes | None = None,
  773. ) -> BestCandidateResult:
  774. """Find matches for the given project and specifier.
  775. :param specifier: An optional object implementing `filter`
  776. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  777. versions.
  778. :return: A `BestCandidateResult` instance.
  779. """
  780. if (project_name, specifier, hashes) in self._best_candidates:
  781. return self._best_candidates[project_name, specifier, hashes]
  782. candidates = self.find_all_candidates(project_name)
  783. candidate_evaluator = self.make_candidate_evaluator(
  784. project_name=project_name,
  785. specifier=specifier,
  786. hashes=hashes,
  787. )
  788. self._best_candidates[project_name, specifier, hashes] = (
  789. candidate_evaluator.compute_best_candidate(candidates)
  790. )
  791. return self._best_candidates[project_name, specifier, hashes]
  792. def find_requirement(
  793. self, req: InstallRequirement, upgrade: bool
  794. ) -> InstallationCandidate | None:
  795. """Try to find a Link matching req
  796. Expects req, an InstallRequirement and upgrade, a boolean
  797. Returns a InstallationCandidate if found,
  798. Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
  799. """
  800. name = req.name
  801. assert name is not None, "find_requirement() called with no name"
  802. hashes = req.hashes(trust_internet=False)
  803. best_candidate_result = self.find_best_candidate(
  804. name,
  805. specifier=req.specifier,
  806. hashes=hashes,
  807. )
  808. best_candidate = best_candidate_result.best_candidate
  809. installed_version: _BaseVersion | None = None
  810. if req.satisfied_by is not None:
  811. installed_version = req.satisfied_by.version
  812. def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str:
  813. # This repeated parse_version and str() conversion is needed to
  814. # handle different vendoring sources from pip and pkg_resources.
  815. # If we stop using the pkg_resources provided specifier and start
  816. # using our own, we can drop the cast to str().
  817. return (
  818. ", ".join(
  819. sorted(
  820. {str(c.version) for c in cand_iter},
  821. key=parse_version,
  822. )
  823. )
  824. or "none"
  825. )
  826. if installed_version is None and best_candidate is None:
  827. logger.critical(
  828. "Could not find a version that satisfies the requirement %s "
  829. "(from versions: %s)",
  830. req,
  831. _format_versions(best_candidate_result.all_candidates),
  832. )
  833. raise DistributionNotFound(f"No matching distribution found for {req}")
  834. def _should_install_candidate(
  835. candidate: InstallationCandidate | None,
  836. ) -> TypeGuard[InstallationCandidate]:
  837. if installed_version is None:
  838. return True
  839. if best_candidate is None:
  840. return False
  841. return best_candidate.version > installed_version
  842. if not upgrade and installed_version is not None:
  843. if _should_install_candidate(best_candidate):
  844. logger.debug(
  845. "Existing installed version (%s) satisfies requirement "
  846. "(most up-to-date version is %s)",
  847. installed_version,
  848. best_candidate.version,
  849. )
  850. else:
  851. logger.debug(
  852. "Existing installed version (%s) is most up-to-date and "
  853. "satisfies requirement",
  854. installed_version,
  855. )
  856. return None
  857. if _should_install_candidate(best_candidate):
  858. logger.debug(
  859. "Using version %s (newest of versions: %s)",
  860. best_candidate.version,
  861. _format_versions(best_candidate_result.applicable_candidates),
  862. )
  863. return best_candidate
  864. # We have an existing version, and its the best version
  865. logger.debug(
  866. "Installed version (%s) is most up-to-date (past versions: %s)",
  867. installed_version,
  868. _format_versions(best_candidate_result.applicable_candidates),
  869. )
  870. raise BestVersionAlreadyInstalled
  871. def _find_name_version_sep(fragment: str, canonical_name: str) -> int:
  872. """Find the separator's index based on the package's canonical name.
  873. :param fragment: A <package>+<version> filename "fragment" (stem) or
  874. egg fragment.
  875. :param canonical_name: The package's canonical name.
  876. This function is needed since the canonicalized name does not necessarily
  877. have the same length as the egg info's name part. An example::
  878. >>> fragment = 'foo__bar-1.0'
  879. >>> canonical_name = 'foo-bar'
  880. >>> _find_name_version_sep(fragment, canonical_name)
  881. 8
  882. """
  883. # Project name and version must be separated by one single dash. Find all
  884. # occurrences of dashes; if the string in front of it matches the canonical
  885. # name, this is the one separating the name and version parts.
  886. for i, c in enumerate(fragment):
  887. if c != "-":
  888. continue
  889. if canonicalize_name(fragment[:i]) == canonical_name:
  890. return i
  891. raise ValueError(f"{fragment} does not match {canonical_name}")
  892. def _extract_version_from_fragment(fragment: str, canonical_name: str) -> str | None:
  893. """Parse the version string from a <package>+<version> filename
  894. "fragment" (stem) or egg fragment.
  895. :param fragment: The string to parse. E.g. foo-2.1
  896. :param canonical_name: The canonicalized name of the package this
  897. belongs to.
  898. """
  899. try:
  900. version_start = _find_name_version_sep(fragment, canonical_name) + 1
  901. except ValueError:
  902. return None
  903. version = fragment[version_start:]
  904. if not version:
  905. return None
  906. return version