install.py 27 KB

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