package_finder.py 37 KB

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