install.py 28 KB

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