package_finder.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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.filetypes import WHEEL_EXTENSION
  24. from pip._internal.utils.logging import indent_log
  25. from pip._internal.utils.misc import build_netloc
  26. from pip._internal.utils.packaging import check_requires_python
  27. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  28. from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS
  29. from pip._internal.utils.urls import url_to_path
  30. if MYPY_CHECK_RUNNING:
  31. from typing import (
  32. FrozenSet, Iterable, List, Optional, Set, Text, Tuple, Union,
  33. )
  34. from pip._vendor.packaging.tags import Tag
  35. from pip._vendor.packaging.version import _BaseVersion
  36. from pip._internal.index.collector import LinkCollector
  37. from pip._internal.models.search_scope import SearchScope
  38. from pip._internal.req import InstallRequirement
  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[str]
  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: {}'.format(ext))
  153. if "binary" not in self._formats and ext == WHEEL_EXTENSION:
  154. reason = 'No binaries permitted for {}'.format(
  155. self.project_name)
  156. return (False, reason)
  157. if "macosx10" in link.path and ext == '.zip':
  158. return (False, 'macosx10 one')
  159. if ext == WHEEL_EXTENSION:
  160. try:
  161. wheel = Wheel(link.filename)
  162. except InvalidWheelFilename:
  163. return (False, 'invalid wheel filename')
  164. if canonicalize_name(wheel.name) != self._canonical_name:
  165. reason = 'wrong project name (not {})'.format(
  166. self.project_name)
  167. return (False, reason)
  168. supported_tags = self._target_python.get_tags()
  169. if not wheel.supported(supported_tags):
  170. # Include the wheel's tags in the reason string to
  171. # simplify troubleshooting compatibility issues.
  172. file_tags = wheel.get_formatted_file_tags()
  173. reason = (
  174. "none of the wheel's tags match: {}".format(
  175. ', '.join(file_tags)
  176. )
  177. )
  178. return (False, reason)
  179. version = wheel.version
  180. # This should be up by the self.ok_binary check, but see issue 2700.
  181. if "source" not in self._formats and ext != WHEEL_EXTENSION:
  182. reason = 'No sources permitted for {}'.format(self.project_name)
  183. return (False, reason)
  184. if not version:
  185. version = _extract_version_from_fragment(
  186. egg_info, self._canonical_name,
  187. )
  188. if not version:
  189. reason = 'Missing project version for {}'.format(self.project_name)
  190. return (False, reason)
  191. match = self._py_version_re.search(version)
  192. if match:
  193. version = version[:match.start()]
  194. py_version = match.group(1)
  195. if py_version != self._target_python.py_version:
  196. return (False, 'Python version is incorrect')
  197. supports_python = _check_link_requires_python(
  198. link, version_info=self._target_python.py_version_info,
  199. ignore_requires_python=self._ignore_requires_python,
  200. )
  201. if not supports_python:
  202. # Return None for the reason text to suppress calling
  203. # _log_skipped_link().
  204. return (False, None)
  205. logger.debug('Found link %s, version: %s', link, version)
  206. return (True, version)
  207. def filter_unallowed_hashes(
  208. candidates, # type: List[InstallationCandidate]
  209. hashes, # type: Hashes
  210. project_name, # type: str
  211. ):
  212. # type: (...) -> List[InstallationCandidate]
  213. """
  214. Filter out candidates whose hashes aren't allowed, and return a new
  215. list of candidates.
  216. If at least one candidate has an allowed hash, then all candidates with
  217. either an allowed hash or no hash specified are returned. Otherwise,
  218. the given candidates are returned.
  219. Including the candidates with no hash specified when there is a match
  220. allows a warning to be logged if there is a more preferred candidate
  221. with no hash specified. Returning all candidates in the case of no
  222. matches lets pip report the hash of the candidate that would otherwise
  223. have been installed (e.g. permitting the user to more easily update
  224. their requirements file with the desired hash).
  225. """
  226. if not hashes:
  227. logger.debug(
  228. 'Given no hashes to check %s links for project %r: '
  229. 'discarding no candidates',
  230. len(candidates),
  231. project_name,
  232. )
  233. # Make sure we're not returning back the given value.
  234. return list(candidates)
  235. matches_or_no_digest = []
  236. # Collect the non-matches for logging purposes.
  237. non_matches = []
  238. match_count = 0
  239. for candidate in candidates:
  240. link = candidate.link
  241. if not link.has_hash:
  242. pass
  243. elif link.is_hash_allowed(hashes=hashes):
  244. match_count += 1
  245. else:
  246. non_matches.append(candidate)
  247. continue
  248. matches_or_no_digest.append(candidate)
  249. if match_count:
  250. filtered = matches_or_no_digest
  251. else:
  252. # Make sure we're not returning back the given value.
  253. filtered = list(candidates)
  254. if len(filtered) == len(candidates):
  255. discard_message = 'discarding no candidates'
  256. else:
  257. discard_message = 'discarding {} non-matches:\n {}'.format(
  258. len(non_matches),
  259. '\n '.join(str(candidate.link) for candidate in non_matches)
  260. )
  261. logger.debug(
  262. 'Checked %s links for project %r against %s hashes '
  263. '(%s matches, %s no digest): %s',
  264. len(candidates),
  265. project_name,
  266. hashes.digest_count,
  267. match_count,
  268. len(matches_or_no_digest) - match_count,
  269. discard_message
  270. )
  271. return filtered
  272. class CandidatePreferences(object):
  273. """
  274. Encapsulates some of the preferences for filtering and sorting
  275. InstallationCandidate objects.
  276. """
  277. def __init__(
  278. self,
  279. prefer_binary=False, # type: bool
  280. allow_all_prereleases=False, # type: bool
  281. ):
  282. # type: (...) -> None
  283. """
  284. :param allow_all_prereleases: Whether to allow all pre-releases.
  285. """
  286. self.allow_all_prereleases = allow_all_prereleases
  287. self.prefer_binary = prefer_binary
  288. class BestCandidateResult(object):
  289. """A collection of candidates, returned by `PackageFinder.find_best_candidate`.
  290. This class is only intended to be instantiated by CandidateEvaluator's
  291. `compute_best_candidate()` method.
  292. """
  293. def __init__(
  294. self,
  295. candidates, # type: List[InstallationCandidate]
  296. applicable_candidates, # type: List[InstallationCandidate]
  297. best_candidate, # type: Optional[InstallationCandidate]
  298. ):
  299. # type: (...) -> None
  300. """
  301. :param candidates: A sequence of all available candidates found.
  302. :param applicable_candidates: The applicable candidates.
  303. :param best_candidate: The most preferred candidate found, or None
  304. if no applicable candidates were found.
  305. """
  306. assert set(applicable_candidates) <= set(candidates)
  307. if best_candidate is None:
  308. assert not applicable_candidates
  309. else:
  310. assert best_candidate in applicable_candidates
  311. self._applicable_candidates = applicable_candidates
  312. self._candidates = candidates
  313. self.best_candidate = best_candidate
  314. def iter_all(self):
  315. # type: () -> Iterable[InstallationCandidate]
  316. """Iterate through all candidates.
  317. """
  318. return iter(self._candidates)
  319. def iter_applicable(self):
  320. # type: () -> Iterable[InstallationCandidate]
  321. """Iterate through the applicable candidates.
  322. """
  323. return iter(self._applicable_candidates)
  324. class CandidateEvaluator(object):
  325. """
  326. Responsible for filtering and sorting candidates for installation based
  327. on what tags are valid.
  328. """
  329. @classmethod
  330. def create(
  331. cls,
  332. project_name, # type: str
  333. target_python=None, # type: Optional[TargetPython]
  334. prefer_binary=False, # type: bool
  335. allow_all_prereleases=False, # type: bool
  336. specifier=None, # type: Optional[specifiers.BaseSpecifier]
  337. hashes=None, # type: Optional[Hashes]
  338. ):
  339. # type: (...) -> CandidateEvaluator
  340. """Create a CandidateEvaluator object.
  341. :param target_python: The target Python interpreter to use when
  342. checking compatibility. If None (the default), a TargetPython
  343. object will be constructed from the running Python.
  344. :param specifier: An optional object implementing `filter`
  345. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  346. versions.
  347. :param hashes: An optional collection of allowed hashes.
  348. """
  349. if target_python is None:
  350. target_python = TargetPython()
  351. if specifier is None:
  352. specifier = specifiers.SpecifierSet()
  353. supported_tags = target_python.get_tags()
  354. return cls(
  355. project_name=project_name,
  356. supported_tags=supported_tags,
  357. specifier=specifier,
  358. prefer_binary=prefer_binary,
  359. allow_all_prereleases=allow_all_prereleases,
  360. hashes=hashes,
  361. )
  362. def __init__(
  363. self,
  364. project_name, # type: str
  365. supported_tags, # type: List[Tag]
  366. specifier, # type: specifiers.BaseSpecifier
  367. prefer_binary=False, # type: bool
  368. allow_all_prereleases=False, # type: bool
  369. hashes=None, # type: Optional[Hashes]
  370. ):
  371. # type: (...) -> None
  372. """
  373. :param supported_tags: The PEP 425 tags supported by the target
  374. Python in order of preference (most preferred first).
  375. """
  376. self._allow_all_prereleases = allow_all_prereleases
  377. self._hashes = hashes
  378. self._prefer_binary = prefer_binary
  379. self._project_name = project_name
  380. self._specifier = specifier
  381. self._supported_tags = supported_tags
  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. if not wheel.supported(valid_tags):
  450. raise UnsupportedWheel(
  451. "{} is not a supported wheel for this platform. It "
  452. "can't be sorted.".format(wheel.filename)
  453. )
  454. if self._prefer_binary:
  455. binary_preference = 1
  456. pri = -(wheel.support_index_min(valid_tags))
  457. if wheel.build_tag is not None:
  458. match = re.match(r'^(\d+)(.*)$', wheel.build_tag)
  459. build_tag_groups = match.groups()
  460. build_tag = (int(build_tag_groups[0]), build_tag_groups[1])
  461. else: # sdist
  462. pri = -(support_num)
  463. has_allowed_hash = int(link.is_hash_allowed(self._hashes))
  464. yank_value = -1 * int(link.is_yanked) # -1 for yanked.
  465. return (
  466. has_allowed_hash, yank_value, binary_preference, candidate.version,
  467. build_tag, pri,
  468. )
  469. def sort_best_candidate(
  470. self,
  471. candidates, # type: List[InstallationCandidate]
  472. ):
  473. # type: (...) -> Optional[InstallationCandidate]
  474. """
  475. Return the best candidate per the instance's sort order, or None if
  476. no candidate is acceptable.
  477. """
  478. if not candidates:
  479. return None
  480. best_candidate = max(candidates, key=self._sort_key)
  481. # Log a warning per PEP 592 if necessary before returning.
  482. link = best_candidate.link
  483. if link.is_yanked:
  484. reason = link.yanked_reason or '<none given>'
  485. msg = (
  486. # Mark this as a unicode string to prevent
  487. # "UnicodeEncodeError: 'ascii' codec can't encode character"
  488. # in Python 2 when the reason contains non-ascii characters.
  489. u'The candidate selected for download or install is a '
  490. 'yanked version: {candidate}\n'
  491. 'Reason for being yanked: {reason}'
  492. ).format(candidate=best_candidate, reason=reason)
  493. logger.warning(msg)
  494. return best_candidate
  495. def compute_best_candidate(
  496. self,
  497. candidates, # type: List[InstallationCandidate]
  498. ):
  499. # type: (...) -> BestCandidateResult
  500. """
  501. Compute and return a `BestCandidateResult` instance.
  502. """
  503. applicable_candidates = self.get_applicable_candidates(candidates)
  504. best_candidate = self.sort_best_candidate(applicable_candidates)
  505. return BestCandidateResult(
  506. candidates,
  507. applicable_candidates=applicable_candidates,
  508. best_candidate=best_candidate,
  509. )
  510. class PackageFinder(object):
  511. """This finds packages.
  512. This is meant to match easy_install's technique for looking for
  513. packages, by reading pages and looking for appropriate links.
  514. """
  515. def __init__(
  516. self,
  517. link_collector, # type: LinkCollector
  518. target_python, # type: TargetPython
  519. allow_yanked, # type: bool
  520. format_control=None, # type: Optional[FormatControl]
  521. candidate_prefs=None, # type: CandidatePreferences
  522. ignore_requires_python=None, # type: Optional[bool]
  523. ):
  524. # type: (...) -> None
  525. """
  526. This constructor is primarily meant to be used by the create() class
  527. method and from tests.
  528. :param format_control: A FormatControl object, used to control
  529. the selection of source packages / binary packages when consulting
  530. the index and links.
  531. :param candidate_prefs: Options to use when creating a
  532. CandidateEvaluator object.
  533. """
  534. if candidate_prefs is None:
  535. candidate_prefs = CandidatePreferences()
  536. format_control = format_control or FormatControl(set(), set())
  537. self._allow_yanked = allow_yanked
  538. self._candidate_prefs = candidate_prefs
  539. self._ignore_requires_python = ignore_requires_python
  540. self._link_collector = link_collector
  541. self._target_python = target_python
  542. self.format_control = format_control
  543. # These are boring links that have already been logged somehow.
  544. self._logged_links = set() # type: Set[Link]
  545. # Don't include an allow_yanked default value to make sure each call
  546. # site considers whether yanked releases are allowed. This also causes
  547. # that decision to be made explicit in the calling code, which helps
  548. # people when reading the code.
  549. @classmethod
  550. def create(
  551. cls,
  552. link_collector, # type: LinkCollector
  553. selection_prefs, # type: SelectionPreferences
  554. target_python=None, # type: Optional[TargetPython]
  555. ):
  556. # type: (...) -> PackageFinder
  557. """Create a PackageFinder.
  558. :param selection_prefs: The candidate selection preferences, as a
  559. SelectionPreferences object.
  560. :param target_python: The target Python interpreter to use when
  561. checking compatibility. If None (the default), a TargetPython
  562. object will be constructed from the running Python.
  563. """
  564. if target_python is None:
  565. target_python = TargetPython()
  566. candidate_prefs = CandidatePreferences(
  567. prefer_binary=selection_prefs.prefer_binary,
  568. allow_all_prereleases=selection_prefs.allow_all_prereleases,
  569. )
  570. return cls(
  571. candidate_prefs=candidate_prefs,
  572. link_collector=link_collector,
  573. target_python=target_python,
  574. allow_yanked=selection_prefs.allow_yanked,
  575. format_control=selection_prefs.format_control,
  576. ignore_requires_python=selection_prefs.ignore_requires_python,
  577. )
  578. @property
  579. def search_scope(self):
  580. # type: () -> SearchScope
  581. return self._link_collector.search_scope
  582. @search_scope.setter
  583. def search_scope(self, search_scope):
  584. # type: (SearchScope) -> None
  585. self._link_collector.search_scope = search_scope
  586. @property
  587. def find_links(self):
  588. # type: () -> List[str]
  589. return self._link_collector.find_links
  590. @property
  591. def index_urls(self):
  592. # type: () -> List[str]
  593. return self.search_scope.index_urls
  594. @property
  595. def trusted_hosts(self):
  596. # type: () -> Iterable[str]
  597. for host_port in self._link_collector.session.pip_trusted_origins:
  598. yield build_netloc(*host_port)
  599. @property
  600. def allow_all_prereleases(self):
  601. # type: () -> bool
  602. return self._candidate_prefs.allow_all_prereleases
  603. def set_allow_all_prereleases(self):
  604. # type: () -> None
  605. self._candidate_prefs.allow_all_prereleases = True
  606. def make_link_evaluator(self, project_name):
  607. # type: (str) -> LinkEvaluator
  608. canonical_name = canonicalize_name(project_name)
  609. formats = self.format_control.get_allowed_formats(canonical_name)
  610. return LinkEvaluator(
  611. project_name=project_name,
  612. canonical_name=canonical_name,
  613. formats=formats,
  614. target_python=self._target_python,
  615. allow_yanked=self._allow_yanked,
  616. ignore_requires_python=self._ignore_requires_python,
  617. )
  618. def _sort_links(self, links):
  619. # type: (Iterable[Link]) -> List[Link]
  620. """
  621. Returns elements of links in order, non-egg links first, egg links
  622. second, while eliminating duplicates
  623. """
  624. eggs, no_eggs = [], []
  625. seen = set() # type: Set[Link]
  626. for link in links:
  627. if link not in seen:
  628. seen.add(link)
  629. if link.egg_fragment:
  630. eggs.append(link)
  631. else:
  632. no_eggs.append(link)
  633. return no_eggs + eggs
  634. def _log_skipped_link(self, link, reason):
  635. # type: (Link, Text) -> None
  636. if link not in self._logged_links:
  637. # Mark this as a unicode string to prevent "UnicodeEncodeError:
  638. # 'ascii' codec can't encode character" in Python 2 when
  639. # the reason contains non-ascii characters.
  640. # Also, put the link at the end so the reason is more visible
  641. # and because the link string is usually very long.
  642. logger.debug(u'Skipping link: %s: %s', reason, link)
  643. self._logged_links.add(link)
  644. def get_install_candidate(self, link_evaluator, link):
  645. # type: (LinkEvaluator, Link) -> Optional[InstallationCandidate]
  646. """
  647. If the link is a candidate for install, convert it to an
  648. InstallationCandidate and return it. Otherwise, return None.
  649. """
  650. is_candidate, result = link_evaluator.evaluate_link(link)
  651. if not is_candidate:
  652. if result:
  653. self._log_skipped_link(link, reason=result)
  654. return None
  655. return InstallationCandidate(
  656. name=link_evaluator.project_name,
  657. link=link,
  658. # Convert the Text result to str since InstallationCandidate
  659. # accepts str.
  660. version=str(result),
  661. )
  662. def evaluate_links(self, link_evaluator, links):
  663. # type: (LinkEvaluator, Iterable[Link]) -> List[InstallationCandidate]
  664. """
  665. Convert links that are candidates to InstallationCandidate objects.
  666. """
  667. candidates = []
  668. for link in self._sort_links(links):
  669. candidate = self.get_install_candidate(link_evaluator, link)
  670. if candidate is not None:
  671. candidates.append(candidate)
  672. return candidates
  673. def process_project_url(self, project_url, link_evaluator):
  674. # type: (Link, LinkEvaluator) -> List[InstallationCandidate]
  675. logger.debug(
  676. 'Fetching project page and analyzing links: %s', project_url,
  677. )
  678. html_page = self._link_collector.fetch_page(project_url)
  679. if html_page is None:
  680. return []
  681. page_links = list(parse_links(html_page))
  682. with indent_log():
  683. package_links = self.evaluate_links(
  684. link_evaluator,
  685. links=page_links,
  686. )
  687. return package_links
  688. def find_all_candidates(self, project_name):
  689. # type: (str) -> List[InstallationCandidate]
  690. """Find all available InstallationCandidate for project_name
  691. This checks index_urls and find_links.
  692. All versions found are returned as an InstallationCandidate list.
  693. See LinkEvaluator.evaluate_link() for details on which files
  694. are accepted.
  695. """
  696. collected_links = self._link_collector.collect_links(project_name)
  697. link_evaluator = self.make_link_evaluator(project_name)
  698. find_links_versions = self.evaluate_links(
  699. link_evaluator,
  700. links=collected_links.find_links,
  701. )
  702. page_versions = []
  703. for project_url in collected_links.project_urls:
  704. package_links = self.process_project_url(
  705. project_url, link_evaluator=link_evaluator,
  706. )
  707. page_versions.extend(package_links)
  708. file_versions = self.evaluate_links(
  709. link_evaluator,
  710. links=collected_links.files,
  711. )
  712. if file_versions:
  713. file_versions.sort(reverse=True)
  714. logger.debug(
  715. 'Local files found: %s',
  716. ', '.join([
  717. url_to_path(candidate.link.url)
  718. for candidate in file_versions
  719. ])
  720. )
  721. # This is an intentional priority ordering
  722. return file_versions + find_links_versions + page_versions
  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. def find_best_candidate(
  742. self,
  743. project_name, # type: str
  744. specifier=None, # type: Optional[specifiers.BaseSpecifier]
  745. hashes=None, # type: Optional[Hashes]
  746. ):
  747. # type: (...) -> BestCandidateResult
  748. """Find matches for the given project and specifier.
  749. :param specifier: An optional object implementing `filter`
  750. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  751. versions.
  752. :return: A `BestCandidateResult` instance.
  753. """
  754. candidates = self.find_all_candidates(project_name)
  755. candidate_evaluator = self.make_candidate_evaluator(
  756. project_name=project_name,
  757. specifier=specifier,
  758. hashes=hashes,
  759. )
  760. return candidate_evaluator.compute_best_candidate(candidates)
  761. def find_requirement(self, req, upgrade):
  762. # type: (InstallRequirement, bool) -> Optional[Link]
  763. """Try to find a Link matching req
  764. Expects req, an InstallRequirement and upgrade, a boolean
  765. Returns a Link if found,
  766. Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
  767. """
  768. hashes = req.hashes(trust_internet=False)
  769. best_candidate_result = self.find_best_candidate(
  770. req.name, specifier=req.specifier, hashes=hashes,
  771. )
  772. best_candidate = best_candidate_result.best_candidate
  773. installed_version = None # type: Optional[_BaseVersion]
  774. if req.satisfied_by is not None:
  775. installed_version = parse_version(req.satisfied_by.version)
  776. def _format_versions(cand_iter):
  777. # type: (Iterable[InstallationCandidate]) -> str
  778. # This repeated parse_version and str() conversion is needed to
  779. # handle different vendoring sources from pip and pkg_resources.
  780. # If we stop using the pkg_resources provided specifier and start
  781. # using our own, we can drop the cast to str().
  782. return ", ".join(sorted(
  783. {str(c.version) for c in cand_iter},
  784. key=parse_version,
  785. )) or "none"
  786. if installed_version is None and best_candidate is None:
  787. logger.critical(
  788. 'Could not find a version that satisfies the requirement %s '
  789. '(from versions: %s)',
  790. req,
  791. _format_versions(best_candidate_result.iter_all()),
  792. )
  793. raise DistributionNotFound(
  794. 'No matching distribution found for {}'.format(
  795. req)
  796. )
  797. best_installed = False
  798. if installed_version and (
  799. best_candidate is None or
  800. best_candidate.version <= installed_version):
  801. best_installed = True
  802. if not upgrade and installed_version is not None:
  803. if best_installed:
  804. logger.debug(
  805. 'Existing installed version (%s) is most up-to-date and '
  806. 'satisfies requirement',
  807. installed_version,
  808. )
  809. else:
  810. logger.debug(
  811. 'Existing installed version (%s) satisfies requirement '
  812. '(most up-to-date version is %s)',
  813. installed_version,
  814. best_candidate.version,
  815. )
  816. return None
  817. if best_installed:
  818. # We have an existing version, and its the best version
  819. logger.debug(
  820. 'Installed version (%s) is most up-to-date (past versions: '
  821. '%s)',
  822. installed_version,
  823. _format_versions(best_candidate_result.iter_applicable()),
  824. )
  825. raise BestVersionAlreadyInstalled
  826. logger.debug(
  827. 'Using version %s (newest of versions: %s)',
  828. best_candidate.version,
  829. _format_versions(best_candidate_result.iter_applicable()),
  830. )
  831. return best_candidate.link
  832. def _find_name_version_sep(fragment, canonical_name):
  833. # type: (str, str) -> int
  834. """Find the separator's index based on the package's canonical name.
  835. :param fragment: A <package>+<version> filename "fragment" (stem) or
  836. egg fragment.
  837. :param canonical_name: The package's canonical name.
  838. This function is needed since the canonicalized name does not necessarily
  839. have the same length as the egg info's name part. An example::
  840. >>> fragment = 'foo__bar-1.0'
  841. >>> canonical_name = 'foo-bar'
  842. >>> _find_name_version_sep(fragment, canonical_name)
  843. 8
  844. """
  845. # Project name and version must be separated by one single dash. Find all
  846. # occurrences of dashes; if the string in front of it matches the canonical
  847. # name, this is the one separating the name and version parts.
  848. for i, c in enumerate(fragment):
  849. if c != "-":
  850. continue
  851. if canonicalize_name(fragment[:i]) == canonical_name:
  852. return i
  853. raise ValueError("{} does not match {}".format(fragment, canonical_name))
  854. def _extract_version_from_fragment(fragment, canonical_name):
  855. # type: (str, str) -> Optional[str]
  856. """Parse the version string from a <package>+<version> filename
  857. "fragment" (stem) or egg fragment.
  858. :param fragment: The string to parse. E.g. foo-2.1
  859. :param canonical_name: The canonicalized name of the package this
  860. belongs to.
  861. """
  862. try:
  863. version_start = _find_name_version_sep(fragment, canonical_name) + 1
  864. except ValueError:
  865. return None
  866. version = fragment[version_start:]
  867. if not version:
  868. return None
  869. return version