install.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. import errno
  2. import operator
  3. import os
  4. import shutil
  5. import site
  6. from optparse import SUPPRESS_HELP, Values
  7. from typing import Iterable, List, Optional
  8. from pip._vendor.packaging.utils import canonicalize_name
  9. from pip._internal.cache import WheelCache
  10. from pip._internal.cli import cmdoptions
  11. from pip._internal.cli.cmdoptions import make_target_python
  12. from pip._internal.cli.req_command import (
  13. RequirementCommand,
  14. warn_if_run_as_root,
  15. with_cleanup,
  16. )
  17. from pip._internal.cli.status_codes import ERROR, SUCCESS
  18. from pip._internal.exceptions import CommandError, InstallationError
  19. from pip._internal.locations import get_scheme
  20. from pip._internal.metadata import get_environment
  21. from pip._internal.models.format_control import FormatControl
  22. from pip._internal.operations.check import ConflictDetails, check_install_conflicts
  23. from pip._internal.req import install_given_reqs
  24. from pip._internal.req.req_install import InstallRequirement
  25. from pip._internal.req.req_tracker import get_requirement_tracker
  26. from pip._internal.utils.compat import WINDOWS
  27. from pip._internal.utils.distutils_args import parse_distutils_args
  28. from pip._internal.utils.filesystem import test_writable_dir
  29. from pip._internal.utils.logging import getLogger
  30. from pip._internal.utils.misc import (
  31. ensure_dir,
  32. get_pip_version,
  33. protect_pip_from_modification_on_windows,
  34. write_output,
  35. )
  36. from pip._internal.utils.temp_dir import TempDirectory
  37. from pip._internal.utils.virtualenv import (
  38. running_under_virtualenv,
  39. virtualenv_no_global,
  40. )
  41. from pip._internal.wheel_builder import (
  42. BinaryAllowedPredicate,
  43. build,
  44. should_build_for_install_command,
  45. )
  46. logger = getLogger(__name__)
  47. def get_check_binary_allowed(format_control: FormatControl) -> BinaryAllowedPredicate:
  48. def check_binary_allowed(req: InstallRequirement) -> bool:
  49. canonical_name = canonicalize_name(req.name or "")
  50. allowed_formats = format_control.get_allowed_formats(canonical_name)
  51. return "binary" in allowed_formats
  52. return check_binary_allowed
  53. class InstallCommand(RequirementCommand):
  54. """
  55. Install packages from:
  56. - PyPI (and other indexes) using requirement specifiers.
  57. - VCS project urls.
  58. - Local project directories.
  59. - Local or remote source archives.
  60. pip also supports installing from "requirements files", which provide
  61. an easy way to specify a whole environment to be installed.
  62. """
  63. usage = """
  64. %prog [options] <requirement specifier> [package-index-options] ...
  65. %prog [options] -r <requirements file> [package-index-options] ...
  66. %prog [options] [-e] <vcs project url> ...
  67. %prog [options] [-e] <local project path> ...
  68. %prog [options] <archive url/path> ..."""
  69. def add_options(self) -> None:
  70. self.cmd_opts.add_option(cmdoptions.requirements())
  71. self.cmd_opts.add_option(cmdoptions.constraints())
  72. self.cmd_opts.add_option(cmdoptions.no_deps())
  73. self.cmd_opts.add_option(cmdoptions.pre())
  74. self.cmd_opts.add_option(cmdoptions.editable())
  75. self.cmd_opts.add_option(
  76. '-t', '--target',
  77. dest='target_dir',
  78. metavar='dir',
  79. default=None,
  80. help='Install packages into <dir>. '
  81. 'By default this will not replace existing files/folders in '
  82. '<dir>. Use --upgrade to replace existing packages in <dir> '
  83. 'with new versions.'
  84. )
  85. cmdoptions.add_target_python_options(self.cmd_opts)
  86. self.cmd_opts.add_option(
  87. '--user',
  88. dest='use_user_site',
  89. action='store_true',
  90. help="Install to the Python user install directory for your "
  91. "platform. Typically ~/.local/, or %APPDATA%\\Python on "
  92. "Windows. (See the Python documentation for site.USER_BASE "
  93. "for full details.)")
  94. self.cmd_opts.add_option(
  95. '--no-user',
  96. dest='use_user_site',
  97. action='store_false',
  98. help=SUPPRESS_HELP)
  99. self.cmd_opts.add_option(
  100. '--root',
  101. dest='root_path',
  102. metavar='dir',
  103. default=None,
  104. help="Install everything relative to this alternate root "
  105. "directory.")
  106. self.cmd_opts.add_option(
  107. '--prefix',
  108. dest='prefix_path',
  109. metavar='dir',
  110. default=None,
  111. help="Installation prefix where lib, bin and other top-level "
  112. "folders are placed")
  113. self.cmd_opts.add_option(cmdoptions.build_dir())
  114. self.cmd_opts.add_option(cmdoptions.src())
  115. self.cmd_opts.add_option(
  116. '-U', '--upgrade',
  117. dest='upgrade',
  118. action='store_true',
  119. help='Upgrade all specified packages to the newest available '
  120. 'version. The handling of dependencies depends on the '
  121. 'upgrade-strategy used.'
  122. )
  123. self.cmd_opts.add_option(
  124. '--upgrade-strategy',
  125. dest='upgrade_strategy',
  126. default='only-if-needed',
  127. choices=['only-if-needed', 'eager'],
  128. help='Determines how dependency upgrading should be handled '
  129. '[default: %default]. '
  130. '"eager" - dependencies are upgraded regardless of '
  131. 'whether the currently installed version satisfies the '
  132. 'requirements of the upgraded package(s). '
  133. '"only-if-needed" - are upgraded only when they do not '
  134. 'satisfy the requirements of the upgraded package(s).'
  135. )
  136. self.cmd_opts.add_option(
  137. '--force-reinstall',
  138. dest='force_reinstall',
  139. action='store_true',
  140. help='Reinstall all packages even if they are already '
  141. 'up-to-date.')
  142. self.cmd_opts.add_option(
  143. '-I', '--ignore-installed',
  144. dest='ignore_installed',
  145. action='store_true',
  146. help='Ignore the installed packages, overwriting them. '
  147. 'This can break your system if the existing package '
  148. 'is of a different version or was installed '
  149. 'with a different package manager!'
  150. )
  151. self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
  152. self.cmd_opts.add_option(cmdoptions.no_build_isolation())
  153. self.cmd_opts.add_option(cmdoptions.use_pep517())
  154. self.cmd_opts.add_option(cmdoptions.no_use_pep517())
  155. self.cmd_opts.add_option(cmdoptions.install_options())
  156. self.cmd_opts.add_option(cmdoptions.global_options())
  157. self.cmd_opts.add_option(
  158. "--compile",
  159. action="store_true",
  160. dest="compile",
  161. default=True,
  162. help="Compile Python source files to bytecode",
  163. )
  164. self.cmd_opts.add_option(
  165. "--no-compile",
  166. action="store_false",
  167. dest="compile",
  168. help="Do not compile Python source files to bytecode",
  169. )
  170. self.cmd_opts.add_option(
  171. "--no-warn-script-location",
  172. action="store_false",
  173. dest="warn_script_location",
  174. default=True,
  175. help="Do not warn when installing scripts outside PATH",
  176. )
  177. self.cmd_opts.add_option(
  178. "--no-warn-conflicts",
  179. action="store_false",
  180. dest="warn_about_conflicts",
  181. default=True,
  182. help="Do not warn about broken dependencies",
  183. )
  184. self.cmd_opts.add_option(cmdoptions.no_binary())
  185. self.cmd_opts.add_option(cmdoptions.only_binary())
  186. self.cmd_opts.add_option(cmdoptions.prefer_binary())
  187. self.cmd_opts.add_option(cmdoptions.require_hashes())
  188. self.cmd_opts.add_option(cmdoptions.progress_bar())
  189. index_opts = cmdoptions.make_option_group(
  190. cmdoptions.index_group,
  191. self.parser,
  192. )
  193. self.parser.insert_option_group(0, index_opts)
  194. self.parser.insert_option_group(0, self.cmd_opts)
  195. @with_cleanup
  196. def run(self, options: Values, args: List[str]) -> int:
  197. if options.use_user_site and options.target_dir is not None:
  198. raise CommandError("Can not combine '--user' and '--target'")
  199. cmdoptions.check_install_build_global(options)
  200. upgrade_strategy = "to-satisfy-only"
  201. if options.upgrade:
  202. upgrade_strategy = options.upgrade_strategy
  203. cmdoptions.check_dist_restriction(options, check_target=True)
  204. install_options = options.install_options or []
  205. logger.verbose("Using %s", get_pip_version())
  206. options.use_user_site = decide_user_install(
  207. options.use_user_site,
  208. prefix_path=options.prefix_path,
  209. target_dir=options.target_dir,
  210. root_path=options.root_path,
  211. isolated_mode=options.isolated_mode,
  212. )
  213. target_temp_dir: Optional[TempDirectory] = None
  214. target_temp_dir_path: Optional[str] = None
  215. if options.target_dir:
  216. options.ignore_installed = True
  217. options.target_dir = os.path.abspath(options.target_dir)
  218. if (os.path.exists(options.target_dir) and not
  219. os.path.isdir(options.target_dir)):
  220. raise CommandError(
  221. "Target path exists but is not a directory, will not "
  222. "continue."
  223. )
  224. # Create a target directory for using with the target option
  225. target_temp_dir = TempDirectory(kind="target")
  226. target_temp_dir_path = target_temp_dir.path
  227. self.enter_context(target_temp_dir)
  228. global_options = options.global_options or []
  229. session = self.get_default_session(options)
  230. target_python = make_target_python(options)
  231. finder = self._build_package_finder(
  232. options=options,
  233. session=session,
  234. target_python=target_python,
  235. ignore_requires_python=options.ignore_requires_python,
  236. )
  237. wheel_cache = WheelCache(options.cache_dir, options.format_control)
  238. req_tracker = self.enter_context(get_requirement_tracker())
  239. directory = TempDirectory(
  240. delete=not options.no_clean,
  241. kind="install",
  242. globally_managed=True,
  243. )
  244. try:
  245. reqs = self.get_requirements(args, options, finder, session)
  246. reject_location_related_install_options(
  247. reqs, options.install_options
  248. )
  249. preparer = self.make_requirement_preparer(
  250. temp_build_dir=directory,
  251. options=options,
  252. req_tracker=req_tracker,
  253. session=session,
  254. finder=finder,
  255. use_user_site=options.use_user_site,
  256. )
  257. resolver = self.make_resolver(
  258. preparer=preparer,
  259. finder=finder,
  260. options=options,
  261. wheel_cache=wheel_cache,
  262. use_user_site=options.use_user_site,
  263. ignore_installed=options.ignore_installed,
  264. ignore_requires_python=options.ignore_requires_python,
  265. force_reinstall=options.force_reinstall,
  266. upgrade_strategy=upgrade_strategy,
  267. use_pep517=options.use_pep517,
  268. )
  269. self.trace_basic_info(finder)
  270. requirement_set = resolver.resolve(
  271. reqs, check_supported_wheels=not options.target_dir
  272. )
  273. try:
  274. pip_req = requirement_set.get_requirement("pip")
  275. except KeyError:
  276. modifying_pip = False
  277. else:
  278. # If we're not replacing an already installed pip,
  279. # we're not modifying it.
  280. modifying_pip = pip_req.satisfied_by is None
  281. protect_pip_from_modification_on_windows(
  282. modifying_pip=modifying_pip
  283. )
  284. check_binary_allowed = get_check_binary_allowed(
  285. finder.format_control
  286. )
  287. reqs_to_build = [
  288. r for r in requirement_set.requirements.values()
  289. if should_build_for_install_command(
  290. r, check_binary_allowed
  291. )
  292. ]
  293. _, build_failures = build(
  294. reqs_to_build,
  295. wheel_cache=wheel_cache,
  296. verify=True,
  297. build_options=[],
  298. global_options=[],
  299. )
  300. # If we're using PEP 517, we cannot do a direct install
  301. # so we fail here.
  302. pep517_build_failure_names: List[str] = [
  303. r.name # type: ignore
  304. for r in build_failures if r.use_pep517
  305. ]
  306. if pep517_build_failure_names:
  307. raise InstallationError(
  308. "Could not build wheels for {} which use"
  309. " PEP 517 and cannot be installed directly".format(
  310. ", ".join(pep517_build_failure_names)
  311. )
  312. )
  313. # For now, we just warn about failures building legacy
  314. # requirements, as we'll fall through to a direct
  315. # install for those.
  316. for r in build_failures:
  317. if not r.use_pep517:
  318. r.legacy_install_reason = 8368
  319. to_install = resolver.get_installation_order(
  320. requirement_set
  321. )
  322. # Check for conflicts in the package set we're installing.
  323. conflicts: Optional[ConflictDetails] = None
  324. should_warn_about_conflicts = (
  325. not options.ignore_dependencies and
  326. options.warn_about_conflicts
  327. )
  328. if should_warn_about_conflicts:
  329. conflicts = self._determine_conflicts(to_install)
  330. # Don't warn about script install locations if
  331. # --target or --prefix has been specified
  332. warn_script_location = options.warn_script_location
  333. if options.target_dir or options.prefix_path:
  334. warn_script_location = False
  335. installed = install_given_reqs(
  336. to_install,
  337. install_options,
  338. global_options,
  339. root=options.root_path,
  340. home=target_temp_dir_path,
  341. prefix=options.prefix_path,
  342. warn_script_location=warn_script_location,
  343. use_user_site=options.use_user_site,
  344. pycompile=options.compile,
  345. )
  346. lib_locations = get_lib_location_guesses(
  347. user=options.use_user_site,
  348. home=target_temp_dir_path,
  349. root=options.root_path,
  350. prefix=options.prefix_path,
  351. isolated=options.isolated_mode,
  352. )
  353. env = get_environment(lib_locations)
  354. installed.sort(key=operator.attrgetter('name'))
  355. items = []
  356. for result in installed:
  357. item = result.name
  358. try:
  359. installed_dist = env.get_distribution(item)
  360. if installed_dist is not None:
  361. item = f"{item}-{installed_dist.version}"
  362. except Exception:
  363. pass
  364. items.append(item)
  365. if conflicts is not None:
  366. self._warn_about_conflicts(
  367. conflicts,
  368. resolver_variant=self.determine_resolver_variant(options),
  369. )
  370. installed_desc = ' '.join(items)
  371. if installed_desc:
  372. write_output(
  373. 'Successfully installed %s', installed_desc,
  374. )
  375. except OSError as error:
  376. show_traceback = (self.verbosity >= 1)
  377. message = create_os_error_message(
  378. error, show_traceback, options.use_user_site,
  379. )
  380. logger.error(message, exc_info=show_traceback) # noqa
  381. return ERROR
  382. if options.target_dir:
  383. assert target_temp_dir
  384. self._handle_target_dir(
  385. options.target_dir, target_temp_dir, options.upgrade
  386. )
  387. warn_if_run_as_root()
  388. return SUCCESS
  389. def _handle_target_dir(
  390. self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool
  391. ) -> None:
  392. ensure_dir(target_dir)
  393. # Checking both purelib and platlib directories for installed
  394. # packages to be moved to target directory
  395. lib_dir_list = []
  396. # Checking both purelib and platlib directories for installed
  397. # packages to be moved to target directory
  398. scheme = get_scheme('', home=target_temp_dir.path)
  399. purelib_dir = scheme.purelib
  400. platlib_dir = scheme.platlib
  401. data_dir = scheme.data
  402. if os.path.exists(purelib_dir):
  403. lib_dir_list.append(purelib_dir)
  404. if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:
  405. lib_dir_list.append(platlib_dir)
  406. if os.path.exists(data_dir):
  407. lib_dir_list.append(data_dir)
  408. for lib_dir in lib_dir_list:
  409. for item in os.listdir(lib_dir):
  410. if lib_dir == data_dir:
  411. ddir = os.path.join(data_dir, item)
  412. if any(s.startswith(ddir) for s in lib_dir_list[:-1]):
  413. continue
  414. target_item_dir = os.path.join(target_dir, item)
  415. if os.path.exists(target_item_dir):
  416. if not upgrade:
  417. logger.warning(
  418. 'Target directory %s already exists. Specify '
  419. '--upgrade to force replacement.',
  420. target_item_dir
  421. )
  422. continue
  423. if os.path.islink(target_item_dir):
  424. logger.warning(
  425. 'Target directory %s already exists and is '
  426. 'a link. pip will not automatically replace '
  427. 'links, please remove if replacement is '
  428. 'desired.',
  429. target_item_dir
  430. )
  431. continue
  432. if os.path.isdir(target_item_dir):
  433. shutil.rmtree(target_item_dir)
  434. else:
  435. os.remove(target_item_dir)
  436. shutil.move(
  437. os.path.join(lib_dir, item),
  438. target_item_dir
  439. )
  440. def _determine_conflicts(
  441. self, to_install: List[InstallRequirement]
  442. ) -> Optional[ConflictDetails]:
  443. try:
  444. return check_install_conflicts(to_install)
  445. except Exception:
  446. logger.exception(
  447. "Error while checking for conflicts. Please file an issue on "
  448. "pip's issue tracker: https://github.com/pypa/pip/issues/new"
  449. )
  450. return None
  451. def _warn_about_conflicts(
  452. self, conflict_details: ConflictDetails, resolver_variant: str
  453. ) -> None:
  454. package_set, (missing, conflicting) = conflict_details
  455. if not missing and not conflicting:
  456. return
  457. parts: List[str] = []
  458. if resolver_variant == "legacy":
  459. parts.append(
  460. "pip's legacy dependency resolver does not consider dependency "
  461. "conflicts when selecting packages. This behaviour is the "
  462. "source of the following dependency conflicts."
  463. )
  464. else:
  465. assert resolver_variant == "2020-resolver"
  466. parts.append(
  467. "pip's dependency resolver does not currently take into account "
  468. "all the packages that are installed. This behaviour is the "
  469. "source of the following dependency conflicts."
  470. )
  471. # NOTE: There is some duplication here, with commands/check.py
  472. for project_name in missing:
  473. version = package_set[project_name][0]
  474. for dependency in missing[project_name]:
  475. message = (
  476. "{name} {version} requires {requirement}, "
  477. "which is not installed."
  478. ).format(
  479. name=project_name,
  480. version=version,
  481. requirement=dependency[1],
  482. )
  483. parts.append(message)
  484. for project_name in conflicting:
  485. version = package_set[project_name][0]
  486. for dep_name, dep_version, req in conflicting[project_name]:
  487. message = (
  488. "{name} {version} requires {requirement}, but {you} have "
  489. "{dep_name} {dep_version} which is incompatible."
  490. ).format(
  491. name=project_name,
  492. version=version,
  493. requirement=req,
  494. dep_name=dep_name,
  495. dep_version=dep_version,
  496. you=("you" if resolver_variant == "2020-resolver" else "you'll")
  497. )
  498. parts.append(message)
  499. logger.critical("\n".join(parts))
  500. def get_lib_location_guesses(
  501. user: bool = False,
  502. home: Optional[str] = None,
  503. root: Optional[str] = None,
  504. isolated: bool = False,
  505. prefix: Optional[str] = None
  506. ) -> List[str]:
  507. scheme = get_scheme(
  508. '',
  509. user=user,
  510. home=home,
  511. root=root,
  512. isolated=isolated,
  513. prefix=prefix,
  514. )
  515. return [scheme.purelib, scheme.platlib]
  516. def site_packages_writable(root: Optional[str], isolated: bool) -> bool:
  517. return all(
  518. test_writable_dir(d) for d in set(
  519. get_lib_location_guesses(root=root, isolated=isolated))
  520. )
  521. def decide_user_install(
  522. use_user_site: Optional[bool],
  523. prefix_path: Optional[str] = None,
  524. target_dir: Optional[str] = None,
  525. root_path: Optional[str] = None,
  526. isolated_mode: bool = False,
  527. ) -> bool:
  528. """Determine whether to do a user install based on the input options.
  529. If use_user_site is False, no additional checks are done.
  530. If use_user_site is True, it is checked for compatibility with other
  531. options.
  532. If use_user_site is None, the default behaviour depends on the environment,
  533. which is provided by the other arguments.
  534. """
  535. # In some cases (config from tox), use_user_site can be set to an integer
  536. # rather than a bool, which 'use_user_site is False' wouldn't catch.
  537. if (use_user_site is not None) and (not use_user_site):
  538. logger.debug("Non-user install by explicit request")
  539. return False
  540. if use_user_site:
  541. if prefix_path:
  542. raise CommandError(
  543. "Can not combine '--user' and '--prefix' as they imply "
  544. "different installation locations"
  545. )
  546. if virtualenv_no_global():
  547. raise InstallationError(
  548. "Can not perform a '--user' install. User site-packages "
  549. "are not visible in this virtualenv."
  550. )
  551. logger.debug("User install by explicit request")
  552. return True
  553. # If we are here, user installs have not been explicitly requested/avoided
  554. assert use_user_site is None
  555. # user install incompatible with --prefix/--target
  556. if prefix_path or target_dir:
  557. logger.debug("Non-user install due to --prefix or --target option")
  558. return False
  559. # If user installs are not enabled, choose a non-user install
  560. if not site.ENABLE_USER_SITE:
  561. logger.debug("Non-user install because user site-packages disabled")
  562. return False
  563. # If we have permission for a non-user install, do that,
  564. # otherwise do a user install.
  565. if site_packages_writable(root=root_path, isolated=isolated_mode):
  566. logger.debug("Non-user install because site-packages writeable")
  567. return False
  568. logger.info("Defaulting to user installation because normal site-packages "
  569. "is not writeable")
  570. return True
  571. def reject_location_related_install_options(
  572. requirements: List[InstallRequirement], options: Optional[List[str]]
  573. ) -> None:
  574. """If any location-changing --install-option arguments were passed for
  575. requirements or on the command-line, then show a deprecation warning.
  576. """
  577. def format_options(option_names: Iterable[str]) -> List[str]:
  578. return ["--{}".format(name.replace("_", "-")) for name in option_names]
  579. offenders = []
  580. for requirement in requirements:
  581. install_options = requirement.install_options
  582. location_options = parse_distutils_args(install_options)
  583. if location_options:
  584. offenders.append(
  585. "{!r} from {}".format(
  586. format_options(location_options.keys()), requirement
  587. )
  588. )
  589. if options:
  590. location_options = parse_distutils_args(options)
  591. if location_options:
  592. offenders.append(
  593. "{!r} from command line".format(
  594. format_options(location_options.keys())
  595. )
  596. )
  597. if not offenders:
  598. return
  599. raise CommandError(
  600. "Location-changing options found in --install-option: {}."
  601. " This is unsupported, use pip-level options like --user,"
  602. " --prefix, --root, and --target instead.".format(
  603. "; ".join(offenders)
  604. )
  605. )
  606. def create_os_error_message(
  607. error: OSError, show_traceback: bool, using_user_site: bool
  608. ) -> str:
  609. """Format an error message for an OSError
  610. It may occur anytime during the execution of the install command.
  611. """
  612. parts = []
  613. # Mention the error if we are not going to show a traceback
  614. parts.append("Could not install packages due to an OSError")
  615. if not show_traceback:
  616. parts.append(": ")
  617. parts.append(str(error))
  618. else:
  619. parts.append(".")
  620. # Spilt the error indication from a helper message (if any)
  621. parts[-1] += "\n"
  622. # Suggest useful actions to the user:
  623. # (1) using user site-packages or (2) verifying the permissions
  624. if error.errno == errno.EACCES:
  625. user_option_part = "Consider using the `--user` option"
  626. permissions_part = "Check the permissions"
  627. if not running_under_virtualenv() and not using_user_site:
  628. parts.extend([
  629. user_option_part, " or ",
  630. permissions_part.lower(),
  631. ])
  632. else:
  633. parts.append(permissions_part)
  634. parts.append(".\n")
  635. # Suggest the user to enable Long Paths if path length is
  636. # more than 260
  637. if (WINDOWS and error.errno == errno.ENOENT and error.filename and
  638. len(error.filename) > 260):
  639. parts.append(
  640. "HINT: This error might have occurred since "
  641. "this system does not have Windows Long Path "
  642. "support enabled. You can find information on "
  643. "how to enable this at "
  644. "https://pip.pypa.io/warnings/enable-long-paths\n"
  645. )
  646. return "".join(parts).strip() + "\n"