factory.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import collections
  2. import logging
  3. from pip._vendor import six
  4. from pip._vendor.packaging.utils import canonicalize_name
  5. from pip._internal.exceptions import (
  6. DistributionNotFound,
  7. InstallationError,
  8. UnsupportedPythonVersion,
  9. UnsupportedWheel,
  10. )
  11. from pip._internal.models.wheel import Wheel
  12. from pip._internal.req.req_install import InstallRequirement
  13. from pip._internal.utils.compatibility_tags import get_supported
  14. from pip._internal.utils.hashes import Hashes
  15. from pip._internal.utils.misc import (
  16. dist_in_site_packages,
  17. dist_in_usersite,
  18. get_installed_distributions,
  19. )
  20. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  21. from pip._internal.utils.virtualenv import running_under_virtualenv
  22. from .candidates import (
  23. AlreadyInstalledCandidate,
  24. EditableCandidate,
  25. ExtrasCandidate,
  26. LinkCandidate,
  27. RequiresPythonCandidate,
  28. )
  29. from .requirements import (
  30. ExplicitRequirement,
  31. RequiresPythonRequirement,
  32. SpecifierRequirement,
  33. )
  34. if MYPY_CHECK_RUNNING:
  35. from typing import (
  36. FrozenSet,
  37. Dict,
  38. Iterable,
  39. List,
  40. Optional,
  41. Sequence,
  42. Set,
  43. Tuple,
  44. TypeVar,
  45. )
  46. from pip._vendor.packaging.specifiers import SpecifierSet
  47. from pip._vendor.packaging.version import _BaseVersion
  48. from pip._vendor.pkg_resources import Distribution
  49. from pip._vendor.resolvelib import ResolutionImpossible
  50. from pip._internal.cache import CacheEntry, WheelCache
  51. from pip._internal.index.package_finder import PackageFinder
  52. from pip._internal.models.link import Link
  53. from pip._internal.operations.prepare import RequirementPreparer
  54. from pip._internal.resolution.base import InstallRequirementProvider
  55. from .base import Candidate, Requirement
  56. from .candidates import BaseCandidate
  57. C = TypeVar("C")
  58. Cache = Dict[Link, C]
  59. VersionCandidates = Dict[_BaseVersion, Candidate]
  60. logger = logging.getLogger(__name__)
  61. class Factory(object):
  62. def __init__(
  63. self,
  64. finder, # type: PackageFinder
  65. preparer, # type: RequirementPreparer
  66. make_install_req, # type: InstallRequirementProvider
  67. wheel_cache, # type: Optional[WheelCache]
  68. use_user_site, # type: bool
  69. force_reinstall, # type: bool
  70. ignore_installed, # type: bool
  71. ignore_requires_python, # type: bool
  72. py_version_info=None, # type: Optional[Tuple[int, ...]]
  73. lazy_wheel=False, # type: bool
  74. ):
  75. # type: (...) -> None
  76. self._finder = finder
  77. self.preparer = preparer
  78. self._wheel_cache = wheel_cache
  79. self._python_candidate = RequiresPythonCandidate(py_version_info)
  80. self._make_install_req_from_spec = make_install_req
  81. self._use_user_site = use_user_site
  82. self._force_reinstall = force_reinstall
  83. self._ignore_requires_python = ignore_requires_python
  84. self.use_lazy_wheel = lazy_wheel
  85. self._link_candidate_cache = {} # type: Cache[LinkCandidate]
  86. self._editable_candidate_cache = {} # type: Cache[EditableCandidate]
  87. if not ignore_installed:
  88. self._installed_dists = {
  89. canonicalize_name(dist.project_name): dist
  90. for dist in get_installed_distributions()
  91. }
  92. else:
  93. self._installed_dists = {}
  94. @property
  95. def force_reinstall(self):
  96. # type: () -> bool
  97. return self._force_reinstall
  98. def _make_candidate_from_dist(
  99. self,
  100. dist, # type: Distribution
  101. extras, # type: FrozenSet[str]
  102. template, # type: InstallRequirement
  103. ):
  104. # type: (...) -> Candidate
  105. base = AlreadyInstalledCandidate(dist, template, factory=self)
  106. if extras:
  107. return ExtrasCandidate(base, extras)
  108. return base
  109. def _make_candidate_from_link(
  110. self,
  111. link, # type: Link
  112. extras, # type: FrozenSet[str]
  113. template, # type: InstallRequirement
  114. name, # type: Optional[str]
  115. version, # type: Optional[_BaseVersion]
  116. ):
  117. # type: (...) -> Candidate
  118. # TODO: Check already installed candidate, and use it if the link and
  119. # editable flag match.
  120. if template.editable:
  121. if link not in self._editable_candidate_cache:
  122. self._editable_candidate_cache[link] = EditableCandidate(
  123. link, template, factory=self, name=name, version=version,
  124. )
  125. base = self._editable_candidate_cache[link] # type: BaseCandidate
  126. else:
  127. if link not in self._link_candidate_cache:
  128. self._link_candidate_cache[link] = LinkCandidate(
  129. link, template, factory=self, name=name, version=version,
  130. )
  131. base = self._link_candidate_cache[link]
  132. if extras:
  133. return ExtrasCandidate(base, extras)
  134. return base
  135. def _iter_found_candidates(
  136. self,
  137. ireqs, # type: Sequence[InstallRequirement]
  138. specifier, # type: SpecifierSet
  139. ):
  140. # type: (...) -> Iterable[Candidate]
  141. if not ireqs:
  142. return ()
  143. # The InstallRequirement implementation requires us to give it a
  144. # "template". Here we just choose the first requirement to represent
  145. # all of them.
  146. # Hopefully the Project model can correct this mismatch in the future.
  147. template = ireqs[0]
  148. name = canonicalize_name(template.req.name)
  149. hashes = Hashes()
  150. extras = frozenset() # type: FrozenSet[str]
  151. for ireq in ireqs:
  152. specifier &= ireq.req.specifier
  153. hashes |= ireq.hashes(trust_internet=False)
  154. extras |= frozenset(ireq.extras)
  155. # We use this to ensure that we only yield a single candidate for
  156. # each version (the finder's preferred one for that version). The
  157. # requirement needs to return only one candidate per version, so we
  158. # implement that logic here so that requirements using this helper
  159. # don't all have to do the same thing later.
  160. candidates = collections.OrderedDict() # type: VersionCandidates
  161. # Get the installed version, if it matches, unless the user
  162. # specified `--force-reinstall`, when we want the version from
  163. # the index instead.
  164. installed_version = None
  165. installed_candidate = None
  166. if not self._force_reinstall and name in self._installed_dists:
  167. installed_dist = self._installed_dists[name]
  168. installed_version = installed_dist.parsed_version
  169. if specifier.contains(installed_version, prereleases=True):
  170. installed_candidate = self._make_candidate_from_dist(
  171. dist=installed_dist,
  172. extras=extras,
  173. template=template,
  174. )
  175. found = self._finder.find_best_candidate(
  176. project_name=name,
  177. specifier=specifier,
  178. hashes=hashes,
  179. )
  180. for ican in found.iter_applicable():
  181. if ican.version == installed_version and installed_candidate:
  182. candidate = installed_candidate
  183. else:
  184. candidate = self._make_candidate_from_link(
  185. link=ican.link,
  186. extras=extras,
  187. template=template,
  188. name=name,
  189. version=ican.version,
  190. )
  191. candidates[ican.version] = candidate
  192. # Yield the installed version even if it is not found on the index.
  193. if installed_version and installed_candidate:
  194. candidates[installed_version] = installed_candidate
  195. return six.itervalues(candidates)
  196. def find_candidates(self, requirements, constraint):
  197. # type: (Sequence[Requirement], SpecifierSet) -> Iterable[Candidate]
  198. explicit_candidates = set() # type: Set[Candidate]
  199. ireqs = [] # type: List[InstallRequirement]
  200. for req in requirements:
  201. cand, ireq = req.get_candidate_lookup()
  202. if cand is not None:
  203. explicit_candidates.add(cand)
  204. if ireq is not None:
  205. ireqs.append(ireq)
  206. # If none of the requirements want an explicit candidate, we can ask
  207. # the finder for candidates.
  208. if not explicit_candidates:
  209. return self._iter_found_candidates(ireqs, constraint)
  210. if constraint:
  211. name = explicit_candidates.pop().name
  212. raise InstallationError(
  213. "Could not satisfy constraints for {!r}: installation from "
  214. "path or url cannot be constrained to a version".format(name)
  215. )
  216. return (
  217. c for c in explicit_candidates
  218. if all(req.is_satisfied_by(c) for req in requirements)
  219. )
  220. def make_requirement_from_install_req(self, ireq, requested_extras):
  221. # type: (InstallRequirement, Iterable[str]) -> Optional[Requirement]
  222. if not ireq.match_markers(requested_extras):
  223. logger.info(
  224. "Ignoring %s: markers '%s' don't match your environment",
  225. ireq.name, ireq.markers,
  226. )
  227. return None
  228. if not ireq.link:
  229. return SpecifierRequirement(ireq)
  230. if ireq.link.is_wheel:
  231. wheel = Wheel(ireq.link.filename)
  232. if not wheel.supported(self._finder.target_python.get_tags()):
  233. msg = "{} is not a supported wheel on this platform.".format(
  234. wheel.filename,
  235. )
  236. raise UnsupportedWheel(msg)
  237. cand = self._make_candidate_from_link(
  238. ireq.link,
  239. extras=frozenset(ireq.extras),
  240. template=ireq,
  241. name=canonicalize_name(ireq.name) if ireq.name else None,
  242. version=None,
  243. )
  244. return self.make_requirement_from_candidate(cand)
  245. def make_requirement_from_candidate(self, candidate):
  246. # type: (Candidate) -> ExplicitRequirement
  247. return ExplicitRequirement(candidate)
  248. def make_requirement_from_spec(
  249. self,
  250. specifier, # type: str
  251. comes_from, # type: InstallRequirement
  252. requested_extras=(), # type: Iterable[str]
  253. ):
  254. # type: (...) -> Optional[Requirement]
  255. ireq = self._make_install_req_from_spec(specifier, comes_from)
  256. return self.make_requirement_from_install_req(ireq, requested_extras)
  257. def make_requires_python_requirement(self, specifier):
  258. # type: (Optional[SpecifierSet]) -> Optional[Requirement]
  259. if self._ignore_requires_python or specifier is None:
  260. return None
  261. return RequiresPythonRequirement(specifier, self._python_candidate)
  262. def get_wheel_cache_entry(self, link, name):
  263. # type: (Link, Optional[str]) -> Optional[CacheEntry]
  264. """Look up the link in the wheel cache.
  265. If ``preparer.require_hashes`` is True, don't use the wheel cache,
  266. because cached wheels, always built locally, have different hashes
  267. than the files downloaded from the index server and thus throw false
  268. hash mismatches. Furthermore, cached wheels at present have
  269. nondeterministic contents due to file modification times.
  270. """
  271. if self._wheel_cache is None or self.preparer.require_hashes:
  272. return None
  273. return self._wheel_cache.get_cache_entry(
  274. link=link,
  275. package_name=name,
  276. supported_tags=get_supported(),
  277. )
  278. def get_dist_to_uninstall(self, candidate):
  279. # type: (Candidate) -> Optional[Distribution]
  280. # TODO: Are there more cases this needs to return True? Editable?
  281. dist = self._installed_dists.get(candidate.name)
  282. if dist is None: # Not installed, no uninstallation required.
  283. return None
  284. # We're installing into global site. The current installation must
  285. # be uninstalled, no matter it's in global or user site, because the
  286. # user site installation has precedence over global.
  287. if not self._use_user_site:
  288. return dist
  289. # We're installing into user site. Remove the user site installation.
  290. if dist_in_usersite(dist):
  291. return dist
  292. # We're installing into user site, but the installed incompatible
  293. # package is in global site. We can't uninstall that, and would let
  294. # the new user installation to "shadow" it. But shadowing won't work
  295. # in virtual environments, so we error out.
  296. if running_under_virtualenv() and dist_in_site_packages(dist):
  297. raise InstallationError(
  298. "Will not install to the user site because it will "
  299. "lack sys.path precedence to {} in {}".format(
  300. dist.project_name, dist.location,
  301. )
  302. )
  303. return None
  304. def _report_requires_python_error(
  305. self,
  306. requirement, # type: RequiresPythonRequirement
  307. template, # type: Candidate
  308. ):
  309. # type: (...) -> UnsupportedPythonVersion
  310. message_format = (
  311. "Package {package!r} requires a different Python: "
  312. "{version} not in {specifier!r}"
  313. )
  314. message = message_format.format(
  315. package=template.name,
  316. version=self._python_candidate.version,
  317. specifier=str(requirement.specifier),
  318. )
  319. return UnsupportedPythonVersion(message)
  320. def get_installation_error(self, e):
  321. # type: (ResolutionImpossible) -> InstallationError
  322. assert e.causes, "Installation error reported with no cause"
  323. # If one of the things we can't solve is "we need Python X.Y",
  324. # that is what we report.
  325. for cause in e.causes:
  326. if isinstance(cause.requirement, RequiresPythonRequirement):
  327. return self._report_requires_python_error(
  328. cause.requirement,
  329. cause.parent,
  330. )
  331. # Otherwise, we have a set of causes which can't all be satisfied
  332. # at once.
  333. # The simplest case is when we have *one* cause that can't be
  334. # satisfied. We just report that case.
  335. if len(e.causes) == 1:
  336. req, parent = e.causes[0]
  337. if parent is None:
  338. req_disp = str(req)
  339. else:
  340. req_disp = '{} (from {})'.format(req, parent.name)
  341. logger.critical(
  342. "Could not find a version that satisfies the requirement %s",
  343. req_disp,
  344. )
  345. return DistributionNotFound(
  346. 'No matching distribution found for {}'.format(req)
  347. )
  348. # OK, we now have a list of requirements that can't all be
  349. # satisfied at once.
  350. # A couple of formatting helpers
  351. def text_join(parts):
  352. # type: (List[str]) -> str
  353. if len(parts) == 1:
  354. return parts[0]
  355. return ", ".join(parts[:-1]) + " and " + parts[-1]
  356. def readable_form(cand):
  357. # type: (Candidate) -> str
  358. return "{} {}".format(cand.name, cand.version)
  359. def describe_trigger(parent):
  360. # type: (Candidate) -> str
  361. ireq = parent.get_install_requirement()
  362. if not ireq or not ireq.comes_from:
  363. return "{} {}".format(parent.name, parent.version)
  364. if isinstance(ireq.comes_from, InstallRequirement):
  365. return str(ireq.comes_from.name)
  366. return str(ireq.comes_from)
  367. triggers = []
  368. for req, parent in e.causes:
  369. if parent is None:
  370. # This is a root requirement, so we can report it directly
  371. trigger = req.format_for_error()
  372. else:
  373. trigger = describe_trigger(parent)
  374. triggers.append(trigger)
  375. if triggers:
  376. info = text_join(triggers)
  377. else:
  378. info = "the requested packages"
  379. msg = "Cannot install {} because these package versions " \
  380. "have conflicting dependencies.".format(info)
  381. logger.critical(msg)
  382. msg = "\nThe conflict is caused by:"
  383. for req, parent in e.causes:
  384. msg = msg + "\n "
  385. if parent:
  386. msg = msg + "{} {} depends on ".format(
  387. parent.name,
  388. parent.version
  389. )
  390. else:
  391. msg = msg + "The user requested "
  392. msg = msg + req.format_for_error()
  393. msg = msg + "\n\n" + \
  394. "To fix this you could try to:\n" + \
  395. "1. loosen the range of package versions you've specified\n" + \
  396. "2. remove package versions to allow pip attempt to solve " + \
  397. "the dependency conflict\n"
  398. logger.info(msg)
  399. return DistributionNotFound(
  400. "ResolutionImpossible: for help visit "
  401. "https://pip.pypa.io/en/latest/user_guide/"
  402. "#fixing-conflicting-dependencies"
  403. )