m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

505 lines
18 KiB

6 months ago
  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. from pip._vendor import truststore
  53. except ImportError as e:
  54. raise CommandError(f"The truststore feature is unavailable: {e}")
  55. return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  56. class SessionCommandMixin(CommandContextMixIn):
  57. """
  58. A class mixin for command classes needing _build_session().
  59. """
  60. def __init__(self) -> None:
  61. super().__init__()
  62. self._session: Optional[PipSession] = None
  63. @classmethod
  64. def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
  65. """Return a list of index urls from user-provided options."""
  66. index_urls = []
  67. if not getattr(options, "no_index", False):
  68. url = getattr(options, "index_url", None)
  69. if url:
  70. index_urls.append(url)
  71. urls = getattr(options, "extra_index_urls", None)
  72. if urls:
  73. index_urls.extend(urls)
  74. # Return None rather than an empty list
  75. return index_urls or None
  76. def get_default_session(self, options: Values) -> PipSession:
  77. """Get a default-managed session."""
  78. if self._session is None:
  79. self._session = self.enter_context(self._build_session(options))
  80. # there's no type annotation on requests.Session, so it's
  81. # automatically ContextManager[Any] and self._session becomes Any,
  82. # then https://github.com/python/mypy/issues/7696 kicks in
  83. assert self._session is not None
  84. return self._session
  85. def _build_session(
  86. self,
  87. options: Values,
  88. retries: Optional[int] = None,
  89. timeout: Optional[int] = None,
  90. fallback_to_certifi: bool = False,
  91. ) -> PipSession:
  92. cache_dir = options.cache_dir
  93. assert not cache_dir or os.path.isabs(cache_dir)
  94. if "truststore" in options.features_enabled:
  95. try:
  96. ssl_context = _create_truststore_ssl_context()
  97. except Exception:
  98. if not fallback_to_certifi:
  99. raise
  100. ssl_context = None
  101. else:
  102. ssl_context = None
  103. session = PipSession(
  104. cache=os.path.join(cache_dir, "http-v2") if cache_dir else None,
  105. retries=retries if retries is not None else options.retries,
  106. trusted_hosts=options.trusted_hosts,
  107. index_urls=self._get_index_urls(options),
  108. ssl_context=ssl_context,
  109. )
  110. # Handle custom ca-bundles from the user
  111. if options.cert:
  112. session.verify = options.cert
  113. # Handle SSL client certificate
  114. if options.client_cert:
  115. session.cert = options.client_cert
  116. # Handle timeouts
  117. if options.timeout or timeout:
  118. session.timeout = timeout if timeout is not None else options.timeout
  119. # Handle configured proxies
  120. if options.proxy:
  121. session.proxies = {
  122. "http": options.proxy,
  123. "https": options.proxy,
  124. }
  125. # Determine if we can prompt the user for authentication or not
  126. session.auth.prompting = not options.no_input
  127. session.auth.keyring_provider = options.keyring_provider
  128. return session
  129. class IndexGroupCommand(Command, SessionCommandMixin):
  130. """
  131. Abstract base class for commands with the index_group options.
  132. This also corresponds to the commands that permit the pip version check.
  133. """
  134. def handle_pip_version_check(self, options: Values) -> None:
  135. """
  136. Do the pip version check if not disabled.
  137. This overrides the default behavior of not doing the check.
  138. """
  139. # Make sure the index_group options are present.
  140. assert hasattr(options, "no_index")
  141. if options.disable_pip_version_check or options.no_index:
  142. return
  143. # Otherwise, check if we're using the latest version of pip available.
  144. session = self._build_session(
  145. options,
  146. retries=0,
  147. timeout=min(5, options.timeout),
  148. # This is set to ensure the function does not fail when truststore is
  149. # specified in use-feature but cannot be loaded. This usually raises a
  150. # CommandError and shows a nice user-facing error, but this function is not
  151. # called in that try-except block.
  152. fallback_to_certifi=True,
  153. )
  154. with session:
  155. pip_self_version_check(session, options)
  156. KEEPABLE_TEMPDIR_TYPES = [
  157. tempdir_kinds.BUILD_ENV,
  158. tempdir_kinds.EPHEM_WHEEL_CACHE,
  159. tempdir_kinds.REQ_BUILD,
  160. ]
  161. def warn_if_run_as_root() -> None:
  162. """Output a warning for sudo users on Unix.
  163. In a virtual environment, sudo pip still writes to virtualenv.
  164. On Windows, users may run pip as Administrator without issues.
  165. This warning only applies to Unix root users outside of virtualenv.
  166. """
  167. if running_under_virtualenv():
  168. return
  169. if not hasattr(os, "getuid"):
  170. return
  171. # On Windows, there are no "system managed" Python packages. Installing as
  172. # Administrator via pip is the correct way of updating system environments.
  173. #
  174. # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
  175. # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
  176. if sys.platform == "win32" or sys.platform == "cygwin":
  177. return
  178. if os.getuid() != 0:
  179. return
  180. logger.warning(
  181. "Running pip as the 'root' user can result in broken permissions and "
  182. "conflicting behaviour with the system package manager. "
  183. "It is recommended to use a virtual environment instead: "
  184. "https://pip.pypa.io/warnings/venv"
  185. )
  186. def with_cleanup(func: Any) -> Any:
  187. """Decorator for common logic related to managing temporary
  188. directories.
  189. """
  190. def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
  191. for t in KEEPABLE_TEMPDIR_TYPES:
  192. registry.set_delete(t, False)
  193. def wrapper(
  194. self: RequirementCommand, options: Values, args: List[Any]
  195. ) -> Optional[int]:
  196. assert self.tempdir_registry is not None
  197. if options.no_clean:
  198. configure_tempdir_registry(self.tempdir_registry)
  199. try:
  200. return func(self, options, args)
  201. except PreviousBuildDirError:
  202. # This kind of conflict can occur when the user passes an explicit
  203. # build directory with a pre-existing folder. In that case we do
  204. # not want to accidentally remove it.
  205. configure_tempdir_registry(self.tempdir_registry)
  206. raise
  207. return wrapper
  208. class RequirementCommand(IndexGroupCommand):
  209. def __init__(self, *args: Any, **kw: Any) -> None:
  210. super().__init__(*args, **kw)
  211. self.cmd_opts.add_option(cmdoptions.no_clean())
  212. @staticmethod
  213. def determine_resolver_variant(options: Values) -> str:
  214. """Determines which resolver should be used, based on the given options."""
  215. if "legacy-resolver" in options.deprecated_features_enabled:
  216. return "legacy"
  217. return "resolvelib"
  218. @classmethod
  219. def make_requirement_preparer(
  220. cls,
  221. temp_build_dir: TempDirectory,
  222. options: Values,
  223. build_tracker: BuildTracker,
  224. session: PipSession,
  225. finder: PackageFinder,
  226. use_user_site: bool,
  227. download_dir: Optional[str] = None,
  228. verbosity: int = 0,
  229. ) -> RequirementPreparer:
  230. """
  231. Create a RequirementPreparer instance for the given parameters.
  232. """
  233. temp_build_dir_path = temp_build_dir.path
  234. assert temp_build_dir_path is not None
  235. legacy_resolver = False
  236. resolver_variant = cls.determine_resolver_variant(options)
  237. if resolver_variant == "resolvelib":
  238. lazy_wheel = "fast-deps" in options.features_enabled
  239. if lazy_wheel:
  240. logger.warning(
  241. "pip is using lazily downloaded wheels using HTTP "
  242. "range requests to obtain dependency information. "
  243. "This experimental feature is enabled through "
  244. "--use-feature=fast-deps and it is not ready for "
  245. "production."
  246. )
  247. else:
  248. legacy_resolver = True
  249. lazy_wheel = False
  250. if "fast-deps" in options.features_enabled:
  251. logger.warning(
  252. "fast-deps has no effect when used with the legacy resolver."
  253. )
  254. return RequirementPreparer(
  255. build_dir=temp_build_dir_path,
  256. src_dir=options.src_dir,
  257. download_dir=download_dir,
  258. build_isolation=options.build_isolation,
  259. check_build_deps=options.check_build_deps,
  260. build_tracker=build_tracker,
  261. session=session,
  262. progress_bar=options.progress_bar,
  263. finder=finder,
  264. require_hashes=options.require_hashes,
  265. use_user_site=use_user_site,
  266. lazy_wheel=lazy_wheel,
  267. verbosity=verbosity,
  268. legacy_resolver=legacy_resolver,
  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 == "resolvelib":
  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. )