install.py 26 KB

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