install.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. )
  42. from pip._internal.utils.compat import WINDOWS
  43. from pip._internal.utils.filesystem import test_writable_dir
  44. from pip._internal.utils.logging import getLogger
  45. from pip._internal.utils.misc import (
  46. check_externally_managed,
  47. ensure_dir,
  48. get_pip_version,
  49. protect_pip_from_modification_on_windows,
  50. warn_if_run_as_root,
  51. write_output,
  52. )
  53. from pip._internal.utils.temp_dir import TempDirectory
  54. from pip._internal.utils.virtualenv import (
  55. running_under_virtualenv,
  56. virtualenv_no_global,
  57. )
  58. from pip._internal.wheel_builder import build
  59. logger = getLogger(__name__)
  60. class InstallCommand(RequirementCommand):
  61. """
  62. Install packages from:
  63. - PyPI (and other indexes) using requirement specifiers.
  64. - VCS project urls.
  65. - Local project directories.
  66. - Local or remote source archives.
  67. pip also supports installing from "requirements files", which provide
  68. an easy way to specify a whole environment to be installed.
  69. """
  70. usage = """
  71. %prog [options] <requirement specifier> [package-index-options] ...
  72. %prog [options] -r <requirements file> [package-index-options] ...
  73. %prog [options] [-e] <vcs project url> ...
  74. %prog [options] [-e] <local project path> ...
  75. %prog [options] <archive url/path> ..."""
  76. def add_options(self) -> None:
  77. self.cmd_opts.add_option(cmdoptions.requirements())
  78. self.cmd_opts.add_option(cmdoptions.constraints())
  79. self.cmd_opts.add_option(cmdoptions.build_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.check_build_deps())
  196. self.cmd_opts.add_option(cmdoptions.override_externally_managed())
  197. self.cmd_opts.add_option(cmdoptions.config_settings())
  198. self.cmd_opts.add_option(
  199. "--compile",
  200. action="store_true",
  201. dest="compile",
  202. default=True,
  203. help="Compile Python source files to bytecode",
  204. )
  205. self.cmd_opts.add_option(
  206. "--no-compile",
  207. action="store_false",
  208. dest="compile",
  209. help="Do not compile Python source files to bytecode",
  210. )
  211. self.cmd_opts.add_option(
  212. "--no-warn-script-location",
  213. action="store_false",
  214. dest="warn_script_location",
  215. default=True,
  216. help="Do not warn when installing scripts outside PATH",
  217. )
  218. self.cmd_opts.add_option(
  219. "--no-warn-conflicts",
  220. action="store_false",
  221. dest="warn_about_conflicts",
  222. default=True,
  223. help="Do not warn about broken dependencies",
  224. )
  225. self.cmd_opts.add_option(cmdoptions.no_binary())
  226. self.cmd_opts.add_option(cmdoptions.only_binary())
  227. self.cmd_opts.add_option(cmdoptions.prefer_binary())
  228. self.cmd_opts.add_option(cmdoptions.require_hashes())
  229. self.cmd_opts.add_option(cmdoptions.progress_bar())
  230. self.cmd_opts.add_option(cmdoptions.root_user_action())
  231. index_opts = cmdoptions.make_option_group(
  232. cmdoptions.index_group,
  233. self.parser,
  234. )
  235. self.parser.insert_option_group(0, index_opts)
  236. self.parser.insert_option_group(0, self.cmd_opts)
  237. self.cmd_opts.add_option(
  238. "--report",
  239. dest="json_report_file",
  240. metavar="file",
  241. default=None,
  242. help=(
  243. "Generate a JSON file describing what pip did to install "
  244. "the provided requirements. "
  245. "Can be used in combination with --dry-run and --ignore-installed "
  246. "to 'resolve' the requirements. "
  247. "When - is used as file name it writes to stdout. "
  248. "When writing to stdout, please combine with the --quiet option "
  249. "to avoid mixing pip logging output with JSON output."
  250. ),
  251. )
  252. @with_cleanup
  253. def run(self, options: Values, args: list[str]) -> int:
  254. if options.use_user_site and options.target_dir is not None:
  255. raise CommandError("Can not combine '--user' and '--target'")
  256. # Check whether the environment we're installing into is externally
  257. # managed, as specified in PEP 668. Specifying --root, --target, or
  258. # --prefix disables the check, since there's no reliable way to locate
  259. # the EXTERNALLY-MANAGED file for those cases. An exception is also
  260. # made specifically for "--dry-run --report" for convenience.
  261. installing_into_current_environment = (
  262. not (options.dry_run and options.json_report_file)
  263. and options.root_path is None
  264. and options.target_dir is None
  265. and options.prefix_path is None
  266. )
  267. if (
  268. installing_into_current_environment
  269. and not options.override_externally_managed
  270. ):
  271. check_externally_managed()
  272. upgrade_strategy = "to-satisfy-only"
  273. if options.upgrade:
  274. upgrade_strategy = options.upgrade_strategy
  275. cmdoptions.check_build_constraints(options)
  276. cmdoptions.check_dist_restriction(options, check_target=True)
  277. logger.verbose("Using %s", get_pip_version())
  278. options.use_user_site = decide_user_install(
  279. options.use_user_site,
  280. prefix_path=options.prefix_path,
  281. target_dir=options.target_dir,
  282. root_path=options.root_path,
  283. isolated_mode=options.isolated_mode,
  284. )
  285. target_temp_dir: TempDirectory | None = None
  286. target_temp_dir_path: str | None = None
  287. if options.target_dir:
  288. options.ignore_installed = True
  289. options.target_dir = os.path.abspath(options.target_dir)
  290. if (
  291. # fmt: off
  292. os.path.exists(options.target_dir) and
  293. not os.path.isdir(options.target_dir)
  294. # fmt: on
  295. ):
  296. raise CommandError(
  297. "Target path exists but is not a directory, will not continue."
  298. )
  299. # Create a target directory for using with the target option
  300. target_temp_dir = TempDirectory(kind="target")
  301. target_temp_dir_path = target_temp_dir.path
  302. self.enter_context(target_temp_dir)
  303. session = self.get_default_session(options)
  304. target_python = make_target_python(options)
  305. finder = self._build_package_finder(
  306. options=options,
  307. session=session,
  308. target_python=target_python,
  309. ignore_requires_python=options.ignore_requires_python,
  310. )
  311. build_tracker = self.enter_context(get_build_tracker())
  312. directory = TempDirectory(
  313. delete=not options.no_clean,
  314. kind="install",
  315. globally_managed=True,
  316. )
  317. try:
  318. reqs = self.get_requirements(args, options, finder, session)
  319. wheel_cache = WheelCache(options.cache_dir)
  320. # Only when installing is it permitted to use PEP 660.
  321. # In other circumstances (pip wheel, pip download) we generate
  322. # regular (i.e. non editable) metadata and wheels.
  323. for req in reqs:
  324. req.permit_editable_wheels = True
  325. preparer = self.make_requirement_preparer(
  326. temp_build_dir=directory,
  327. options=options,
  328. build_tracker=build_tracker,
  329. session=session,
  330. finder=finder,
  331. use_user_site=options.use_user_site,
  332. verbosity=self.verbosity,
  333. )
  334. resolver = self.make_resolver(
  335. preparer=preparer,
  336. finder=finder,
  337. options=options,
  338. wheel_cache=wheel_cache,
  339. use_user_site=options.use_user_site,
  340. ignore_installed=options.ignore_installed,
  341. ignore_requires_python=options.ignore_requires_python,
  342. force_reinstall=options.force_reinstall,
  343. upgrade_strategy=upgrade_strategy,
  344. py_version_info=options.python_version,
  345. )
  346. self.trace_basic_info(finder)
  347. requirement_set = resolver.resolve(
  348. reqs, check_supported_wheels=not options.target_dir
  349. )
  350. if options.json_report_file:
  351. report = InstallationReport(requirement_set.requirements_to_install)
  352. if options.json_report_file == "-":
  353. print_json(data=report.to_dict())
  354. else:
  355. with open(options.json_report_file, "w", encoding="utf-8") as f:
  356. json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)
  357. if options.dry_run:
  358. would_install_items = sorted(
  359. (r.metadata["name"], r.metadata["version"])
  360. for r in requirement_set.requirements_to_install
  361. )
  362. if would_install_items:
  363. write_output(
  364. "Would install %s",
  365. " ".join("-".join(item) for item in would_install_items),
  366. )
  367. return SUCCESS
  368. # If there is any more preparation to do for the actual installation, do
  369. # so now. This includes actually downloading the files in the case that
  370. # we have been using PEP-658 metadata so far.
  371. preparer.prepare_linked_requirements_more(
  372. requirement_set.requirements.values()
  373. )
  374. try:
  375. pip_req = requirement_set.get_requirement("pip")
  376. except KeyError:
  377. modifying_pip = False
  378. else:
  379. # If we're not replacing an already installed pip,
  380. # we're not modifying it.
  381. modifying_pip = pip_req.satisfied_by is None
  382. protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)
  383. reqs_to_build = [
  384. r for r in requirement_set.requirements_to_install if not r.is_wheel
  385. ]
  386. _, build_failures = build(
  387. reqs_to_build,
  388. wheel_cache=wheel_cache,
  389. verify=True,
  390. )
  391. if build_failures:
  392. raise InstallWheelBuildError(build_failures)
  393. to_install = resolver.get_installation_order(requirement_set)
  394. # Check for conflicts in the package set we're installing.
  395. conflicts: ConflictDetails | None = None
  396. should_warn_about_conflicts = (
  397. not options.ignore_dependencies and options.warn_about_conflicts
  398. )
  399. if should_warn_about_conflicts:
  400. conflicts = self._determine_conflicts(to_install)
  401. # Don't warn about script install locations if
  402. # --target or --prefix has been specified
  403. warn_script_location = options.warn_script_location
  404. if options.target_dir or options.prefix_path:
  405. warn_script_location = False
  406. installed = install_given_reqs(
  407. to_install,
  408. root=options.root_path,
  409. home=target_temp_dir_path,
  410. prefix=options.prefix_path,
  411. warn_script_location=warn_script_location,
  412. use_user_site=options.use_user_site,
  413. pycompile=options.compile,
  414. progress_bar=options.progress_bar,
  415. )
  416. lib_locations = get_lib_location_guesses(
  417. user=options.use_user_site,
  418. home=target_temp_dir_path,
  419. root=options.root_path,
  420. prefix=options.prefix_path,
  421. isolated=options.isolated_mode,
  422. )
  423. env = get_environment(lib_locations)
  424. # Display a summary of installed packages, with extra care to
  425. # display a package name as it was requested by the user.
  426. installed.sort(key=operator.attrgetter("name"))
  427. summary = []
  428. installed_versions = {}
  429. for distribution in env.iter_all_distributions():
  430. installed_versions[distribution.canonical_name] = distribution.version
  431. for package in installed:
  432. display_name = package.name
  433. version = installed_versions.get(canonicalize_name(display_name), None)
  434. if version:
  435. text = f"{display_name}-{version}"
  436. else:
  437. text = display_name
  438. summary.append(text)
  439. if conflicts is not None:
  440. self._warn_about_conflicts(
  441. conflicts,
  442. resolver_variant=self.determine_resolver_variant(options),
  443. )
  444. installed_desc = " ".join(summary)
  445. if installed_desc:
  446. write_output(
  447. "Successfully installed %s",
  448. installed_desc,
  449. )
  450. except OSError as error:
  451. show_traceback = self.verbosity >= 1
  452. message = create_os_error_message(
  453. error,
  454. show_traceback,
  455. options.use_user_site,
  456. )
  457. logger.error(message, exc_info=show_traceback)
  458. return ERROR
  459. if options.target_dir:
  460. assert target_temp_dir
  461. self._handle_target_dir(
  462. options.target_dir, target_temp_dir, options.upgrade
  463. )
  464. if options.root_user_action == "warn":
  465. warn_if_run_as_root()
  466. return SUCCESS
  467. def _handle_target_dir(
  468. self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool
  469. ) -> None:
  470. ensure_dir(target_dir)
  471. # Checking both purelib and platlib directories for installed
  472. # packages to be moved to target directory
  473. lib_dir_list = []
  474. # Checking both purelib and platlib directories for installed
  475. # packages to be moved to target directory
  476. scheme = get_scheme("", home=target_temp_dir.path)
  477. purelib_dir = scheme.purelib
  478. platlib_dir = scheme.platlib
  479. data_dir = scheme.data
  480. if os.path.exists(purelib_dir):
  481. lib_dir_list.append(purelib_dir)
  482. if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:
  483. lib_dir_list.append(platlib_dir)
  484. if os.path.exists(data_dir):
  485. lib_dir_list.append(data_dir)
  486. for lib_dir in lib_dir_list:
  487. for item in os.listdir(lib_dir):
  488. if lib_dir == data_dir:
  489. ddir = os.path.join(data_dir, item)
  490. if any(s.startswith(ddir) for s in lib_dir_list[:-1]):
  491. continue
  492. target_item_dir = os.path.join(target_dir, item)
  493. if os.path.exists(target_item_dir):
  494. if not upgrade:
  495. logger.warning(
  496. "Target directory %s already exists. Specify "
  497. "--upgrade to force replacement.",
  498. target_item_dir,
  499. )
  500. continue
  501. if os.path.islink(target_item_dir):
  502. logger.warning(
  503. "Target directory %s already exists and is "
  504. "a link. pip will not automatically replace "
  505. "links, please remove if replacement is "
  506. "desired.",
  507. target_item_dir,
  508. )
  509. continue
  510. if os.path.isdir(target_item_dir):
  511. shutil.rmtree(target_item_dir)
  512. else:
  513. os.remove(target_item_dir)
  514. shutil.move(os.path.join(lib_dir, item), target_item_dir)
  515. def _determine_conflicts(
  516. self, to_install: list[InstallRequirement]
  517. ) -> ConflictDetails | None:
  518. try:
  519. return check_install_conflicts(to_install)
  520. except Exception:
  521. logger.exception(
  522. "Error while checking for conflicts. Please file an issue on "
  523. "pip's issue tracker: https://github.com/pypa/pip/issues/new"
  524. )
  525. return None
  526. def _warn_about_conflicts(
  527. self, conflict_details: ConflictDetails, resolver_variant: str
  528. ) -> None:
  529. package_set, (missing, conflicting) = conflict_details
  530. if not missing and not conflicting:
  531. return
  532. parts: list[str] = []
  533. if resolver_variant == "legacy":
  534. parts.append(
  535. "pip's legacy dependency resolver does not consider dependency "
  536. "conflicts when selecting packages. This behaviour is the "
  537. "source of the following dependency conflicts."
  538. )
  539. else:
  540. assert resolver_variant == "resolvelib"
  541. parts.append(
  542. "pip's dependency resolver does not currently take into account "
  543. "all the packages that are installed. This behaviour is the "
  544. "source of the following dependency conflicts."
  545. )
  546. # NOTE: There is some duplication here, with commands/check.py
  547. for project_name in missing:
  548. version = package_set[project_name][0]
  549. for dependency in missing[project_name]:
  550. message = (
  551. f"{project_name} {version} requires {dependency[1]}, "
  552. "which is not installed."
  553. )
  554. parts.append(message)
  555. for project_name in conflicting:
  556. version = package_set[project_name][0]
  557. for dep_name, dep_version, req in conflicting[project_name]:
  558. message = (
  559. "{name} {version} requires {requirement}, but {you} have "
  560. "{dep_name} {dep_version} which is incompatible."
  561. ).format(
  562. name=project_name,
  563. version=version,
  564. requirement=req,
  565. dep_name=dep_name,
  566. dep_version=dep_version,
  567. you=("you" if resolver_variant == "resolvelib" else "you'll"),
  568. )
  569. parts.append(message)
  570. logger.critical("\n".join(parts))
  571. def get_lib_location_guesses(
  572. user: bool = False,
  573. home: str | None = None,
  574. root: str | None = None,
  575. isolated: bool = False,
  576. prefix: str | None = None,
  577. ) -> list[str]:
  578. scheme = get_scheme(
  579. "",
  580. user=user,
  581. home=home,
  582. root=root,
  583. isolated=isolated,
  584. prefix=prefix,
  585. )
  586. return [scheme.purelib, scheme.platlib]
  587. def site_packages_writable(root: str | None, isolated: bool) -> bool:
  588. return all(
  589. test_writable_dir(d)
  590. for d in set(get_lib_location_guesses(root=root, isolated=isolated))
  591. )
  592. def decide_user_install(
  593. use_user_site: bool | None,
  594. prefix_path: str | None = None,
  595. target_dir: str | None = None,
  596. root_path: str | None = None,
  597. isolated_mode: bool = False,
  598. ) -> bool:
  599. """Determine whether to do a user install based on the input options.
  600. If use_user_site is False, no additional checks are done.
  601. If use_user_site is True, it is checked for compatibility with other
  602. options.
  603. If use_user_site is None, the default behaviour depends on the environment,
  604. which is provided by the other arguments.
  605. """
  606. # In some cases (config from tox), use_user_site can be set to an integer
  607. # rather than a bool, which 'use_user_site is False' wouldn't catch.
  608. if (use_user_site is not None) and (not use_user_site):
  609. logger.debug("Non-user install by explicit request")
  610. return False
  611. # If we have been asked for a user install explicitly, check compatibility.
  612. if use_user_site:
  613. if prefix_path:
  614. raise CommandError(
  615. "Can not combine '--user' and '--prefix' as they imply "
  616. "different installation locations"
  617. )
  618. if virtualenv_no_global():
  619. raise InstallationError(
  620. "Can not perform a '--user' install. User site-packages "
  621. "are not visible in this virtualenv."
  622. )
  623. # Catch all remaining cases which honour the site.ENABLE_USER_SITE
  624. # value, such as a plain Python installation (e.g. no virtualenv).
  625. if not site.ENABLE_USER_SITE:
  626. raise InstallationError(
  627. "Can not perform a '--user' install. User site-packages "
  628. "are disabled for this Python."
  629. )
  630. logger.debug("User install by explicit request")
  631. return True
  632. # If we are here, user installs have not been explicitly requested/avoided
  633. assert use_user_site is None
  634. # user install incompatible with --prefix/--target
  635. if prefix_path or target_dir:
  636. logger.debug("Non-user install due to --prefix or --target option")
  637. return False
  638. # If user installs are not enabled, choose a non-user install
  639. if not site.ENABLE_USER_SITE:
  640. logger.debug("Non-user install because user site-packages disabled")
  641. return False
  642. # If we have permission for a non-user install, do that,
  643. # otherwise do a user install.
  644. if site_packages_writable(root=root_path, isolated=isolated_mode):
  645. logger.debug("Non-user install because site-packages writeable")
  646. return False
  647. logger.info(
  648. "Defaulting to user installation because normal site-packages "
  649. "is not writeable"
  650. )
  651. return True
  652. def create_os_error_message(
  653. error: OSError, show_traceback: bool, using_user_site: bool
  654. ) -> str:
  655. """Format an error message for an OSError
  656. It may occur anytime during the execution of the install command.
  657. """
  658. parts = []
  659. # Mention the error if we are not going to show a traceback
  660. parts.append("Could not install packages due to an OSError")
  661. if not show_traceback:
  662. parts.append(": ")
  663. parts.append(str(error))
  664. else:
  665. parts.append(".")
  666. # Spilt the error indication from a helper message (if any)
  667. parts[-1] += "\n"
  668. # Suggest useful actions to the user:
  669. # (1) using user site-packages or (2) verifying the permissions
  670. if error.errno == errno.EACCES:
  671. user_option_part = "Consider using the `--user` option"
  672. permissions_part = "Check the permissions"
  673. if not running_under_virtualenv() and not using_user_site:
  674. parts.extend(
  675. [
  676. user_option_part,
  677. " or ",
  678. permissions_part.lower(),
  679. ]
  680. )
  681. else:
  682. parts.append(permissions_part)
  683. parts.append(".\n")
  684. # Suggest to check "pip config debug" in case of invalid proxy
  685. if type(error) is InvalidProxyURL:
  686. parts.append(
  687. 'Consider checking your local proxy configuration with "pip config debug"'
  688. )
  689. parts.append(".\n")
  690. # On Windows, errors like EINVAL or ENOENT may occur
  691. # if a file or folder name exceeds 255 characters,
  692. # or if the full path exceeds 260 characters and long path support isn't enabled.
  693. # This condition checks for such cases and adds a hint to the error output.
  694. if WINDOWS and error.errno in (errno.EINVAL, errno.ENOENT) and error.filename:
  695. if any(len(part) > 255 for part in Path(error.filename).parts):
  696. parts.append(
  697. "HINT: This error might be caused by a file or folder name exceeding "
  698. "255 characters, which is a Windows limitation even if long paths "
  699. "are enabled.\n "
  700. )
  701. if len(error.filename) > 260:
  702. parts.append(
  703. "HINT: This error might have occurred since "
  704. "this system does not have Windows Long Path "
  705. "support enabled. You can find information on "
  706. "how to enable this at "
  707. "https://pip.pypa.io/warnings/enable-long-paths\n"
  708. )
  709. return "".join(parts).strip() + "\n"