package_finder.py 36 KB

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