resolver.py 17 KB

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