resolver.py 18 KB

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