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