package_finder.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. class BestCandidateResult:
  291. """A collection of candidates, returned by `PackageFinder.find_best_candidate`.
  292. This class is only intended to be instantiated by CandidateEvaluator's
  293. `compute_best_candidate()` method.
  294. """
  295. def __init__(
  296. self,
  297. candidates: List[InstallationCandidate],
  298. applicable_candidates: List[InstallationCandidate],
  299. best_candidate: Optional[InstallationCandidate],
  300. ) -> None:
  301. """
  302. :param candidates: A sequence of all available candidates found.
  303. :param applicable_candidates: The applicable candidates.
  304. :param best_candidate: The most preferred candidate found, or None
  305. if no applicable candidates were found.
  306. """
  307. assert set(applicable_candidates) <= set(candidates)
  308. if best_candidate is None:
  309. assert not applicable_candidates
  310. else:
  311. assert best_candidate in applicable_candidates
  312. self._applicable_candidates = applicable_candidates
  313. self._candidates = candidates
  314. self.best_candidate = best_candidate
  315. def iter_all(self) -> Iterable[InstallationCandidate]:
  316. """Iterate through all candidates."""
  317. return iter(self._candidates)
  318. def iter_applicable(self) -> Iterable[InstallationCandidate]:
  319. """Iterate through the applicable candidates."""
  320. return iter(self._applicable_candidates)
  321. class CandidateEvaluator:
  322. """
  323. Responsible for filtering and sorting candidates for installation based
  324. on what tags are valid.
  325. """
  326. @classmethod
  327. def create(
  328. cls,
  329. project_name: str,
  330. target_python: Optional[TargetPython] = None,
  331. prefer_binary: bool = False,
  332. allow_all_prereleases: bool = False,
  333. specifier: Optional[specifiers.BaseSpecifier] = None,
  334. hashes: Optional[Hashes] = None,
  335. ) -> "CandidateEvaluator":
  336. """Create a CandidateEvaluator object.
  337. :param target_python: The target Python interpreter to use when
  338. checking compatibility. If None (the default), a TargetPython
  339. object will be constructed from the running Python.
  340. :param specifier: An optional object implementing `filter`
  341. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  342. versions.
  343. :param hashes: An optional collection of allowed hashes.
  344. """
  345. if target_python is None:
  346. target_python = TargetPython()
  347. if specifier is None:
  348. specifier = specifiers.SpecifierSet()
  349. supported_tags = target_python.get_sorted_tags()
  350. return cls(
  351. project_name=project_name,
  352. supported_tags=supported_tags,
  353. specifier=specifier,
  354. prefer_binary=prefer_binary,
  355. allow_all_prereleases=allow_all_prereleases,
  356. hashes=hashes,
  357. )
  358. def __init__(
  359. self,
  360. project_name: str,
  361. supported_tags: List[Tag],
  362. specifier: specifiers.BaseSpecifier,
  363. prefer_binary: bool = False,
  364. allow_all_prereleases: bool = False,
  365. hashes: Optional[Hashes] = None,
  366. ) -> None:
  367. """
  368. :param supported_tags: The PEP 425 tags supported by the target
  369. Python in order of preference (most preferred first).
  370. """
  371. self._allow_all_prereleases = allow_all_prereleases
  372. self._hashes = hashes
  373. self._prefer_binary = prefer_binary
  374. self._project_name = project_name
  375. self._specifier = specifier
  376. self._supported_tags = supported_tags
  377. # Since the index of the tag in the _supported_tags list is used
  378. # as a priority, precompute a map from tag to index/priority to be
  379. # used in wheel.find_most_preferred_tag.
  380. self._wheel_tag_preferences = {
  381. tag: idx for idx, tag in enumerate(supported_tags)
  382. }
  383. def get_applicable_candidates(
  384. self,
  385. candidates: List[InstallationCandidate],
  386. ) -> List[InstallationCandidate]:
  387. """
  388. Return the applicable candidates from a list of candidates.
  389. """
  390. # Using None infers from the specifier instead.
  391. allow_prereleases = self._allow_all_prereleases or None
  392. specifier = self._specifier
  393. # We turn the version object into a str here because otherwise
  394. # when we're debundled but setuptools isn't, Python will see
  395. # packaging.version.Version and
  396. # pkg_resources._vendor.packaging.version.Version as different
  397. # types. This way we'll use a str as a common data interchange
  398. # format. If we stop using the pkg_resources provided specifier
  399. # and start using our own, we can drop the cast to str().
  400. candidates_and_versions = [(c, str(c.version)) for c in candidates]
  401. versions = set(
  402. specifier.filter(
  403. (v for _, v in candidates_and_versions),
  404. prereleases=allow_prereleases,
  405. )
  406. )
  407. applicable_candidates = [c for c, v in candidates_and_versions if v in versions]
  408. filtered_applicable_candidates = filter_unallowed_hashes(
  409. candidates=applicable_candidates,
  410. hashes=self._hashes,
  411. project_name=self._project_name,
  412. )
  413. return sorted(filtered_applicable_candidates, key=self._sort_key)
  414. def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey:
  415. """
  416. Function to pass as the `key` argument to a call to sorted() to sort
  417. InstallationCandidates by preference.
  418. Returns a tuple such that tuples sorting as greater using Python's
  419. default comparison operator are more preferred.
  420. The preference is as follows:
  421. First and foremost, candidates with allowed (matching) hashes are
  422. always preferred over candidates without matching hashes. This is
  423. because e.g. if the only candidate with an allowed hash is yanked,
  424. we still want to use that candidate.
  425. Second, excepting hash considerations, candidates that have been
  426. yanked (in the sense of PEP 592) are always less preferred than
  427. candidates that haven't been yanked. Then:
  428. If not finding wheels, they are sorted by version only.
  429. If finding wheels, then the sort order is by version, then:
  430. 1. existing installs
  431. 2. wheels ordered via Wheel.support_index_min(self._supported_tags)
  432. 3. source archives
  433. If prefer_binary was set, then all wheels are sorted above sources.
  434. Note: it was considered to embed this logic into the Link
  435. comparison operators, but then different sdist links
  436. with the same version, would have to be considered equal
  437. """
  438. valid_tags = self._supported_tags
  439. support_num = len(valid_tags)
  440. build_tag: BuildTag = ()
  441. binary_preference = 0
  442. link = candidate.link
  443. if link.is_wheel:
  444. # can raise InvalidWheelFilename
  445. wheel = Wheel(link.filename)
  446. try:
  447. pri = -(
  448. wheel.find_most_preferred_tag(
  449. valid_tags, self._wheel_tag_preferences
  450. )
  451. )
  452. except ValueError:
  453. raise UnsupportedWheel(
  454. f"{wheel.filename} is not a supported wheel for this platform. It "
  455. "can't be sorted."
  456. )
  457. if self._prefer_binary:
  458. binary_preference = 1
  459. if wheel.build_tag is not None:
  460. match = re.match(r"^(\d+)(.*)$", wheel.build_tag)
  461. assert match is not None, "guaranteed by filename validation"
  462. build_tag_groups = match.groups()
  463. build_tag = (int(build_tag_groups[0]), build_tag_groups[1])
  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. ) -> Optional[InstallationCandidate]:
  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: Optional[FormatControl] = None,
  513. candidate_prefs: Optional[CandidatePreferences] = None,
  514. ignore_requires_python: Optional[bool] = 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. # Don't include an allow_yanked default value to make sure each call
  537. # site considers whether yanked releases are allowed. This also causes
  538. # that decision to be made explicit in the calling code, which helps
  539. # people when reading the code.
  540. @classmethod
  541. def create(
  542. cls,
  543. link_collector: LinkCollector,
  544. selection_prefs: SelectionPreferences,
  545. target_python: Optional[TargetPython] = None,
  546. ) -> "PackageFinder":
  547. """Create a PackageFinder.
  548. :param selection_prefs: The candidate selection preferences, as a
  549. SelectionPreferences object.
  550. :param target_python: The target Python interpreter to use when
  551. checking compatibility. If None (the default), a TargetPython
  552. object will be constructed from the running Python.
  553. """
  554. if target_python is None:
  555. target_python = TargetPython()
  556. candidate_prefs = CandidatePreferences(
  557. prefer_binary=selection_prefs.prefer_binary,
  558. allow_all_prereleases=selection_prefs.allow_all_prereleases,
  559. )
  560. return cls(
  561. candidate_prefs=candidate_prefs,
  562. link_collector=link_collector,
  563. target_python=target_python,
  564. allow_yanked=selection_prefs.allow_yanked,
  565. format_control=selection_prefs.format_control,
  566. ignore_requires_python=selection_prefs.ignore_requires_python,
  567. )
  568. @property
  569. def target_python(self) -> TargetPython:
  570. return self._target_python
  571. @property
  572. def search_scope(self) -> SearchScope:
  573. return self._link_collector.search_scope
  574. @search_scope.setter
  575. def search_scope(self, search_scope: SearchScope) -> None:
  576. self._link_collector.search_scope = search_scope
  577. @property
  578. def find_links(self) -> List[str]:
  579. return self._link_collector.find_links
  580. @property
  581. def index_urls(self) -> List[str]:
  582. return self.search_scope.index_urls
  583. @property
  584. def trusted_hosts(self) -> Iterable[str]:
  585. for host_port in self._link_collector.session.pip_trusted_origins:
  586. yield build_netloc(*host_port)
  587. @property
  588. def allow_all_prereleases(self) -> bool:
  589. return self._candidate_prefs.allow_all_prereleases
  590. def set_allow_all_prereleases(self) -> None:
  591. self._candidate_prefs.allow_all_prereleases = True
  592. @property
  593. def prefer_binary(self) -> bool:
  594. return self._candidate_prefs.prefer_binary
  595. def set_prefer_binary(self) -> None:
  596. self._candidate_prefs.prefer_binary = True
  597. def requires_python_skipped_reasons(self) -> List[str]:
  598. reasons = {
  599. detail
  600. for _, result, detail in self._logged_links
  601. if result == LinkType.requires_python_mismatch
  602. }
  603. return sorted(reasons)
  604. def make_link_evaluator(self, project_name: str) -> LinkEvaluator:
  605. canonical_name = canonicalize_name(project_name)
  606. formats = self.format_control.get_allowed_formats(canonical_name)
  607. return LinkEvaluator(
  608. project_name=project_name,
  609. canonical_name=canonical_name,
  610. formats=formats,
  611. target_python=self._target_python,
  612. allow_yanked=self._allow_yanked,
  613. ignore_requires_python=self._ignore_requires_python,
  614. )
  615. def _sort_links(self, links: Iterable[Link]) -> List[Link]:
  616. """
  617. Returns elements of links in order, non-egg links first, egg links
  618. second, while eliminating duplicates
  619. """
  620. eggs, no_eggs = [], []
  621. seen: Set[Link] = set()
  622. for link in links:
  623. if link not in seen:
  624. seen.add(link)
  625. if link.egg_fragment:
  626. eggs.append(link)
  627. else:
  628. no_eggs.append(link)
  629. return no_eggs + eggs
  630. def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None:
  631. entry = (link, result, detail)
  632. if entry not in self._logged_links:
  633. # Put the link at the end so the reason is more visible and because
  634. # the link string is usually very long.
  635. logger.debug("Skipping link: %s: %s", detail, link)
  636. self._logged_links.add(entry)
  637. def get_install_candidate(
  638. self, link_evaluator: LinkEvaluator, link: Link
  639. ) -> Optional[InstallationCandidate]:
  640. """
  641. If the link is a candidate for install, convert it to an
  642. InstallationCandidate and return it. Otherwise, return None.
  643. """
  644. result, detail = link_evaluator.evaluate_link(link)
  645. if result != LinkType.candidate:
  646. self._log_skipped_link(link, result, detail)
  647. return None
  648. try:
  649. return InstallationCandidate(
  650. name=link_evaluator.project_name,
  651. link=link,
  652. version=detail,
  653. )
  654. except InvalidVersion:
  655. return None
  656. def evaluate_links(
  657. self, link_evaluator: LinkEvaluator, links: Iterable[Link]
  658. ) -> List[InstallationCandidate]:
  659. """
  660. Convert links that are candidates to InstallationCandidate objects.
  661. """
  662. candidates = []
  663. for link in self._sort_links(links):
  664. candidate = self.get_install_candidate(link_evaluator, link)
  665. if candidate is not None:
  666. candidates.append(candidate)
  667. return candidates
  668. def process_project_url(
  669. self, project_url: Link, link_evaluator: LinkEvaluator
  670. ) -> List[InstallationCandidate]:
  671. logger.debug(
  672. "Fetching project page and analyzing links: %s",
  673. project_url,
  674. )
  675. index_response = self._link_collector.fetch_response(project_url)
  676. if index_response is None:
  677. return []
  678. page_links = list(parse_links(index_response))
  679. with indent_log():
  680. package_links = self.evaluate_links(
  681. link_evaluator,
  682. links=page_links,
  683. )
  684. return package_links
  685. @functools.lru_cache(maxsize=None)
  686. def find_all_candidates(self, project_name: str) -> List[InstallationCandidate]:
  687. """Find all available InstallationCandidate for project_name
  688. This checks index_urls and find_links.
  689. All versions found are returned as an InstallationCandidate list.
  690. See LinkEvaluator.evaluate_link() for details on which files
  691. are accepted.
  692. """
  693. link_evaluator = self.make_link_evaluator(project_name)
  694. collected_sources = self._link_collector.collect_sources(
  695. project_name=project_name,
  696. candidates_from_page=functools.partial(
  697. self.process_project_url,
  698. link_evaluator=link_evaluator,
  699. ),
  700. )
  701. page_candidates_it = itertools.chain.from_iterable(
  702. source.page_candidates()
  703. for sources in collected_sources
  704. for source in sources
  705. if source is not None
  706. )
  707. page_candidates = list(page_candidates_it)
  708. file_links_it = itertools.chain.from_iterable(
  709. source.file_links()
  710. for sources in collected_sources
  711. for source in sources
  712. if source is not None
  713. )
  714. file_candidates = self.evaluate_links(
  715. link_evaluator,
  716. sorted(file_links_it, reverse=True),
  717. )
  718. if logger.isEnabledFor(logging.DEBUG) and file_candidates:
  719. paths = []
  720. for candidate in file_candidates:
  721. assert candidate.link.url # we need to have a URL
  722. try:
  723. paths.append(candidate.link.file_path)
  724. except Exception:
  725. paths.append(candidate.link.url) # it's not a local file
  726. logger.debug("Local files found: %s", ", ".join(paths))
  727. # This is an intentional priority ordering
  728. return file_candidates + page_candidates
  729. def make_candidate_evaluator(
  730. self,
  731. project_name: str,
  732. specifier: Optional[specifiers.BaseSpecifier] = None,
  733. hashes: Optional[Hashes] = None,
  734. ) -> CandidateEvaluator:
  735. """Create a CandidateEvaluator object to use."""
  736. candidate_prefs = self._candidate_prefs
  737. return CandidateEvaluator.create(
  738. project_name=project_name,
  739. target_python=self._target_python,
  740. prefer_binary=candidate_prefs.prefer_binary,
  741. allow_all_prereleases=candidate_prefs.allow_all_prereleases,
  742. specifier=specifier,
  743. hashes=hashes,
  744. )
  745. @functools.lru_cache(maxsize=None)
  746. def find_best_candidate(
  747. self,
  748. project_name: str,
  749. specifier: Optional[specifiers.BaseSpecifier] = None,
  750. hashes: Optional[Hashes] = None,
  751. ) -> BestCandidateResult:
  752. """Find matches for the given project and specifier.
  753. :param specifier: An optional object implementing `filter`
  754. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  755. versions.
  756. :return: A `BestCandidateResult` instance.
  757. """
  758. candidates = self.find_all_candidates(project_name)
  759. candidate_evaluator = self.make_candidate_evaluator(
  760. project_name=project_name,
  761. specifier=specifier,
  762. hashes=hashes,
  763. )
  764. return candidate_evaluator.compute_best_candidate(candidates)
  765. def find_requirement(
  766. self, req: InstallRequirement, upgrade: bool
  767. ) -> Optional[InstallationCandidate]:
  768. """Try to find a Link matching req
  769. Expects req, an InstallRequirement and upgrade, a boolean
  770. Returns a InstallationCandidate if found,
  771. Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
  772. """
  773. hashes = req.hashes(trust_internet=False)
  774. best_candidate_result = self.find_best_candidate(
  775. req.name,
  776. specifier=req.specifier,
  777. hashes=hashes,
  778. )
  779. best_candidate = best_candidate_result.best_candidate
  780. installed_version: Optional[_BaseVersion] = None
  781. if req.satisfied_by is not None:
  782. installed_version = req.satisfied_by.version
  783. def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str:
  784. # This repeated parse_version and str() conversion is needed to
  785. # handle different vendoring sources from pip and pkg_resources.
  786. # If we stop using the pkg_resources provided specifier and start
  787. # using our own, we can drop the cast to str().
  788. return (
  789. ", ".join(
  790. sorted(
  791. {str(c.version) for c in cand_iter},
  792. key=parse_version,
  793. )
  794. )
  795. or "none"
  796. )
  797. if installed_version is None and best_candidate is None:
  798. logger.critical(
  799. "Could not find a version that satisfies the requirement %s "
  800. "(from versions: %s)",
  801. req,
  802. _format_versions(best_candidate_result.iter_all()),
  803. )
  804. raise DistributionNotFound(f"No matching distribution found for {req}")
  805. def _should_install_candidate(
  806. candidate: Optional[InstallationCandidate],
  807. ) -> "TypeGuard[InstallationCandidate]":
  808. if installed_version is None:
  809. return True
  810. if best_candidate is None:
  811. return False
  812. return best_candidate.version > installed_version
  813. if not upgrade and installed_version is not None:
  814. if _should_install_candidate(best_candidate):
  815. logger.debug(
  816. "Existing installed version (%s) satisfies requirement "
  817. "(most up-to-date version is %s)",
  818. installed_version,
  819. best_candidate.version,
  820. )
  821. else:
  822. logger.debug(
  823. "Existing installed version (%s) is most up-to-date and "
  824. "satisfies requirement",
  825. installed_version,
  826. )
  827. return None
  828. if _should_install_candidate(best_candidate):
  829. logger.debug(
  830. "Using version %s (newest of versions: %s)",
  831. best_candidate.version,
  832. _format_versions(best_candidate_result.iter_applicable()),
  833. )
  834. return best_candidate
  835. # We have an existing version, and its the best version
  836. logger.debug(
  837. "Installed version (%s) is most up-to-date (past versions: %s)",
  838. installed_version,
  839. _format_versions(best_candidate_result.iter_applicable()),
  840. )
  841. raise BestVersionAlreadyInstalled
  842. def _find_name_version_sep(fragment: str, canonical_name: str) -> int:
  843. """Find the separator's index based on the package's canonical name.
  844. :param fragment: A <package>+<version> filename "fragment" (stem) or
  845. egg fragment.
  846. :param canonical_name: The package's canonical name.
  847. This function is needed since the canonicalized name does not necessarily
  848. have the same length as the egg info's name part. An example::
  849. >>> fragment = 'foo__bar-1.0'
  850. >>> canonical_name = 'foo-bar'
  851. >>> _find_name_version_sep(fragment, canonical_name)
  852. 8
  853. """
  854. # Project name and version must be separated by one single dash. Find all
  855. # occurrences of dashes; if the string in front of it matches the canonical
  856. # name, this is the one separating the name and version parts.
  857. for i, c in enumerate(fragment):
  858. if c != "-":
  859. continue
  860. if canonicalize_name(fragment[:i]) == canonical_name:
  861. return i
  862. raise ValueError(f"{fragment} does not match {canonical_name}")
  863. def _extract_version_from_fragment(fragment: str, canonical_name: str) -> Optional[str]:
  864. """Parse the version string from a <package>+<version> filename
  865. "fragment" (stem) or egg fragment.
  866. :param fragment: The string to parse. E.g. foo-2.1
  867. :param canonical_name: The canonicalized name of the package this
  868. belongs to.
  869. """
  870. try:
  871. version_start = _find_name_version_sep(fragment, canonical_name) + 1
  872. except ValueError:
  873. return None
  874. version = fragment[version_start:]
  875. if not version:
  876. return None
  877. return version