index.py 36 KB

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