req_command.py 16 KB

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