package_finder.py 37 KB

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