package_finder.py 36 KB

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