candidates.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. import logging
  2. import sys
  3. from pip._vendor.contextlib2 import suppress
  4. from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
  5. from pip._vendor.packaging.utils import canonicalize_name
  6. from pip._vendor.packaging.version import Version
  7. from pip._internal.exceptions import HashError, MetadataInconsistent
  8. from pip._internal.network.lazy_wheel import (
  9. HTTPRangeRequestUnsupported,
  10. dist_from_wheel_url,
  11. )
  12. from pip._internal.req.constructors import (
  13. install_req_from_editable,
  14. install_req_from_line,
  15. )
  16. from pip._internal.req.req_install import InstallRequirement
  17. from pip._internal.utils.logging import indent_log
  18. from pip._internal.utils.misc import dist_is_editable, normalize_version_info
  19. from pip._internal.utils.packaging import get_requires_python
  20. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  21. from .base import Candidate, format_name
  22. if MYPY_CHECK_RUNNING:
  23. from typing import Any, FrozenSet, Iterable, Optional, Tuple, Union
  24. from pip._vendor.packaging.version import _BaseVersion
  25. from pip._vendor.pkg_resources import Distribution
  26. from pip._internal.distributions import AbstractDistribution
  27. from pip._internal.models.link import Link
  28. from .base import Requirement
  29. from .factory import Factory
  30. BaseCandidate = Union[
  31. "AlreadyInstalledCandidate",
  32. "EditableCandidate",
  33. "LinkCandidate",
  34. ]
  35. logger = logging.getLogger(__name__)
  36. def make_install_req_from_link(link, template):
  37. # type: (Link, InstallRequirement) -> InstallRequirement
  38. assert not template.editable, "template is editable"
  39. if template.req:
  40. line = str(template.req)
  41. else:
  42. line = link.url
  43. ireq = install_req_from_line(
  44. line,
  45. user_supplied=template.user_supplied,
  46. comes_from=template.comes_from,
  47. use_pep517=template.use_pep517,
  48. isolated=template.isolated,
  49. constraint=template.constraint,
  50. options=dict(
  51. install_options=template.install_options,
  52. global_options=template.global_options,
  53. hashes=template.hash_options
  54. ),
  55. )
  56. ireq.original_link = template.original_link
  57. ireq.link = link
  58. return ireq
  59. def make_install_req_from_editable(link, template):
  60. # type: (Link, InstallRequirement) -> InstallRequirement
  61. assert template.editable, "template not editable"
  62. return install_req_from_editable(
  63. link.url,
  64. user_supplied=template.user_supplied,
  65. comes_from=template.comes_from,
  66. use_pep517=template.use_pep517,
  67. isolated=template.isolated,
  68. constraint=template.constraint,
  69. options=dict(
  70. install_options=template.install_options,
  71. global_options=template.global_options,
  72. hashes=template.hash_options
  73. ),
  74. )
  75. def make_install_req_from_dist(dist, template):
  76. # type: (Distribution, InstallRequirement) -> InstallRequirement
  77. project_name = canonicalize_name(dist.project_name)
  78. if template.req:
  79. line = str(template.req)
  80. elif template.link:
  81. line = "{} @ {}".format(project_name, template.link.url)
  82. else:
  83. line = "{}=={}".format(project_name, dist.parsed_version)
  84. ireq = install_req_from_line(
  85. line,
  86. user_supplied=template.user_supplied,
  87. comes_from=template.comes_from,
  88. use_pep517=template.use_pep517,
  89. isolated=template.isolated,
  90. constraint=template.constraint,
  91. options=dict(
  92. install_options=template.install_options,
  93. global_options=template.global_options,
  94. hashes=template.hash_options
  95. ),
  96. )
  97. ireq.satisfied_by = dist
  98. return ireq
  99. class _InstallRequirementBackedCandidate(Candidate):
  100. """A candidate backed by an ``InstallRequirement``.
  101. This represents a package request with the target not being already
  102. in the environment, and needs to be fetched and installed. The backing
  103. ``InstallRequirement`` is responsible for most of the leg work; this
  104. class exposes appropriate information to the resolver.
  105. :param link: The link passed to the ``InstallRequirement``. The backing
  106. ``InstallRequirement`` will use this link to fetch the distribution.
  107. :param source_link: The link this candidate "originates" from. This is
  108. different from ``link`` when the link is found in the wheel cache.
  109. ``link`` would point to the wheel cache, while this points to the
  110. found remote link (e.g. from pypi.org).
  111. """
  112. is_installed = False
  113. def __init__(
  114. self,
  115. link, # type: Link
  116. source_link, # type: Link
  117. ireq, # type: InstallRequirement
  118. factory, # type: Factory
  119. name=None, # type: Optional[str]
  120. version=None, # type: Optional[_BaseVersion]
  121. ):
  122. # type: (...) -> None
  123. self._link = link
  124. self._source_link = source_link
  125. self._factory = factory
  126. self._ireq = ireq
  127. self._name = name
  128. self._version = version
  129. self._dist = None # type: Optional[Distribution]
  130. self._prepared = False
  131. def __repr__(self):
  132. # type: () -> str
  133. return "{class_name}({link!r})".format(
  134. class_name=self.__class__.__name__,
  135. link=str(self._link),
  136. )
  137. def __hash__(self):
  138. # type: () -> int
  139. return hash((self.__class__, self._link))
  140. def __eq__(self, other):
  141. # type: (Any) -> bool
  142. if isinstance(other, self.__class__):
  143. return self._link == other._link
  144. return False
  145. # Needed for Python 2, which does not implement this by default
  146. def __ne__(self, other):
  147. # type: (Any) -> bool
  148. return not self.__eq__(other)
  149. @property
  150. def source_link(self):
  151. # type: () -> Optional[Link]
  152. return self._source_link
  153. @property
  154. def name(self):
  155. # type: () -> str
  156. """The normalised name of the project the candidate refers to"""
  157. if self._name is None:
  158. self._name = canonicalize_name(self.dist.project_name)
  159. return self._name
  160. @property
  161. def version(self):
  162. # type: () -> _BaseVersion
  163. if self._version is None:
  164. self._version = self.dist.parsed_version
  165. return self._version
  166. def format_for_error(self):
  167. # type: () -> str
  168. return "{} {} (from {})".format(
  169. self.name,
  170. self.version,
  171. self._link.file_path if self._link.is_file else self._link
  172. )
  173. def _prepare_abstract_distribution(self):
  174. # type: () -> AbstractDistribution
  175. raise NotImplementedError("Override in subclass")
  176. def _check_metadata_consistency(self):
  177. # type: () -> None
  178. """Check for consistency of project name and version of dist."""
  179. # TODO: (Longer term) Rather than abort, reject this candidate
  180. # and backtrack. This would need resolvelib support.
  181. dist = self._dist # type: Distribution
  182. name = canonicalize_name(dist.project_name)
  183. if self._name is not None and self._name != name:
  184. raise MetadataInconsistent(self._ireq, "name", dist.project_name)
  185. version = dist.parsed_version
  186. if self._version is not None and self._version != version:
  187. raise MetadataInconsistent(self._ireq, "version", dist.version)
  188. def _prepare(self):
  189. # type: () -> None
  190. if self._prepared:
  191. return
  192. try:
  193. abstract_dist = self._prepare_abstract_distribution()
  194. except HashError as e:
  195. e.req = self._ireq
  196. raise
  197. self._dist = abstract_dist.get_pkg_resources_distribution()
  198. assert self._dist is not None, "Distribution already installed"
  199. self._check_metadata_consistency()
  200. self._prepared = True
  201. def _fetch_metadata(self):
  202. # type: () -> None
  203. """Fetch metadata, using lazy wheel if possible."""
  204. preparer = self._factory.preparer
  205. use_lazy_wheel = self._factory.use_lazy_wheel
  206. remote_wheel = self._link.is_wheel and not self._link.is_file
  207. if use_lazy_wheel and remote_wheel and not preparer.require_hashes:
  208. assert self._name is not None
  209. logger.info('Collecting %s', self._ireq.req or self._ireq)
  210. # If HTTPRangeRequestUnsupported is raised, fallback silently.
  211. with indent_log(), suppress(HTTPRangeRequestUnsupported):
  212. logger.info(
  213. 'Obtaining dependency information from %s %s',
  214. self._name, self._version,
  215. )
  216. url = self._link.url.split('#', 1)[0]
  217. session = preparer.downloader._session
  218. self._dist = dist_from_wheel_url(self._name, url, session)
  219. self._check_metadata_consistency()
  220. if self._dist is None:
  221. self._prepare()
  222. @property
  223. def dist(self):
  224. # type: () -> Distribution
  225. if self._dist is None:
  226. self._fetch_metadata()
  227. return self._dist
  228. def _get_requires_python_specifier(self):
  229. # type: () -> Optional[SpecifierSet]
  230. requires_python = get_requires_python(self.dist)
  231. if requires_python is None:
  232. return None
  233. try:
  234. spec = SpecifierSet(requires_python)
  235. except InvalidSpecifier as e:
  236. logger.warning(
  237. "Package %r has an invalid Requires-Python: %s", self.name, e,
  238. )
  239. return None
  240. return spec
  241. def iter_dependencies(self):
  242. # type: () -> Iterable[Optional[Requirement]]
  243. for r in self.dist.requires():
  244. yield self._factory.make_requirement_from_spec(str(r), self._ireq)
  245. python_dep = self._factory.make_requires_python_requirement(
  246. self._get_requires_python_specifier(),
  247. )
  248. if python_dep:
  249. yield python_dep
  250. def get_install_requirement(self):
  251. # type: () -> Optional[InstallRequirement]
  252. self._prepare()
  253. return self._ireq
  254. class LinkCandidate(_InstallRequirementBackedCandidate):
  255. is_editable = False
  256. def __init__(
  257. self,
  258. link, # type: Link
  259. template, # type: InstallRequirement
  260. factory, # type: Factory
  261. name=None, # type: Optional[str]
  262. version=None, # type: Optional[_BaseVersion]
  263. ):
  264. # type: (...) -> None
  265. source_link = link
  266. cache_entry = factory.get_wheel_cache_entry(link, name)
  267. if cache_entry is not None:
  268. logger.debug("Using cached wheel link: %s", cache_entry.link)
  269. link = cache_entry.link
  270. ireq = make_install_req_from_link(link, template)
  271. if (cache_entry is not None and
  272. cache_entry.persistent and
  273. template.link is template.original_link):
  274. ireq.original_link_is_in_wheel_cache = True
  275. super(LinkCandidate, self).__init__(
  276. link=link,
  277. source_link=source_link,
  278. ireq=ireq,
  279. factory=factory,
  280. name=name,
  281. version=version,
  282. )
  283. def _prepare_abstract_distribution(self):
  284. # type: () -> AbstractDistribution
  285. return self._factory.preparer.prepare_linked_requirement(
  286. self._ireq, parallel_builds=True,
  287. )
  288. class EditableCandidate(_InstallRequirementBackedCandidate):
  289. is_editable = True
  290. def __init__(
  291. self,
  292. link, # type: Link
  293. template, # type: InstallRequirement
  294. factory, # type: Factory
  295. name=None, # type: Optional[str]
  296. version=None, # type: Optional[_BaseVersion]
  297. ):
  298. # type: (...) -> None
  299. super(EditableCandidate, self).__init__(
  300. link=link,
  301. source_link=link,
  302. ireq=make_install_req_from_editable(link, template),
  303. factory=factory,
  304. name=name,
  305. version=version,
  306. )
  307. def _prepare_abstract_distribution(self):
  308. # type: () -> AbstractDistribution
  309. return self._factory.preparer.prepare_editable_requirement(self._ireq)
  310. class AlreadyInstalledCandidate(Candidate):
  311. is_installed = True
  312. source_link = None
  313. def __init__(
  314. self,
  315. dist, # type: Distribution
  316. template, # type: InstallRequirement
  317. factory, # type: Factory
  318. ):
  319. # type: (...) -> None
  320. self.dist = dist
  321. self._ireq = make_install_req_from_dist(dist, template)
  322. self._factory = factory
  323. # This is just logging some messages, so we can do it eagerly.
  324. # The returned dist would be exactly the same as self.dist because we
  325. # set satisfied_by in make_install_req_from_dist.
  326. # TODO: Supply reason based on force_reinstall and upgrade_strategy.
  327. skip_reason = "already satisfied"
  328. factory.preparer.prepare_installed_requirement(self._ireq, skip_reason)
  329. def __repr__(self):
  330. # type: () -> str
  331. return "{class_name}({distribution!r})".format(
  332. class_name=self.__class__.__name__,
  333. distribution=self.dist,
  334. )
  335. def __hash__(self):
  336. # type: () -> int
  337. return hash((self.__class__, self.name, self.version))
  338. def __eq__(self, other):
  339. # type: (Any) -> bool
  340. if isinstance(other, self.__class__):
  341. return self.name == other.name and self.version == other.version
  342. return False
  343. # Needed for Python 2, which does not implement this by default
  344. def __ne__(self, other):
  345. # type: (Any) -> bool
  346. return not self.__eq__(other)
  347. @property
  348. def name(self):
  349. # type: () -> str
  350. return canonicalize_name(self.dist.project_name)
  351. @property
  352. def version(self):
  353. # type: () -> _BaseVersion
  354. return self.dist.parsed_version
  355. @property
  356. def is_editable(self):
  357. # type: () -> bool
  358. return dist_is_editable(self.dist)
  359. def format_for_error(self):
  360. # type: () -> str
  361. return "{} {} (Installed)".format(self.name, self.version)
  362. def iter_dependencies(self):
  363. # type: () -> Iterable[Optional[Requirement]]
  364. for r in self.dist.requires():
  365. yield self._factory.make_requirement_from_spec(str(r), self._ireq)
  366. def get_install_requirement(self):
  367. # type: () -> Optional[InstallRequirement]
  368. return None
  369. class ExtrasCandidate(Candidate):
  370. """A candidate that has 'extras', indicating additional dependencies.
  371. Requirements can be for a project with dependencies, something like
  372. foo[extra]. The extras don't affect the project/version being installed
  373. directly, but indicate that we need additional dependencies. We model that
  374. by having an artificial ExtrasCandidate that wraps the "base" candidate.
  375. The ExtrasCandidate differs from the base in the following ways:
  376. 1. It has a unique name, of the form foo[extra]. This causes the resolver
  377. to treat it as a separate node in the dependency graph.
  378. 2. When we're getting the candidate's dependencies,
  379. a) We specify that we want the extra dependencies as well.
  380. b) We add a dependency on the base candidate.
  381. See below for why this is needed.
  382. 3. We return None for the underlying InstallRequirement, as the base
  383. candidate will provide it, and we don't want to end up with duplicates.
  384. The dependency on the base candidate is needed so that the resolver can't
  385. decide that it should recommend foo[extra1] version 1.0 and foo[extra2]
  386. version 2.0. Having those candidates depend on foo=1.0 and foo=2.0
  387. respectively forces the resolver to recognise that this is a conflict.
  388. """
  389. def __init__(
  390. self,
  391. base, # type: BaseCandidate
  392. extras, # type: FrozenSet[str]
  393. ):
  394. # type: (...) -> None
  395. self.base = base
  396. self.extras = extras
  397. def __repr__(self):
  398. # type: () -> str
  399. return "{class_name}(base={base!r}, extras={extras!r})".format(
  400. class_name=self.__class__.__name__,
  401. base=self.base,
  402. extras=self.extras,
  403. )
  404. def __hash__(self):
  405. # type: () -> int
  406. return hash((self.base, self.extras))
  407. def __eq__(self, other):
  408. # type: (Any) -> bool
  409. if isinstance(other, self.__class__):
  410. return self.base == other.base and self.extras == other.extras
  411. return False
  412. # Needed for Python 2, which does not implement this by default
  413. def __ne__(self, other):
  414. # type: (Any) -> bool
  415. return not self.__eq__(other)
  416. @property
  417. def name(self):
  418. # type: () -> str
  419. """The normalised name of the project the candidate refers to"""
  420. return format_name(self.base.name, self.extras)
  421. @property
  422. def version(self):
  423. # type: () -> _BaseVersion
  424. return self.base.version
  425. def format_for_error(self):
  426. # type: () -> str
  427. return "{} [{}]".format(
  428. self.base.format_for_error(),
  429. ", ".join(sorted(self.extras))
  430. )
  431. @property
  432. def is_installed(self):
  433. # type: () -> bool
  434. return self.base.is_installed
  435. @property
  436. def is_editable(self):
  437. # type: () -> bool
  438. return self.base.is_editable
  439. @property
  440. def source_link(self):
  441. # type: () -> Optional[Link]
  442. return self.base.source_link
  443. def iter_dependencies(self):
  444. # type: () -> Iterable[Optional[Requirement]]
  445. factory = self.base._factory
  446. # The user may have specified extras that the candidate doesn't
  447. # support. We ignore any unsupported extras here.
  448. valid_extras = self.extras.intersection(self.base.dist.extras)
  449. invalid_extras = self.extras.difference(self.base.dist.extras)
  450. for extra in sorted(invalid_extras):
  451. logger.warning(
  452. "%s %s does not provide the extra '%s'",
  453. self.base.name,
  454. self.version,
  455. extra
  456. )
  457. # Add a dependency on the exact base
  458. # (See note 2b in the class docstring)
  459. yield factory.make_requirement_from_candidate(self.base)
  460. for r in self.base.dist.requires(valid_extras):
  461. requirement = factory.make_requirement_from_spec(
  462. str(r), self.base._ireq, valid_extras,
  463. )
  464. if requirement:
  465. yield requirement
  466. def get_install_requirement(self):
  467. # type: () -> Optional[InstallRequirement]
  468. # We don't return anything here, because we always
  469. # depend on the base candidate, and we'll get the
  470. # install requirement from that.
  471. return None
  472. class RequiresPythonCandidate(Candidate):
  473. is_installed = False
  474. source_link = None
  475. def __init__(self, py_version_info):
  476. # type: (Optional[Tuple[int, ...]]) -> None
  477. if py_version_info is not None:
  478. version_info = normalize_version_info(py_version_info)
  479. else:
  480. version_info = sys.version_info[:3]
  481. self._version = Version(".".join(str(c) for c in version_info))
  482. # We don't need to implement __eq__() and __ne__() since there is always
  483. # only one RequiresPythonCandidate in a resolution, i.e. the host Python.
  484. # The built-in object.__eq__() and object.__ne__() do exactly what we want.
  485. @property
  486. def name(self):
  487. # type: () -> str
  488. # Avoid conflicting with the PyPI package "Python".
  489. return "<Python from Requires-Python>"
  490. @property
  491. def version(self):
  492. # type: () -> _BaseVersion
  493. return self._version
  494. def format_for_error(self):
  495. # type: () -> str
  496. return "Python {}".format(self.version)
  497. def iter_dependencies(self):
  498. # type: () -> Iterable[Optional[Requirement]]
  499. return ()
  500. def get_install_requirement(self):
  501. # type: () -> Optional[InstallRequirement]
  502. return None