req_command.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. """Contains the Command base classes that depend on PipSession.
  2. The classes in this module are in a separate module so the commands not
  3. needing download / PackageFinder capability don't unnecessarily import the
  4. PackageFinder machinery and all its vendored dependencies, etc.
  5. """
  6. import logging
  7. import os
  8. import sys
  9. from functools import partial
  10. from optparse import Values
  11. from typing import TYPE_CHECKING, Any, List, Optional, Tuple
  12. from pip._internal.cache import WheelCache
  13. from pip._internal.cli import cmdoptions
  14. from pip._internal.cli.base_command import Command
  15. from pip._internal.cli.command_context import CommandContextMixIn
  16. from pip._internal.exceptions import CommandError, PreviousBuildDirError
  17. from pip._internal.index.collector import LinkCollector
  18. from pip._internal.index.package_finder import PackageFinder
  19. from pip._internal.models.selection_prefs import SelectionPreferences
  20. from pip._internal.models.target_python import TargetPython
  21. from pip._internal.network.session import PipSession
  22. from pip._internal.operations.build.build_tracker import BuildTracker
  23. from pip._internal.operations.prepare import RequirementPreparer
  24. from pip._internal.req.constructors import (
  25. install_req_from_editable,
  26. install_req_from_line,
  27. install_req_from_parsed_requirement,
  28. install_req_from_req_string,
  29. )
  30. from pip._internal.req.req_file import parse_requirements
  31. from pip._internal.req.req_install import InstallRequirement
  32. from pip._internal.resolution.base import BaseResolver
  33. from pip._internal.self_outdated_check import pip_self_version_check
  34. from pip._internal.utils.temp_dir import (
  35. TempDirectory,
  36. TempDirectoryTypeRegistry,
  37. tempdir_kinds,
  38. )
  39. from pip._internal.utils.virtualenv import running_under_virtualenv
  40. if TYPE_CHECKING:
  41. from ssl import SSLContext
  42. logger = logging.getLogger(__name__)
  43. def _create_truststore_ssl_context() -> Optional["SSLContext"]:
  44. if sys.version_info < (3, 10):
  45. raise CommandError("The truststore feature is only available for Python 3.10+")
  46. try:
  47. import ssl
  48. except ImportError:
  49. logger.warning("Disabling truststore since ssl support is missing")
  50. return None
  51. try:
  52. import truststore
  53. except ImportError:
  54. raise CommandError(
  55. "To use the truststore feature, 'truststore' must be installed into "
  56. "pip's current environment."
  57. )
  58. return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  59. class SessionCommandMixin(CommandContextMixIn):
  60. """
  61. A class mixin for command classes needing _build_session().
  62. """
  63. def __init__(self) -> None:
  64. super().__init__()
  65. self._session: Optional[PipSession] = None
  66. @classmethod
  67. def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
  68. """Return a list of index urls from user-provided options."""
  69. index_urls = []
  70. if not getattr(options, "no_index", False):
  71. url = getattr(options, "index_url", None)
  72. if url:
  73. index_urls.append(url)
  74. urls = getattr(options, "extra_index_urls", None)
  75. if urls:
  76. index_urls.extend(urls)
  77. # Return None rather than an empty list
  78. return index_urls or None
  79. def get_default_session(self, options: Values) -> PipSession:
  80. """Get a default-managed session."""
  81. if self._session is None:
  82. self._session = self.enter_context(self._build_session(options))
  83. # there's no type annotation on requests.Session, so it's
  84. # automatically ContextManager[Any] and self._session becomes Any,
  85. # then https://github.com/python/mypy/issues/7696 kicks in
  86. assert self._session is not None
  87. return self._session
  88. def _build_session(
  89. self,
  90. options: Values,
  91. retries: Optional[int] = None,
  92. timeout: Optional[int] = None,
  93. fallback_to_certifi: bool = False,
  94. ) -> PipSession:
  95. cache_dir = options.cache_dir
  96. assert not cache_dir or os.path.isabs(cache_dir)
  97. if "truststore" in options.features_enabled:
  98. try:
  99. ssl_context = _create_truststore_ssl_context()
  100. except Exception:
  101. if not fallback_to_certifi:
  102. raise
  103. ssl_context = None
  104. else:
  105. ssl_context = None
  106. session = PipSession(
  107. cache=os.path.join(cache_dir, "http") if cache_dir else None,
  108. retries=retries if retries is not None else options.retries,
  109. trusted_hosts=options.trusted_hosts,
  110. index_urls=self._get_index_urls(options),
  111. ssl_context=ssl_context,
  112. )
  113. # Handle custom ca-bundles from the user
  114. if options.cert:
  115. session.verify = options.cert
  116. # Handle SSL client certificate
  117. if options.client_cert:
  118. session.cert = options.client_cert
  119. # Handle timeouts
  120. if options.timeout or timeout:
  121. session.timeout = timeout if timeout is not None else options.timeout
  122. # Handle configured proxies
  123. if options.proxy:
  124. session.proxies = {
  125. "http": options.proxy,
  126. "https": options.proxy,
  127. }
  128. # Determine if we can prompt the user for authentication or not
  129. session.auth.prompting = not options.no_input
  130. session.auth.keyring_provider = options.keyring_provider
  131. return session
  132. class IndexGroupCommand(Command, SessionCommandMixin):
  133. """
  134. Abstract base class for commands with the index_group options.
  135. This also corresponds to the commands that permit the pip version check.
  136. """
  137. def handle_pip_version_check(self, options: Values) -> None:
  138. """
  139. Do the pip version check if not disabled.
  140. This overrides the default behavior of not doing the check.
  141. """
  142. # Make sure the index_group options are present.
  143. assert hasattr(options, "no_index")
  144. if options.disable_pip_version_check or options.no_index:
  145. return
  146. # Otherwise, check if we're using the latest version of pip available.
  147. session = self._build_session(
  148. options,
  149. retries=0,
  150. timeout=min(5, options.timeout),
  151. # This is set to ensure the function does not fail when truststore is
  152. # specified in use-feature but cannot be loaded. This usually raises a
  153. # CommandError and shows a nice user-facing error, but this function is not
  154. # called in that try-except block.
  155. fallback_to_certifi=True,
  156. )
  157. with session:
  158. pip_self_version_check(session, options)
  159. KEEPABLE_TEMPDIR_TYPES = [
  160. tempdir_kinds.BUILD_ENV,
  161. tempdir_kinds.EPHEM_WHEEL_CACHE,
  162. tempdir_kinds.REQ_BUILD,
  163. ]
  164. def warn_if_run_as_root() -> None:
  165. """Output a warning for sudo users on Unix.
  166. In a virtual environment, sudo pip still writes to virtualenv.
  167. On Windows, users may run pip as Administrator without issues.
  168. This warning only applies to Unix root users outside of virtualenv.
  169. """
  170. if running_under_virtualenv():
  171. return
  172. if not hasattr(os, "getuid"):
  173. return
  174. # On Windows, there are no "system managed" Python packages. Installing as
  175. # Administrator via pip is the correct way of updating system environments.
  176. #
  177. # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
  178. # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
  179. if sys.platform == "win32" or sys.platform == "cygwin":
  180. return
  181. if os.getuid() != 0:
  182. return
  183. logger.warning(
  184. "Running pip as the 'root' user can result in broken permissions and "
  185. "conflicting behaviour with the system package manager. "
  186. "It is recommended to use a virtual environment instead: "
  187. "https://pip.pypa.io/warnings/venv"
  188. )
  189. def with_cleanup(func: Any) -> Any:
  190. """Decorator for common logic related to managing temporary
  191. directories.
  192. """
  193. def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
  194. for t in KEEPABLE_TEMPDIR_TYPES:
  195. registry.set_delete(t, False)
  196. def wrapper(
  197. self: RequirementCommand, options: Values, args: List[Any]
  198. ) -> Optional[int]:
  199. assert self.tempdir_registry is not None
  200. if options.no_clean:
  201. configure_tempdir_registry(self.tempdir_registry)
  202. try:
  203. return func(self, options, args)
  204. except PreviousBuildDirError:
  205. # This kind of conflict can occur when the user passes an explicit
  206. # build directory with a pre-existing folder. In that case we do
  207. # not want to accidentally remove it.
  208. configure_tempdir_registry(self.tempdir_registry)
  209. raise
  210. return wrapper
  211. class RequirementCommand(IndexGroupCommand):
  212. def __init__(self, *args: Any, **kw: Any) -> None:
  213. super().__init__(*args, **kw)
  214. self.cmd_opts.add_option(cmdoptions.no_clean())
  215. @staticmethod
  216. def determine_resolver_variant(options: Values) -> str:
  217. """Determines which resolver should be used, based on the given options."""
  218. if "legacy-resolver" in options.deprecated_features_enabled:
  219. return "legacy"
  220. return "2020-resolver"
  221. @classmethod
  222. def make_requirement_preparer(
  223. cls,
  224. temp_build_dir: TempDirectory,
  225. options: Values,
  226. build_tracker: BuildTracker,
  227. session: PipSession,
  228. finder: PackageFinder,
  229. use_user_site: bool,
  230. download_dir: Optional[str] = None,
  231. verbosity: int = 0,
  232. ) -> RequirementPreparer:
  233. """
  234. Create a RequirementPreparer instance for the given parameters.
  235. """
  236. temp_build_dir_path = temp_build_dir.path
  237. assert temp_build_dir_path is not None
  238. resolver_variant = cls.determine_resolver_variant(options)
  239. if resolver_variant == "2020-resolver":
  240. lazy_wheel = "fast-deps" in options.features_enabled
  241. if lazy_wheel:
  242. logger.warning(
  243. "pip is using lazily downloaded wheels using HTTP "
  244. "range requests to obtain dependency information. "
  245. "This experimental feature is enabled through "
  246. "--use-feature=fast-deps and it is not ready for "
  247. "production."
  248. )
  249. else:
  250. lazy_wheel = False
  251. if "fast-deps" in options.features_enabled:
  252. logger.warning(
  253. "fast-deps has no effect when used with the legacy resolver."
  254. )
  255. return RequirementPreparer(
  256. build_dir=temp_build_dir_path,
  257. src_dir=options.src_dir,
  258. download_dir=download_dir,
  259. build_isolation=options.build_isolation,
  260. check_build_deps=options.check_build_deps,
  261. build_tracker=build_tracker,
  262. session=session,
  263. progress_bar=options.progress_bar,
  264. finder=finder,
  265. require_hashes=options.require_hashes,
  266. use_user_site=use_user_site,
  267. lazy_wheel=lazy_wheel,
  268. verbosity=verbosity,
  269. )
  270. @classmethod
  271. def make_resolver(
  272. cls,
  273. preparer: RequirementPreparer,
  274. finder: PackageFinder,
  275. options: Values,
  276. wheel_cache: Optional[WheelCache] = None,
  277. use_user_site: bool = False,
  278. ignore_installed: bool = True,
  279. ignore_requires_python: bool = False,
  280. force_reinstall: bool = False,
  281. upgrade_strategy: str = "to-satisfy-only",
  282. use_pep517: Optional[bool] = None,
  283. py_version_info: Optional[Tuple[int, ...]] = None,
  284. ) -> BaseResolver:
  285. """
  286. Create a Resolver instance for the given parameters.
  287. """
  288. make_install_req = partial(
  289. install_req_from_req_string,
  290. isolated=options.isolated_mode,
  291. use_pep517=use_pep517,
  292. )
  293. resolver_variant = cls.determine_resolver_variant(options)
  294. # The long import name and duplicated invocation is needed to convince
  295. # Mypy into correctly typechecking. Otherwise it would complain the
  296. # "Resolver" class being redefined.
  297. if resolver_variant == "2020-resolver":
  298. import pip._internal.resolution.resolvelib.resolver
  299. return pip._internal.resolution.resolvelib.resolver.Resolver(
  300. preparer=preparer,
  301. finder=finder,
  302. wheel_cache=wheel_cache,
  303. make_install_req=make_install_req,
  304. use_user_site=use_user_site,
  305. ignore_dependencies=options.ignore_dependencies,
  306. ignore_installed=ignore_installed,
  307. ignore_requires_python=ignore_requires_python,
  308. force_reinstall=force_reinstall,
  309. upgrade_strategy=upgrade_strategy,
  310. py_version_info=py_version_info,
  311. )
  312. import pip._internal.resolution.legacy.resolver
  313. return pip._internal.resolution.legacy.resolver.Resolver(
  314. preparer=preparer,
  315. finder=finder,
  316. wheel_cache=wheel_cache,
  317. make_install_req=make_install_req,
  318. use_user_site=use_user_site,
  319. ignore_dependencies=options.ignore_dependencies,
  320. ignore_installed=ignore_installed,
  321. ignore_requires_python=ignore_requires_python,
  322. force_reinstall=force_reinstall,
  323. upgrade_strategy=upgrade_strategy,
  324. py_version_info=py_version_info,
  325. )
  326. def get_requirements(
  327. self,
  328. args: List[str],
  329. options: Values,
  330. finder: PackageFinder,
  331. session: PipSession,
  332. ) -> List[InstallRequirement]:
  333. """
  334. Parse command-line arguments into the corresponding requirements.
  335. """
  336. requirements: List[InstallRequirement] = []
  337. for filename in options.constraints:
  338. for parsed_req in parse_requirements(
  339. filename,
  340. constraint=True,
  341. finder=finder,
  342. options=options,
  343. session=session,
  344. ):
  345. req_to_add = install_req_from_parsed_requirement(
  346. parsed_req,
  347. isolated=options.isolated_mode,
  348. user_supplied=False,
  349. )
  350. requirements.append(req_to_add)
  351. for req in args:
  352. req_to_add = install_req_from_line(
  353. req,
  354. comes_from=None,
  355. isolated=options.isolated_mode,
  356. use_pep517=options.use_pep517,
  357. user_supplied=True,
  358. config_settings=getattr(options, "config_settings", None),
  359. )
  360. requirements.append(req_to_add)
  361. for req in options.editables:
  362. req_to_add = install_req_from_editable(
  363. req,
  364. user_supplied=True,
  365. isolated=options.isolated_mode,
  366. use_pep517=options.use_pep517,
  367. config_settings=getattr(options, "config_settings", None),
  368. )
  369. requirements.append(req_to_add)
  370. # NOTE: options.require_hashes may be set if --require-hashes is True
  371. for filename in options.requirements:
  372. for parsed_req in parse_requirements(
  373. filename, finder=finder, options=options, session=session
  374. ):
  375. req_to_add = install_req_from_parsed_requirement(
  376. parsed_req,
  377. isolated=options.isolated_mode,
  378. use_pep517=options.use_pep517,
  379. user_supplied=True,
  380. config_settings=parsed_req.options.get("config_settings")
  381. if parsed_req.options
  382. else None,
  383. )
  384. requirements.append(req_to_add)
  385. # If any requirement has hash options, enable hash checking.
  386. if any(req.has_hash_options for req in requirements):
  387. options.require_hashes = True
  388. if not (args or options.editables or options.requirements):
  389. opts = {"name": self.name}
  390. if options.find_links:
  391. raise CommandError(
  392. "You must give at least one requirement to {name} "
  393. '(maybe you meant "pip {name} {links}"?)'.format(
  394. **dict(opts, links=" ".join(options.find_links))
  395. )
  396. )
  397. else:
  398. raise CommandError(
  399. "You must give at least one requirement to {name} "
  400. '(see "pip help {name}")'.format(**opts)
  401. )
  402. return requirements
  403. @staticmethod
  404. def trace_basic_info(finder: PackageFinder) -> None:
  405. """
  406. Trace basic information about the provided objects.
  407. """
  408. # Display where finder is looking for packages
  409. search_scope = finder.search_scope
  410. locations = search_scope.get_formatted_locations()
  411. if locations:
  412. logger.info(locations)
  413. def _build_package_finder(
  414. self,
  415. options: Values,
  416. session: PipSession,
  417. target_python: Optional[TargetPython] = None,
  418. ignore_requires_python: Optional[bool] = None,
  419. ) -> PackageFinder:
  420. """
  421. Create a package finder appropriate to this requirement command.
  422. :param ignore_requires_python: Whether to ignore incompatible
  423. "Requires-Python" values in links. Defaults to False.
  424. """
  425. link_collector = LinkCollector.create(session, options=options)
  426. selection_prefs = SelectionPreferences(
  427. allow_yanked=True,
  428. format_control=options.format_control,
  429. allow_all_prereleases=options.pre,
  430. prefer_binary=options.prefer_binary,
  431. ignore_requires_python=ignore_requires_python,
  432. )
  433. return PackageFinder.create(
  434. link_collector=link_collector,
  435. selection_prefs=selection_prefs,
  436. target_python=target_python,
  437. )