install.py 29 KB

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