install.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. from __future__ import absolute_import
  2. import errno
  3. import logging
  4. import operator
  5. import os
  6. import shutil
  7. import site
  8. from optparse import SUPPRESS_HELP
  9. from pip._vendor import pkg_resources
  10. from pip._vendor.packaging.utils import canonicalize_name
  11. from pip._internal.cache import WheelCache
  12. from pip._internal.cli import cmdoptions
  13. from pip._internal.cli.cmdoptions import make_target_python
  14. from pip._internal.cli.req_command import RequirementCommand, with_cleanup
  15. from pip._internal.cli.status_codes import ERROR, SUCCESS
  16. from pip._internal.exceptions import CommandError, InstallationError
  17. from pip._internal.locations import distutils_scheme
  18. from pip._internal.operations.check import check_install_conflicts
  19. from pip._internal.req import install_given_reqs
  20. from pip._internal.req.req_tracker import get_requirement_tracker
  21. from pip._internal.utils.distutils_args import parse_distutils_args
  22. from pip._internal.utils.filesystem import test_writable_dir
  23. from pip._internal.utils.misc import (
  24. ensure_dir,
  25. get_installed_version,
  26. get_pip_version,
  27. protect_pip_from_modification_on_windows,
  28. write_output,
  29. )
  30. from pip._internal.utils.temp_dir import TempDirectory
  31. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  32. from pip._internal.utils.virtualenv import virtualenv_no_global
  33. from pip._internal.wheel_builder import build, should_build_for_install_command
  34. if MYPY_CHECK_RUNNING:
  35. from optparse import Values
  36. from typing import Iterable, List, Optional
  37. from pip._internal.models.format_control import FormatControl
  38. from pip._internal.operations.check import ConflictDetails
  39. from pip._internal.req.req_install import InstallRequirement
  40. from pip._internal.wheel_builder import BinaryAllowedPredicate
  41. logger = logging.getLogger(__name__)
  42. def get_check_binary_allowed(format_control):
  43. # type: (FormatControl) -> BinaryAllowedPredicate
  44. def check_binary_allowed(req):
  45. # type: (InstallRequirement) -> bool
  46. if req.use_pep517:
  47. return True
  48. canonical_name = canonicalize_name(req.name)
  49. allowed_formats = format_control.get_allowed_formats(canonical_name)
  50. return "binary" in allowed_formats
  51. return check_binary_allowed
  52. class InstallCommand(RequirementCommand):
  53. """
  54. Install packages from:
  55. - PyPI (and other indexes) using requirement specifiers.
  56. - VCS project urls.
  57. - Local project directories.
  58. - Local or remote source archives.
  59. pip also supports installing from "requirements files", which provide
  60. an easy way to specify a whole environment to be installed.
  61. """
  62. usage = """
  63. %prog [options] <requirement specifier> [package-index-options] ...
  64. %prog [options] -r <requirements file> [package-index-options] ...
  65. %prog [options] [-e] <vcs project url> ...
  66. %prog [options] [-e] <local project path> ...
  67. %prog [options] <archive url/path> ..."""
  68. def add_options(self):
  69. # type: () -> 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, args):
  197. # type: (Values, List[str]) -> int
  198. if options.use_user_site and options.target_dir is not None:
  199. raise CommandError("Can not combine '--user' and '--target'")
  200. cmdoptions.check_install_build_global(options)
  201. upgrade_strategy = "to-satisfy-only"
  202. if options.upgrade:
  203. upgrade_strategy = options.upgrade_strategy
  204. cmdoptions.check_dist_restriction(options, check_target=True)
  205. install_options = options.install_options or []
  206. logger.debug("Using %s", get_pip_version())
  207. options.use_user_site = decide_user_install(
  208. options.use_user_site,
  209. prefix_path=options.prefix_path,
  210. target_dir=options.target_dir,
  211. root_path=options.root_path,
  212. isolated_mode=options.isolated_mode,
  213. )
  214. target_temp_dir = None # type: Optional[TempDirectory]
  215. target_temp_dir_path = None # type: Optional[str]
  216. if options.target_dir:
  217. options.ignore_installed = True
  218. options.target_dir = os.path.abspath(options.target_dir)
  219. if (os.path.exists(options.target_dir) and not
  220. os.path.isdir(options.target_dir)):
  221. raise CommandError(
  222. "Target path exists but is not a directory, will not "
  223. "continue."
  224. )
  225. # Create a target directory for using with the target option
  226. target_temp_dir = TempDirectory(kind="target")
  227. target_temp_dir_path = target_temp_dir.path
  228. self.enter_context(target_temp_dir)
  229. global_options = options.global_options or []
  230. session = self.get_default_session(options)
  231. target_python = make_target_python(options)
  232. finder = self._build_package_finder(
  233. options=options,
  234. session=session,
  235. target_python=target_python,
  236. ignore_requires_python=options.ignore_requires_python,
  237. )
  238. wheel_cache = WheelCache(options.cache_dir, options.format_control)
  239. req_tracker = self.enter_context(get_requirement_tracker())
  240. directory = TempDirectory(
  241. delete=not options.no_clean,
  242. kind="install",
  243. globally_managed=True,
  244. )
  245. try:
  246. reqs = self.get_requirements(args, options, finder, session)
  247. reject_location_related_install_options(
  248. reqs, options.install_options
  249. )
  250. preparer = self.make_requirement_preparer(
  251. temp_build_dir=directory,
  252. options=options,
  253. req_tracker=req_tracker,
  254. session=session,
  255. finder=finder,
  256. use_user_site=options.use_user_site,
  257. )
  258. resolver = self.make_resolver(
  259. preparer=preparer,
  260. finder=finder,
  261. options=options,
  262. wheel_cache=wheel_cache,
  263. use_user_site=options.use_user_site,
  264. ignore_installed=options.ignore_installed,
  265. ignore_requires_python=options.ignore_requires_python,
  266. force_reinstall=options.force_reinstall,
  267. upgrade_strategy=upgrade_strategy,
  268. use_pep517=options.use_pep517,
  269. )
  270. self.trace_basic_info(finder)
  271. requirement_set = resolver.resolve(
  272. reqs, check_supported_wheels=not options.target_dir
  273. )
  274. try:
  275. pip_req = requirement_set.get_requirement("pip")
  276. except KeyError:
  277. modifying_pip = False
  278. else:
  279. # If we're not replacing an already installed pip,
  280. # we're not modifying it.
  281. modifying_pip = pip_req.satisfied_by is None
  282. protect_pip_from_modification_on_windows(
  283. modifying_pip=modifying_pip
  284. )
  285. check_binary_allowed = get_check_binary_allowed(
  286. finder.format_control
  287. )
  288. reqs_to_build = [
  289. r for r in requirement_set.requirements.values()
  290. if should_build_for_install_command(
  291. r, check_binary_allowed
  292. )
  293. ]
  294. _, build_failures = build(
  295. reqs_to_build,
  296. wheel_cache=wheel_cache,
  297. verify=True,
  298. build_options=[],
  299. global_options=[],
  300. )
  301. # If we're using PEP 517, we cannot do a direct install
  302. # so we fail here.
  303. pep517_build_failure_names = [
  304. r.name # type: ignore
  305. for r in build_failures if r.use_pep517
  306. ] # type: List[str]
  307. if pep517_build_failure_names:
  308. raise InstallationError(
  309. "Could not build wheels for {} which use"
  310. " PEP 517 and cannot be installed directly".format(
  311. ", ".join(pep517_build_failure_names)
  312. )
  313. )
  314. # For now, we just warn about failures building legacy
  315. # requirements, as we'll fall through to a direct
  316. # install for those.
  317. for r in build_failures:
  318. if not r.use_pep517:
  319. r.legacy_install_reason = 8368
  320. to_install = resolver.get_installation_order(
  321. requirement_set
  322. )
  323. # Check for conflicts in the package set we're installing.
  324. conflicts = None # type: Optional[ConflictDetails]
  325. should_warn_about_conflicts = (
  326. not options.ignore_dependencies and
  327. options.warn_about_conflicts
  328. )
  329. if should_warn_about_conflicts:
  330. conflicts = self._determine_conflicts(to_install)
  331. # Don't warn about script install locations if
  332. # --target has been specified
  333. warn_script_location = options.warn_script_location
  334. if options.target_dir:
  335. warn_script_location = False
  336. installed = install_given_reqs(
  337. to_install,
  338. install_options,
  339. global_options,
  340. root=options.root_path,
  341. home=target_temp_dir_path,
  342. prefix=options.prefix_path,
  343. warn_script_location=warn_script_location,
  344. use_user_site=options.use_user_site,
  345. pycompile=options.compile,
  346. )
  347. lib_locations = get_lib_location_guesses(
  348. user=options.use_user_site,
  349. home=target_temp_dir_path,
  350. root=options.root_path,
  351. prefix=options.prefix_path,
  352. isolated=options.isolated_mode,
  353. )
  354. working_set = pkg_resources.WorkingSet(lib_locations)
  355. installed.sort(key=operator.attrgetter('name'))
  356. items = []
  357. for result in installed:
  358. item = result.name
  359. try:
  360. installed_version = get_installed_version(
  361. result.name, working_set=working_set
  362. )
  363. if installed_version:
  364. item += '-' + installed_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 EnvironmentError as error:
  379. show_traceback = (self.verbosity >= 1)
  380. message = create_env_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. return SUCCESS
  391. def _handle_target_dir(self, target_dir, target_temp_dir, upgrade):
  392. # type: (str, TempDirectory, bool) -> None
  393. ensure_dir(target_dir)
  394. # Checking both purelib and platlib directories for installed
  395. # packages to be moved to target directory
  396. lib_dir_list = []
  397. # Checking both purelib and platlib directories for installed
  398. # packages to be moved to target directory
  399. scheme = distutils_scheme('', home=target_temp_dir.path)
  400. purelib_dir = scheme['purelib']
  401. platlib_dir = scheme['platlib']
  402. data_dir = scheme['data']
  403. if os.path.exists(purelib_dir):
  404. lib_dir_list.append(purelib_dir)
  405. if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:
  406. lib_dir_list.append(platlib_dir)
  407. if os.path.exists(data_dir):
  408. lib_dir_list.append(data_dir)
  409. for lib_dir in lib_dir_list:
  410. for item in os.listdir(lib_dir):
  411. if lib_dir == data_dir:
  412. ddir = os.path.join(data_dir, item)
  413. if any(s.startswith(ddir) for s in lib_dir_list[:-1]):
  414. continue
  415. target_item_dir = os.path.join(target_dir, item)
  416. if os.path.exists(target_item_dir):
  417. if not upgrade:
  418. logger.warning(
  419. 'Target directory %s already exists. Specify '
  420. '--upgrade to force replacement.',
  421. target_item_dir
  422. )
  423. continue
  424. if os.path.islink(target_item_dir):
  425. logger.warning(
  426. 'Target directory %s already exists and is '
  427. 'a link. pip will not automatically replace '
  428. 'links, please remove if replacement is '
  429. 'desired.',
  430. target_item_dir
  431. )
  432. continue
  433. if os.path.isdir(target_item_dir):
  434. shutil.rmtree(target_item_dir)
  435. else:
  436. os.remove(target_item_dir)
  437. shutil.move(
  438. os.path.join(lib_dir, item),
  439. target_item_dir
  440. )
  441. def _determine_conflicts(self, to_install):
  442. # type: (List[InstallRequirement]) -> 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(self, conflict_details, resolver_variant):
  452. # type: (ConflictDetails, str) -> None
  453. package_set, (missing, conflicting) = conflict_details
  454. if not missing and not conflicting:
  455. return
  456. parts = [] # type: List[str]
  457. if resolver_variant == "legacy":
  458. parts.append(
  459. "pip's legacy dependency resolver does not consider dependency "
  460. "conflicts when selecting packages. This behaviour is the "
  461. "source of the following dependency conflicts."
  462. )
  463. else:
  464. assert resolver_variant == "2020-resolver"
  465. parts.append(
  466. "pip's dependency resolver does not currently take into account "
  467. "all the packages that are installed. This behaviour is the "
  468. "source of the following dependency conflicts."
  469. )
  470. # NOTE: There is some duplication here, with commands/check.py
  471. for project_name in missing:
  472. version = package_set[project_name][0]
  473. for dependency in missing[project_name]:
  474. message = (
  475. "{name} {version} requires {requirement}, "
  476. "which is not installed."
  477. ).format(
  478. name=project_name,
  479. version=version,
  480. requirement=dependency[1],
  481. )
  482. parts.append(message)
  483. for project_name in conflicting:
  484. version = package_set[project_name][0]
  485. for dep_name, dep_version, req in conflicting[project_name]:
  486. message = (
  487. "{name} {version} requires {requirement}, but {you} have "
  488. "{dep_name} {dep_version} which is incompatible."
  489. ).format(
  490. name=project_name,
  491. version=version,
  492. requirement=req,
  493. dep_name=dep_name,
  494. dep_version=dep_version,
  495. you=("you" if resolver_variant == "2020-resolver" else "you'll")
  496. )
  497. parts.append(message)
  498. logger.critical("\n".join(parts))
  499. def get_lib_location_guesses(
  500. user=False, # type: bool
  501. home=None, # type: Optional[str]
  502. root=None, # type: Optional[str]
  503. isolated=False, # type: bool
  504. prefix=None # type: Optional[str]
  505. ):
  506. # type:(...) -> List[str]
  507. scheme = distutils_scheme('', user=user, home=home, root=root,
  508. isolated=isolated, prefix=prefix)
  509. return [scheme['purelib'], scheme['platlib']]
  510. def site_packages_writable(root, isolated):
  511. # type: (Optional[str], bool) -> bool
  512. return all(
  513. test_writable_dir(d) for d in set(
  514. get_lib_location_guesses(root=root, isolated=isolated))
  515. )
  516. def decide_user_install(
  517. use_user_site, # type: Optional[bool]
  518. prefix_path=None, # type: Optional[str]
  519. target_dir=None, # type: Optional[str]
  520. root_path=None, # type: Optional[str]
  521. isolated_mode=False, # type: bool
  522. ):
  523. # type: (...) -> bool
  524. """Determine whether to do a user install based on the input options.
  525. If use_user_site is False, no additional checks are done.
  526. If use_user_site is True, it is checked for compatibility with other
  527. options.
  528. If use_user_site is None, the default behaviour depends on the environment,
  529. which is provided by the other arguments.
  530. """
  531. # In some cases (config from tox), use_user_site can be set to an integer
  532. # rather than a bool, which 'use_user_site is False' wouldn't catch.
  533. if (use_user_site is not None) and (not use_user_site):
  534. logger.debug("Non-user install by explicit request")
  535. return False
  536. if use_user_site:
  537. if prefix_path:
  538. raise CommandError(
  539. "Can not combine '--user' and '--prefix' as they imply "
  540. "different installation locations"
  541. )
  542. if virtualenv_no_global():
  543. raise InstallationError(
  544. "Can not perform a '--user' install. User site-packages "
  545. "are not visible in this virtualenv."
  546. )
  547. logger.debug("User install by explicit request")
  548. return True
  549. # If we are here, user installs have not been explicitly requested/avoided
  550. assert use_user_site is None
  551. # user install incompatible with --prefix/--target
  552. if prefix_path or target_dir:
  553. logger.debug("Non-user install due to --prefix or --target option")
  554. return False
  555. # If user installs are not enabled, choose a non-user install
  556. if not site.ENABLE_USER_SITE:
  557. logger.debug("Non-user install because user site-packages disabled")
  558. return False
  559. # If we have permission for a non-user install, do that,
  560. # otherwise do a user install.
  561. if site_packages_writable(root=root_path, isolated=isolated_mode):
  562. logger.debug("Non-user install because site-packages writeable")
  563. return False
  564. logger.info("Defaulting to user installation because normal site-packages "
  565. "is not writeable")
  566. return True
  567. def reject_location_related_install_options(requirements, options):
  568. # type: (List[InstallRequirement], Optional[List[str]]) -> None
  569. """If any location-changing --install-option arguments were passed for
  570. requirements or on the command-line, then show a deprecation warning.
  571. """
  572. def format_options(option_names):
  573. # type: (Iterable[str]) -> List[str]
  574. return ["--{}".format(name.replace("_", "-")) for name in option_names]
  575. offenders = []
  576. for requirement in requirements:
  577. install_options = requirement.install_options
  578. location_options = parse_distutils_args(install_options)
  579. if location_options:
  580. offenders.append(
  581. "{!r} from {}".format(
  582. format_options(location_options.keys()), requirement
  583. )
  584. )
  585. if options:
  586. location_options = parse_distutils_args(options)
  587. if location_options:
  588. offenders.append(
  589. "{!r} from command line".format(
  590. format_options(location_options.keys())
  591. )
  592. )
  593. if not offenders:
  594. return
  595. raise CommandError(
  596. "Location-changing options found in --install-option: {}."
  597. " This is unsupported, use pip-level options like --user,"
  598. " --prefix, --root, and --target instead.".format(
  599. "; ".join(offenders)
  600. )
  601. )
  602. def create_env_error_message(error, show_traceback, using_user_site):
  603. # type: (EnvironmentError, bool, bool) -> str
  604. """Format an error message for an EnvironmentError
  605. It may occur anytime during the execution of the install command.
  606. """
  607. parts = []
  608. # Mention the error if we are not going to show a traceback
  609. parts.append("Could not install packages due to an EnvironmentError")
  610. if not show_traceback:
  611. parts.append(": ")
  612. parts.append(str(error))
  613. else:
  614. parts.append(".")
  615. # Spilt the error indication from a helper message (if any)
  616. parts[-1] += "\n"
  617. # Suggest useful actions to the user:
  618. # (1) using user site-packages or (2) verifying the permissions
  619. if error.errno == errno.EACCES:
  620. user_option_part = "Consider using the `--user` option"
  621. permissions_part = "Check the permissions"
  622. if not using_user_site:
  623. parts.extend([
  624. user_option_part, " or ",
  625. permissions_part.lower(),
  626. ])
  627. else:
  628. parts.append(permissions_part)
  629. parts.append(".\n")
  630. return "".join(parts).strip() + "\n"