resolver.py 18 KB

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