resolver.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. """Dependency Resolution
  2. The dependency resolution in pip is performed as follows:
  3. for top-level requirements:
  4. a. only one spec allowed per project, regardless of conflicts or not.
  5. otherwise a "double requirement" exception is raised
  6. b. they override sub-dependency requirements.
  7. for sub-dependencies
  8. a. "first found, wins" (where the order is breadth first)
  9. """
  10. # The following comment should be removed at some point in the future.
  11. # mypy: strict-optional=False
  12. # mypy: disallow-untyped-defs=False
  13. import logging
  14. import sys
  15. from collections import defaultdict
  16. from itertools import chain
  17. from pip._vendor.packaging import specifiers
  18. from pip._internal.exceptions import (
  19. BestVersionAlreadyInstalled,
  20. DistributionNotFound,
  21. HashError,
  22. HashErrors,
  23. UnsupportedPythonVersion,
  24. )
  25. from pip._internal.req.req_install import check_invalid_constraint_type
  26. from pip._internal.req.req_set import RequirementSet
  27. from pip._internal.resolution.base import BaseResolver
  28. from pip._internal.utils.compatibility_tags import get_supported
  29. from pip._internal.utils.logging import indent_log
  30. from pip._internal.utils.misc import dist_in_usersite, normalize_version_info
  31. from pip._internal.utils.packaging import (
  32. check_requires_python,
  33. get_requires_python,
  34. )
  35. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  36. if MYPY_CHECK_RUNNING:
  37. from typing import DefaultDict, List, Optional, Set, Tuple
  38. from pip._vendor import pkg_resources
  39. from pip._internal.cache import WheelCache
  40. from pip._internal.distributions import AbstractDistribution
  41. from pip._internal.index.package_finder import PackageFinder
  42. from pip._internal.models.link import Link
  43. from pip._internal.operations.prepare import RequirementPreparer
  44. from pip._internal.req.req_install import InstallRequirement
  45. from pip._internal.resolution.base import InstallRequirementProvider
  46. DiscoveredDependencies = DefaultDict[str, List[InstallRequirement]]
  47. logger = logging.getLogger(__name__)
  48. def _check_dist_requires_python(
  49. dist, # type: pkg_resources.Distribution
  50. version_info, # type: Tuple[int, int, int]
  51. ignore_requires_python=False, # type: bool
  52. ):
  53. # type: (...) -> None
  54. """
  55. Check whether the given Python version is compatible with a distribution's
  56. "Requires-Python" value.
  57. :param version_info: A 3-tuple of ints representing the Python
  58. major-minor-micro version to check.
  59. :param ignore_requires_python: Whether to ignore the "Requires-Python"
  60. value if the given Python version isn't compatible.
  61. :raises UnsupportedPythonVersion: When the given Python version isn't
  62. compatible.
  63. """
  64. requires_python = get_requires_python(dist)
  65. try:
  66. is_compatible = check_requires_python(
  67. requires_python, version_info=version_info,
  68. )
  69. except specifiers.InvalidSpecifier as exc:
  70. logger.warning(
  71. "Package %r has an invalid Requires-Python: %s",
  72. dist.project_name, exc,
  73. )
  74. return
  75. if is_compatible:
  76. return
  77. version = '.'.join(map(str, version_info))
  78. if ignore_requires_python:
  79. logger.debug(
  80. 'Ignoring failed Requires-Python check for package %r: '
  81. '%s not in %r',
  82. dist.project_name, version, requires_python,
  83. )
  84. return
  85. raise UnsupportedPythonVersion(
  86. 'Package {!r} requires a different Python: {} not in {!r}'.format(
  87. dist.project_name, version, requires_python,
  88. ))
  89. class Resolver(BaseResolver):
  90. """Resolves which packages need to be installed/uninstalled to perform \
  91. the requested operation without breaking the requirements of any package.
  92. """
  93. _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
  94. def __init__(
  95. self,
  96. preparer, # type: RequirementPreparer
  97. finder, # type: PackageFinder
  98. wheel_cache, # type: Optional[WheelCache]
  99. make_install_req, # type: InstallRequirementProvider
  100. use_user_site, # type: bool
  101. ignore_dependencies, # type: bool
  102. ignore_installed, # type: bool
  103. ignore_requires_python, # type: bool
  104. force_reinstall, # type: bool
  105. upgrade_strategy, # type: str
  106. py_version_info=None, # type: Optional[Tuple[int, ...]]
  107. ):
  108. # type: (...) -> None
  109. super(Resolver, self).__init__()
  110. assert upgrade_strategy in self._allowed_strategies
  111. if py_version_info is None:
  112. py_version_info = sys.version_info[:3]
  113. else:
  114. py_version_info = normalize_version_info(py_version_info)
  115. self._py_version_info = py_version_info
  116. self.preparer = preparer
  117. self.finder = finder
  118. self.wheel_cache = wheel_cache
  119. self.upgrade_strategy = upgrade_strategy
  120. self.force_reinstall = force_reinstall
  121. self.ignore_dependencies = ignore_dependencies
  122. self.ignore_installed = ignore_installed
  123. self.ignore_requires_python = ignore_requires_python
  124. self.use_user_site = use_user_site
  125. self._make_install_req = make_install_req
  126. self._discovered_dependencies = \
  127. defaultdict(list) # type: DiscoveredDependencies
  128. def resolve(self, root_reqs, check_supported_wheels):
  129. # type: (List[InstallRequirement], bool) -> RequirementSet
  130. """Resolve what operations need to be done
  131. As a side-effect of this method, the packages (and their dependencies)
  132. are downloaded, unpacked and prepared for installation. This
  133. preparation is done by ``pip.operations.prepare``.
  134. Once PyPI has static dependency metadata available, it would be
  135. possible to move the preparation to become a step separated from
  136. dependency resolution.
  137. """
  138. requirement_set = RequirementSet(
  139. check_supported_wheels=check_supported_wheels
  140. )
  141. for req in root_reqs:
  142. if req.constraint:
  143. check_invalid_constraint_type(req)
  144. requirement_set.add_requirement(req)
  145. # Actually prepare the files, and collect any exceptions. Most hash
  146. # exceptions cannot be checked ahead of time, because
  147. # _populate_link() needs to be called before we can make decisions
  148. # based on link type.
  149. discovered_reqs = [] # type: List[InstallRequirement]
  150. hash_errors = HashErrors()
  151. for req in chain(requirement_set.all_requirements, discovered_reqs):
  152. try:
  153. discovered_reqs.extend(self._resolve_one(requirement_set, req))
  154. except HashError as exc:
  155. exc.req = req
  156. hash_errors.append(exc)
  157. if hash_errors:
  158. raise hash_errors
  159. return requirement_set
  160. def _is_upgrade_allowed(self, req):
  161. # type: (InstallRequirement) -> bool
  162. if self.upgrade_strategy == "to-satisfy-only":
  163. return False
  164. elif self.upgrade_strategy == "eager":
  165. return True
  166. else:
  167. assert self.upgrade_strategy == "only-if-needed"
  168. return req.user_supplied or req.constraint
  169. def _set_req_to_reinstall(self, req):
  170. # type: (InstallRequirement) -> None
  171. """
  172. Set a requirement to be installed.
  173. """
  174. # Don't uninstall the conflict if doing a user install and the
  175. # conflict is not a user install.
  176. if not self.use_user_site or dist_in_usersite(req.satisfied_by):
  177. req.should_reinstall = True
  178. req.satisfied_by = None
  179. def _check_skip_installed(self, req_to_install):
  180. # type: (InstallRequirement) -> Optional[str]
  181. """Check if req_to_install should be skipped.
  182. This will check if the req is installed, and whether we should upgrade
  183. or reinstall it, taking into account all the relevant user options.
  184. After calling this req_to_install will only have satisfied_by set to
  185. None if the req_to_install is to be upgraded/reinstalled etc. Any
  186. other value will be a dist recording the current thing installed that
  187. satisfies the requirement.
  188. Note that for vcs urls and the like we can't assess skipping in this
  189. routine - we simply identify that we need to pull the thing down,
  190. then later on it is pulled down and introspected to assess upgrade/
  191. reinstalls etc.
  192. :return: A text reason for why it was skipped, or None.
  193. """
  194. if self.ignore_installed:
  195. return None
  196. req_to_install.check_if_exists(self.use_user_site)
  197. if not req_to_install.satisfied_by:
  198. return None
  199. if self.force_reinstall:
  200. self._set_req_to_reinstall(req_to_install)
  201. return None
  202. if not self._is_upgrade_allowed(req_to_install):
  203. if self.upgrade_strategy == "only-if-needed":
  204. return 'already satisfied, skipping upgrade'
  205. return 'already satisfied'
  206. # Check for the possibility of an upgrade. For link-based
  207. # requirements we have to pull the tree down and inspect to assess
  208. # the version #, so it's handled way down.
  209. if not req_to_install.link:
  210. try:
  211. self.finder.find_requirement(req_to_install, upgrade=True)
  212. except BestVersionAlreadyInstalled:
  213. # Then the best version is installed.
  214. return 'already up-to-date'
  215. except DistributionNotFound:
  216. # No distribution found, so we squash the error. It will
  217. # be raised later when we re-try later to do the install.
  218. # Why don't we just raise here?
  219. pass
  220. self._set_req_to_reinstall(req_to_install)
  221. return None
  222. def _find_requirement_link(self, req):
  223. # type: (InstallRequirement) -> Optional[Link]
  224. upgrade = self._is_upgrade_allowed(req)
  225. best_candidate = self.finder.find_requirement(req, upgrade)
  226. if not best_candidate:
  227. return None
  228. # Log a warning per PEP 592 if necessary before returning.
  229. link = best_candidate.link
  230. if link.is_yanked:
  231. reason = link.yanked_reason or '<none given>'
  232. msg = (
  233. # Mark this as a unicode string to prevent
  234. # "UnicodeEncodeError: 'ascii' codec can't encode character"
  235. # in Python 2 when the reason contains non-ascii characters.
  236. u'The candidate selected for download or install is a '
  237. 'yanked version: {candidate}\n'
  238. 'Reason for being yanked: {reason}'
  239. ).format(candidate=best_candidate, reason=reason)
  240. logger.warning(msg)
  241. return link
  242. def _populate_link(self, req):
  243. # type: (InstallRequirement) -> None
  244. """Ensure that if a link can be found for this, that it is found.
  245. Note that req.link may still be None - if the requirement is already
  246. installed and not needed to be upgraded based on the return value of
  247. _is_upgrade_allowed().
  248. If preparer.require_hashes is True, don't use the wheel cache, because
  249. cached wheels, always built locally, have different hashes than the
  250. files downloaded from the index server and thus throw false hash
  251. mismatches. Furthermore, cached wheels at present have undeterministic
  252. contents due to file modification times.
  253. """
  254. if req.link is None:
  255. req.link = self._find_requirement_link(req)
  256. if self.wheel_cache is None or self.preparer.require_hashes:
  257. return
  258. cache_entry = self.wheel_cache.get_cache_entry(
  259. link=req.link,
  260. package_name=req.name,
  261. supported_tags=get_supported(),
  262. )
  263. if cache_entry is not None:
  264. logger.debug('Using cached wheel link: %s', cache_entry.link)
  265. if req.link is req.original_link and cache_entry.persistent:
  266. req.original_link_is_in_wheel_cache = True
  267. req.link = cache_entry.link
  268. def _get_abstract_dist_for(self, req):
  269. # type: (InstallRequirement) -> AbstractDistribution
  270. """Takes a InstallRequirement and returns a single AbstractDist \
  271. representing a prepared variant of the same.
  272. """
  273. if req.editable:
  274. return self.preparer.prepare_editable_requirement(req)
  275. # satisfied_by is only evaluated by calling _check_skip_installed,
  276. # so it must be None here.
  277. assert req.satisfied_by is None
  278. skip_reason = self._check_skip_installed(req)
  279. if req.satisfied_by:
  280. return self.preparer.prepare_installed_requirement(
  281. req, skip_reason
  282. )
  283. # We eagerly populate the link, since that's our "legacy" behavior.
  284. self._populate_link(req)
  285. abstract_dist = self.preparer.prepare_linked_requirement(req)
  286. # NOTE
  287. # The following portion is for determining if a certain package is
  288. # going to be re-installed/upgraded or not and reporting to the user.
  289. # This should probably get cleaned up in a future refactor.
  290. # req.req is only avail after unpack for URL
  291. # pkgs repeat check_if_exists to uninstall-on-upgrade
  292. # (#14)
  293. if not self.ignore_installed:
  294. req.check_if_exists(self.use_user_site)
  295. if req.satisfied_by:
  296. should_modify = (
  297. self.upgrade_strategy != "to-satisfy-only" or
  298. self.force_reinstall or
  299. self.ignore_installed or
  300. req.link.scheme == 'file'
  301. )
  302. if should_modify:
  303. self._set_req_to_reinstall(req)
  304. else:
  305. logger.info(
  306. 'Requirement already satisfied (use --upgrade to upgrade):'
  307. ' %s', req,
  308. )
  309. return abstract_dist
  310. def _resolve_one(
  311. self,
  312. requirement_set, # type: RequirementSet
  313. req_to_install, # type: InstallRequirement
  314. ):
  315. # type: (...) -> List[InstallRequirement]
  316. """Prepare a single requirements file.
  317. :return: A list of additional InstallRequirements to also install.
  318. """
  319. # Tell user what we are doing for this requirement:
  320. # obtain (editable), skipping, processing (local url), collecting
  321. # (remote url or package name)
  322. if req_to_install.constraint or req_to_install.prepared:
  323. return []
  324. req_to_install.prepared = True
  325. abstract_dist = self._get_abstract_dist_for(req_to_install)
  326. # Parse and return dependencies
  327. dist = abstract_dist.get_pkg_resources_distribution()
  328. # This will raise UnsupportedPythonVersion if the given Python
  329. # version isn't compatible with the distribution's Requires-Python.
  330. _check_dist_requires_python(
  331. dist, version_info=self._py_version_info,
  332. ignore_requires_python=self.ignore_requires_python,
  333. )
  334. more_reqs = [] # type: List[InstallRequirement]
  335. def add_req(subreq, extras_requested):
  336. sub_install_req = self._make_install_req(
  337. str(subreq),
  338. req_to_install,
  339. )
  340. parent_req_name = req_to_install.name
  341. to_scan_again, add_to_parent = requirement_set.add_requirement(
  342. sub_install_req,
  343. parent_req_name=parent_req_name,
  344. extras_requested=extras_requested,
  345. )
  346. if parent_req_name and add_to_parent:
  347. self._discovered_dependencies[parent_req_name].append(
  348. add_to_parent
  349. )
  350. more_reqs.extend(to_scan_again)
  351. with indent_log():
  352. # We add req_to_install before its dependencies, so that we
  353. # can refer to it when adding dependencies.
  354. if not requirement_set.has_requirement(req_to_install.name):
  355. # 'unnamed' requirements will get added here
  356. # 'unnamed' requirements can only come from being directly
  357. # provided by the user.
  358. assert req_to_install.user_supplied
  359. requirement_set.add_requirement(
  360. req_to_install, parent_req_name=None,
  361. )
  362. if not self.ignore_dependencies:
  363. if req_to_install.extras:
  364. logger.debug(
  365. "Installing extra requirements: %r",
  366. ','.join(req_to_install.extras),
  367. )
  368. missing_requested = sorted(
  369. set(req_to_install.extras) - set(dist.extras)
  370. )
  371. for missing in missing_requested:
  372. logger.warning(
  373. "%s does not provide the extra '%s'",
  374. dist, missing
  375. )
  376. available_requested = sorted(
  377. set(dist.extras) & set(req_to_install.extras)
  378. )
  379. for subreq in dist.requires(available_requested):
  380. add_req(subreq, extras_requested=available_requested)
  381. if not req_to_install.editable and not req_to_install.satisfied_by:
  382. # XXX: --no-install leads this to report 'Successfully
  383. # downloaded' for only non-editable reqs, even though we took
  384. # action on them.
  385. req_to_install.successfully_downloaded = True
  386. return more_reqs
  387. def get_installation_order(self, req_set):
  388. # type: (RequirementSet) -> List[InstallRequirement]
  389. """Create the installation order.
  390. The installation order is topological - requirements are installed
  391. before the requiring thing. We break cycles at an arbitrary point,
  392. and make no other guarantees.
  393. """
  394. # The current implementation, which we may change at any point
  395. # installs the user specified things in the order given, except when
  396. # dependencies must come earlier to achieve topological order.
  397. order = []
  398. ordered_reqs = set() # type: Set[InstallRequirement]
  399. def schedule(req):
  400. if req.satisfied_by or req in ordered_reqs:
  401. return
  402. if req.constraint:
  403. return
  404. ordered_reqs.add(req)
  405. for dep in self._discovered_dependencies[req.name]:
  406. schedule(dep)
  407. order.append(req)
  408. for install_req in req_set.requirements.values():
  409. schedule(install_req)
  410. return order