resolver.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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_set import RequirementSet
  26. from pip._internal.resolution.base import BaseResolver
  27. from pip._internal.utils.compatibility_tags import get_supported
  28. from pip._internal.utils.logging import indent_log
  29. from pip._internal.utils.misc import dist_in_usersite, normalize_version_info
  30. from pip._internal.utils.packaging import (
  31. check_requires_python,
  32. get_requires_python,
  33. )
  34. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  35. if MYPY_CHECK_RUNNING:
  36. from typing import DefaultDict, List, Optional, Set, Tuple
  37. from pip._vendor import pkg_resources
  38. from pip._internal.cache import WheelCache
  39. from pip._internal.distributions import AbstractDistribution
  40. from pip._internal.index.package_finder import PackageFinder
  41. from pip._internal.operations.prepare import RequirementPreparer
  42. from pip._internal.req.req_install import InstallRequirement
  43. from pip._internal.resolution.base import InstallRequirementProvider
  44. DiscoveredDependencies = DefaultDict[str, List[InstallRequirement]]
  45. logger = logging.getLogger(__name__)
  46. def _check_dist_requires_python(
  47. dist, # type: pkg_resources.Distribution
  48. version_info, # type: Tuple[int, int, int]
  49. ignore_requires_python=False, # type: bool
  50. ):
  51. # type: (...) -> None
  52. """
  53. Check whether the given Python version is compatible with a distribution'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. :raises UnsupportedPythonVersion: When the given Python version isn't
  60. compatible.
  61. """
  62. requires_python = get_requires_python(dist)
  63. try:
  64. is_compatible = check_requires_python(
  65. requires_python, version_info=version_info,
  66. )
  67. except specifiers.InvalidSpecifier as exc:
  68. logger.warning(
  69. "Package %r has an invalid Requires-Python: %s",
  70. dist.project_name, exc,
  71. )
  72. return
  73. if is_compatible:
  74. return
  75. version = '.'.join(map(str, version_info))
  76. if ignore_requires_python:
  77. logger.debug(
  78. 'Ignoring failed Requires-Python check for package %r: '
  79. '%s not in %r',
  80. dist.project_name, version, requires_python,
  81. )
  82. return
  83. raise UnsupportedPythonVersion(
  84. 'Package {!r} requires a different Python: {} not in {!r}'.format(
  85. dist.project_name, version, requires_python,
  86. ))
  87. class Resolver(BaseResolver):
  88. """Resolves which packages need to be installed/uninstalled to perform \
  89. the requested operation without breaking the requirements of any package.
  90. """
  91. _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"}
  92. def __init__(
  93. self,
  94. preparer, # type: RequirementPreparer
  95. finder, # type: PackageFinder
  96. wheel_cache, # type: Optional[WheelCache]
  97. make_install_req, # type: InstallRequirementProvider
  98. use_user_site, # type: bool
  99. ignore_dependencies, # type: bool
  100. ignore_installed, # type: bool
  101. ignore_requires_python, # type: bool
  102. force_reinstall, # type: bool
  103. upgrade_strategy, # type: str
  104. py_version_info=None, # type: Optional[Tuple[int, ...]]
  105. ):
  106. # type: (...) -> None
  107. super(Resolver, self).__init__()
  108. assert upgrade_strategy in self._allowed_strategies
  109. if py_version_info is None:
  110. py_version_info = sys.version_info[:3]
  111. else:
  112. py_version_info = normalize_version_info(py_version_info)
  113. self._py_version_info = py_version_info
  114. self.preparer = preparer
  115. self.finder = finder
  116. self.wheel_cache = wheel_cache
  117. self.upgrade_strategy = upgrade_strategy
  118. self.force_reinstall = force_reinstall
  119. self.ignore_dependencies = ignore_dependencies
  120. self.ignore_installed = ignore_installed
  121. self.ignore_requires_python = ignore_requires_python
  122. self.use_user_site = use_user_site
  123. self._make_install_req = make_install_req
  124. self._discovered_dependencies = \
  125. defaultdict(list) # type: DiscoveredDependencies
  126. def resolve(self, root_reqs, check_supported_wheels):
  127. # type: (List[InstallRequirement], bool) -> RequirementSet
  128. """Resolve what operations need to be done
  129. As a side-effect of this method, the packages (and their dependencies)
  130. are downloaded, unpacked and prepared for installation. This
  131. preparation is done by ``pip.operations.prepare``.
  132. Once PyPI has static dependency metadata available, it would be
  133. possible to move the preparation to become a step separated from
  134. dependency resolution.
  135. """
  136. requirement_set = RequirementSet(
  137. check_supported_wheels=check_supported_wheels
  138. )
  139. for req in root_reqs:
  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(root_reqs, 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.is_direct
  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 _populate_link(self, req):
  219. # type: (InstallRequirement) -> None
  220. """Ensure that if a link can be found for this, that it is found.
  221. Note that req.link may still be None - if the requirement is already
  222. installed and not needed to be upgraded based on the return value of
  223. _is_upgrade_allowed().
  224. If preparer.require_hashes is True, don't use the wheel cache, because
  225. cached wheels, always built locally, have different hashes than the
  226. files downloaded from the index server and thus throw false hash
  227. mismatches. Furthermore, cached wheels at present have undeterministic
  228. contents due to file modification times.
  229. """
  230. upgrade = self._is_upgrade_allowed(req)
  231. if req.link is None:
  232. req.link = self.finder.find_requirement(req, upgrade)
  233. if self.wheel_cache is None or self.preparer.require_hashes:
  234. return
  235. cache_entry = self.wheel_cache.get_cache_entry(
  236. link=req.link,
  237. package_name=req.name,
  238. supported_tags=get_supported(),
  239. )
  240. if cache_entry is not None:
  241. logger.debug('Using cached wheel link: %s', cache_entry.link)
  242. if req.link is req.original_link and cache_entry.persistent:
  243. req.original_link_is_in_wheel_cache = True
  244. req.link = cache_entry.link
  245. def _get_abstract_dist_for(self, req):
  246. # type: (InstallRequirement) -> AbstractDistribution
  247. """Takes a InstallRequirement and returns a single AbstractDist \
  248. representing a prepared variant of the same.
  249. """
  250. if req.editable:
  251. return self.preparer.prepare_editable_requirement(req)
  252. # satisfied_by is only evaluated by calling _check_skip_installed,
  253. # so it must be None here.
  254. assert req.satisfied_by is None
  255. skip_reason = self._check_skip_installed(req)
  256. if req.satisfied_by:
  257. return self.preparer.prepare_installed_requirement(
  258. req, skip_reason
  259. )
  260. # We eagerly populate the link, since that's our "legacy" behavior.
  261. self._populate_link(req)
  262. abstract_dist = self.preparer.prepare_linked_requirement(req)
  263. # NOTE
  264. # The following portion is for determining if a certain package is
  265. # going to be re-installed/upgraded or not and reporting to the user.
  266. # This should probably get cleaned up in a future refactor.
  267. # req.req is only avail after unpack for URL
  268. # pkgs repeat check_if_exists to uninstall-on-upgrade
  269. # (#14)
  270. if not self.ignore_installed:
  271. req.check_if_exists(self.use_user_site)
  272. if req.satisfied_by:
  273. should_modify = (
  274. self.upgrade_strategy != "to-satisfy-only" or
  275. self.force_reinstall or
  276. self.ignore_installed or
  277. req.link.scheme == 'file'
  278. )
  279. if should_modify:
  280. self._set_req_to_reinstall(req)
  281. else:
  282. logger.info(
  283. 'Requirement already satisfied (use --upgrade to upgrade):'
  284. ' %s', req,
  285. )
  286. return abstract_dist
  287. def _resolve_one(
  288. self,
  289. requirement_set, # type: RequirementSet
  290. req_to_install, # type: InstallRequirement
  291. ):
  292. # type: (...) -> List[InstallRequirement]
  293. """Prepare a single requirements file.
  294. :return: A list of additional InstallRequirements to also install.
  295. """
  296. # Tell user what we are doing for this requirement:
  297. # obtain (editable), skipping, processing (local url), collecting
  298. # (remote url or package name)
  299. if req_to_install.constraint or req_to_install.prepared:
  300. return []
  301. req_to_install.prepared = True
  302. abstract_dist = self._get_abstract_dist_for(req_to_install)
  303. # Parse and return dependencies
  304. dist = abstract_dist.get_pkg_resources_distribution()
  305. # This will raise UnsupportedPythonVersion if the given Python
  306. # version isn't compatible with the distribution's Requires-Python.
  307. _check_dist_requires_python(
  308. dist, version_info=self._py_version_info,
  309. ignore_requires_python=self.ignore_requires_python,
  310. )
  311. more_reqs = [] # type: List[InstallRequirement]
  312. def add_req(subreq, extras_requested):
  313. sub_install_req = self._make_install_req(
  314. str(subreq),
  315. req_to_install,
  316. )
  317. parent_req_name = req_to_install.name
  318. to_scan_again, add_to_parent = requirement_set.add_requirement(
  319. sub_install_req,
  320. parent_req_name=parent_req_name,
  321. extras_requested=extras_requested,
  322. )
  323. if parent_req_name and add_to_parent:
  324. self._discovered_dependencies[parent_req_name].append(
  325. add_to_parent
  326. )
  327. more_reqs.extend(to_scan_again)
  328. with indent_log():
  329. # We add req_to_install before its dependencies, so that we
  330. # can refer to it when adding dependencies.
  331. if not requirement_set.has_requirement(req_to_install.name):
  332. # 'unnamed' requirements will get added here
  333. # 'unnamed' requirements can only come from being directly
  334. # provided by the user.
  335. assert req_to_install.is_direct
  336. requirement_set.add_requirement(
  337. req_to_install, parent_req_name=None,
  338. )
  339. if not self.ignore_dependencies:
  340. if req_to_install.extras:
  341. logger.debug(
  342. "Installing extra requirements: %r",
  343. ','.join(req_to_install.extras),
  344. )
  345. missing_requested = sorted(
  346. set(req_to_install.extras) - set(dist.extras)
  347. )
  348. for missing in missing_requested:
  349. logger.warning(
  350. '%s does not provide the extra \'%s\'',
  351. dist, missing
  352. )
  353. available_requested = sorted(
  354. set(dist.extras) & set(req_to_install.extras)
  355. )
  356. for subreq in dist.requires(available_requested):
  357. add_req(subreq, extras_requested=available_requested)
  358. if not req_to_install.editable and not req_to_install.satisfied_by:
  359. # XXX: --no-install leads this to report 'Successfully
  360. # downloaded' for only non-editable reqs, even though we took
  361. # action on them.
  362. req_to_install.successfully_downloaded = True
  363. return more_reqs
  364. def get_installation_order(self, req_set):
  365. # type: (RequirementSet) -> List[InstallRequirement]
  366. """Create the installation order.
  367. The installation order is topological - requirements are installed
  368. before the requiring thing. We break cycles at an arbitrary point,
  369. and make no other guarantees.
  370. """
  371. # The current implementation, which we may change at any point
  372. # installs the user specified things in the order given, except when
  373. # dependencies must come earlier to achieve topological order.
  374. order = []
  375. ordered_reqs = set() # type: Set[InstallRequirement]
  376. def schedule(req):
  377. if req.satisfied_by or req in ordered_reqs:
  378. return
  379. if req.constraint:
  380. return
  381. ordered_reqs.add(req)
  382. for dep in self._discovered_dependencies[req.name]:
  383. schedule(dep)
  384. order.append(req)
  385. for install_req in req_set.requirements.values():
  386. schedule(install_req)
  387. return order