install.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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.packaging.utils import canonicalize_name
  10. from pip._vendor.rich import print_json
  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 (
  15. RequirementCommand,
  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. warn_if_run_as_root,
  39. write_output,
  40. )
  41. from pip._internal.utils.temp_dir import TempDirectory
  42. from pip._internal.utils.virtualenv import (
  43. running_under_virtualenv,
  44. virtualenv_no_global,
  45. )
  46. from pip._internal.wheel_builder import build, should_build_for_install_command
  47. logger = getLogger(__name__)
  48. class InstallCommand(RequirementCommand):
  49. """
  50. Install packages from:
  51. - PyPI (and other indexes) using requirement specifiers.
  52. - VCS project urls.
  53. - Local project directories.
  54. - Local or remote source archives.
  55. pip also supports installing from "requirements files", which provide
  56. an easy way to specify a whole environment to be installed.
  57. """
  58. usage = """
  59. %prog [options] <requirement specifier> [package-index-options] ...
  60. %prog [options] -r <requirements file> [package-index-options] ...
  61. %prog [options] [-e] <vcs project url> ...
  62. %prog [options] [-e] <local project path> ...
  63. %prog [options] <archive url/path> ..."""
  64. def add_options(self) -> None:
  65. self.cmd_opts.add_option(cmdoptions.requirements())
  66. self.cmd_opts.add_option(cmdoptions.constraints())
  67. self.cmd_opts.add_option(cmdoptions.no_deps())
  68. self.cmd_opts.add_option(cmdoptions.pre())
  69. self.cmd_opts.add_option(cmdoptions.editable())
  70. self.cmd_opts.add_option(
  71. "--dry-run",
  72. action="store_true",
  73. dest="dry_run",
  74. default=False,
  75. help=(
  76. "Don't actually install anything, just print what would be. "
  77. "Can be used in combination with --ignore-installed "
  78. "to 'resolve' the requirements."
  79. ),
  80. )
  81. self.cmd_opts.add_option(
  82. "-t",
  83. "--target",
  84. dest="target_dir",
  85. metavar="dir",
  86. default=None,
  87. help=(
  88. "Install packages into <dir>. "
  89. "By default this will not replace existing files/folders in "
  90. "<dir>. Use --upgrade to replace existing packages in <dir> "
  91. "with new versions."
  92. ),
  93. )
  94. cmdoptions.add_target_python_options(self.cmd_opts)
  95. self.cmd_opts.add_option(
  96. "--user",
  97. dest="use_user_site",
  98. action="store_true",
  99. help=(
  100. "Install to the Python user install directory for your "
  101. "platform. Typically ~/.local/, or %APPDATA%\\Python on "
  102. "Windows. (See the Python documentation for site.USER_BASE "
  103. "for full details.)"
  104. ),
  105. )
  106. self.cmd_opts.add_option(
  107. "--no-user",
  108. dest="use_user_site",
  109. action="store_false",
  110. help=SUPPRESS_HELP,
  111. )
  112. self.cmd_opts.add_option(
  113. "--root",
  114. dest="root_path",
  115. metavar="dir",
  116. default=None,
  117. help="Install everything relative to this alternate root directory.",
  118. )
  119. self.cmd_opts.add_option(
  120. "--prefix",
  121. dest="prefix_path",
  122. metavar="dir",
  123. default=None,
  124. help=(
  125. "Installation prefix where lib, bin and other top-level "
  126. "folders are placed. Note that the resulting installation may "
  127. "contain scripts and other resources which reference the "
  128. "Python interpreter of pip, and not that of ``--prefix``. "
  129. "See also the ``--python`` option if the intention is to "
  130. "install packages into another (possibly pip-free) "
  131. "environment."
  132. ),
  133. )
  134. self.cmd_opts.add_option(cmdoptions.src())
  135. self.cmd_opts.add_option(
  136. "-U",
  137. "--upgrade",
  138. dest="upgrade",
  139. action="store_true",
  140. help=(
  141. "Upgrade all specified packages to the newest available "
  142. "version. The handling of dependencies depends on the "
  143. "upgrade-strategy used."
  144. ),
  145. )
  146. self.cmd_opts.add_option(
  147. "--upgrade-strategy",
  148. dest="upgrade_strategy",
  149. default="only-if-needed",
  150. choices=["only-if-needed", "eager"],
  151. help=(
  152. "Determines how dependency upgrading should be handled "
  153. "[default: %default]. "
  154. '"eager" - dependencies are upgraded regardless of '
  155. "whether the currently installed version satisfies the "
  156. "requirements of the upgraded package(s). "
  157. '"only-if-needed" - are upgraded only when they do not '
  158. "satisfy the requirements of the upgraded package(s)."
  159. ),
  160. )
  161. self.cmd_opts.add_option(
  162. "--force-reinstall",
  163. dest="force_reinstall",
  164. action="store_true",
  165. help="Reinstall all packages even if they are already up-to-date.",
  166. )
  167. self.cmd_opts.add_option(
  168. "-I",
  169. "--ignore-installed",
  170. dest="ignore_installed",
  171. action="store_true",
  172. help=(
  173. "Ignore the installed packages, overwriting them. "
  174. "This can break your system if the existing package "
  175. "is of a different version or was installed "
  176. "with a different package manager!"
  177. ),
  178. )
  179. self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
  180. self.cmd_opts.add_option(cmdoptions.no_build_isolation())
  181. self.cmd_opts.add_option(cmdoptions.use_pep517())
  182. self.cmd_opts.add_option(cmdoptions.no_use_pep517())
  183. self.cmd_opts.add_option(cmdoptions.check_build_deps())
  184. self.cmd_opts.add_option(cmdoptions.override_externally_managed())
  185. self.cmd_opts.add_option(cmdoptions.config_settings())
  186. self.cmd_opts.add_option(cmdoptions.global_options())
  187. self.cmd_opts.add_option(
  188. "--compile",
  189. action="store_true",
  190. dest="compile",
  191. default=True,
  192. help="Compile Python source files to bytecode",
  193. )
  194. self.cmd_opts.add_option(
  195. "--no-compile",
  196. action="store_false",
  197. dest="compile",
  198. help="Do not compile Python source files to bytecode",
  199. )
  200. self.cmd_opts.add_option(
  201. "--no-warn-script-location",
  202. action="store_false",
  203. dest="warn_script_location",
  204. default=True,
  205. help="Do not warn when installing scripts outside PATH",
  206. )
  207. self.cmd_opts.add_option(
  208. "--no-warn-conflicts",
  209. action="store_false",
  210. dest="warn_about_conflicts",
  211. default=True,
  212. help="Do not warn about broken dependencies",
  213. )
  214. self.cmd_opts.add_option(cmdoptions.no_binary())
  215. self.cmd_opts.add_option(cmdoptions.only_binary())
  216. self.cmd_opts.add_option(cmdoptions.prefer_binary())
  217. self.cmd_opts.add_option(cmdoptions.require_hashes())
  218. self.cmd_opts.add_option(cmdoptions.progress_bar())
  219. self.cmd_opts.add_option(cmdoptions.root_user_action())
  220. index_opts = cmdoptions.make_option_group(
  221. cmdoptions.index_group,
  222. self.parser,
  223. )
  224. self.parser.insert_option_group(0, index_opts)
  225. self.parser.insert_option_group(0, self.cmd_opts)
  226. self.cmd_opts.add_option(
  227. "--report",
  228. dest="json_report_file",
  229. metavar="file",
  230. default=None,
  231. help=(
  232. "Generate a JSON file describing what pip did to install "
  233. "the provided requirements. "
  234. "Can be used in combination with --dry-run and --ignore-installed "
  235. "to 'resolve' the requirements. "
  236. "When - is used as file name it writes to stdout. "
  237. "When writing to stdout, please combine with the --quiet option "
  238. "to avoid mixing pip logging output with JSON output."
  239. ),
  240. )
  241. @with_cleanup
  242. def run(self, options: Values, args: List[str]) -> int:
  243. if options.use_user_site and options.target_dir is not None:
  244. raise CommandError("Can not combine '--user' and '--target'")
  245. # Check whether the environment we're installing into is externally
  246. # managed, as specified in PEP 668. Specifying --root, --target, or
  247. # --prefix disables the check, since there's no reliable way to locate
  248. # the EXTERNALLY-MANAGED file for those cases. An exception is also
  249. # made specifically for "--dry-run --report" for convenience.
  250. installing_into_current_environment = (
  251. not (options.dry_run and options.json_report_file)
  252. and options.root_path is None
  253. and options.target_dir is None
  254. and options.prefix_path is None
  255. )
  256. if (
  257. installing_into_current_environment
  258. and not options.override_externally_managed
  259. ):
  260. check_externally_managed()
  261. upgrade_strategy = "to-satisfy-only"
  262. if options.upgrade:
  263. upgrade_strategy = options.upgrade_strategy
  264. cmdoptions.check_dist_restriction(options, check_target=True)
  265. logger.verbose("Using %s", get_pip_version())
  266. options.use_user_site = decide_user_install(
  267. options.use_user_site,
  268. prefix_path=options.prefix_path,
  269. target_dir=options.target_dir,
  270. root_path=options.root_path,
  271. isolated_mode=options.isolated_mode,
  272. )
  273. target_temp_dir: Optional[TempDirectory] = None
  274. target_temp_dir_path: Optional[str] = None
  275. if options.target_dir:
  276. options.ignore_installed = True
  277. options.target_dir = os.path.abspath(options.target_dir)
  278. if (
  279. # fmt: off
  280. os.path.exists(options.target_dir) and
  281. not os.path.isdir(options.target_dir)
  282. # fmt: on
  283. ):
  284. raise CommandError(
  285. "Target path exists but is not a directory, will not continue."
  286. )
  287. # Create a target directory for using with the target option
  288. target_temp_dir = TempDirectory(kind="target")
  289. target_temp_dir_path = target_temp_dir.path
  290. self.enter_context(target_temp_dir)
  291. global_options = options.global_options or []
  292. session = self.get_default_session(options)
  293. target_python = make_target_python(options)
  294. finder = self._build_package_finder(
  295. options=options,
  296. session=session,
  297. target_python=target_python,
  298. ignore_requires_python=options.ignore_requires_python,
  299. )
  300. build_tracker = self.enter_context(get_build_tracker())
  301. directory = TempDirectory(
  302. delete=not options.no_clean,
  303. kind="install",
  304. globally_managed=True,
  305. )
  306. try:
  307. reqs = self.get_requirements(args, options, finder, session)
  308. check_legacy_setup_py_options(options, reqs)
  309. wheel_cache = WheelCache(options.cache_dir)
  310. # Only when installing is it permitted to use PEP 660.
  311. # In other circumstances (pip wheel, pip download) we generate
  312. # regular (i.e. non editable) metadata and wheels.
  313. for req in reqs:
  314. req.permit_editable_wheels = True
  315. preparer = self.make_requirement_preparer(
  316. temp_build_dir=directory,
  317. options=options,
  318. build_tracker=build_tracker,
  319. session=session,
  320. finder=finder,
  321. use_user_site=options.use_user_site,
  322. verbosity=self.verbosity,
  323. )
  324. resolver = self.make_resolver(
  325. preparer=preparer,
  326. finder=finder,
  327. options=options,
  328. wheel_cache=wheel_cache,
  329. use_user_site=options.use_user_site,
  330. ignore_installed=options.ignore_installed,
  331. ignore_requires_python=options.ignore_requires_python,
  332. force_reinstall=options.force_reinstall,
  333. upgrade_strategy=upgrade_strategy,
  334. use_pep517=options.use_pep517,
  335. py_version_info=options.python_version,
  336. )
  337. self.trace_basic_info(finder)
  338. requirement_set = resolver.resolve(
  339. reqs, check_supported_wheels=not options.target_dir
  340. )
  341. if options.json_report_file:
  342. report = InstallationReport(requirement_set.requirements_to_install)
  343. if options.json_report_file == "-":
  344. print_json(data=report.to_dict())
  345. else:
  346. with open(options.json_report_file, "w", encoding="utf-8") as f:
  347. json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)
  348. if options.dry_run:
  349. would_install_items = sorted(
  350. (r.metadata["name"], r.metadata["version"])
  351. for r in requirement_set.requirements_to_install
  352. )
  353. if would_install_items:
  354. write_output(
  355. "Would install %s",
  356. " ".join("-".join(item) for item in would_install_items),
  357. )
  358. return SUCCESS
  359. try:
  360. pip_req = requirement_set.get_requirement("pip")
  361. except KeyError:
  362. modifying_pip = False
  363. else:
  364. # If we're not replacing an already installed pip,
  365. # we're not modifying it.
  366. modifying_pip = pip_req.satisfied_by is None
  367. if modifying_pip:
  368. # Eagerly import this module to avoid crashes. Otherwise, this
  369. # module would be imported *after* pip was replaced, resulting in
  370. # crashes if the new self_outdated_check module was incompatible
  371. # with the rest of pip that's already imported.
  372. import pip._internal.self_outdated_check # noqa: F401
  373. protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)
  374. reqs_to_build = [
  375. r
  376. for r in requirement_set.requirements.values()
  377. if should_build_for_install_command(r)
  378. ]
  379. _, build_failures = build(
  380. reqs_to_build,
  381. wheel_cache=wheel_cache,
  382. verify=True,
  383. build_options=[],
  384. global_options=global_options,
  385. )
  386. if build_failures:
  387. raise InstallationError(
  388. "ERROR: Failed to build installable wheels for some "
  389. "pyproject.toml based projects ({})".format(
  390. ", ".join(r.name for r in build_failures) # type: ignore
  391. )
  392. )
  393. to_install = resolver.get_installation_order(requirement_set)
  394. # Check for conflicts in the package set we're installing.
  395. conflicts: Optional[ConflictDetails] = 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. global_options,
  409. root=options.root_path,
  410. home=target_temp_dir_path,
  411. prefix=options.prefix_path,
  412. warn_script_location=warn_script_location,
  413. use_user_site=options.use_user_site,
  414. pycompile=options.compile,
  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. ) -> Optional[ConflictDetails]:
  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: Optional[str] = None,
  574. root: Optional[str] = None,
  575. isolated: bool = False,
  576. prefix: Optional[str] = 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: Optional[str], 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: Optional[bool],
  594. prefix_path: Optional[str] = None,
  595. target_dir: Optional[str] = None,
  596. root_path: Optional[str] = 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 use_user_site:
  612. if prefix_path:
  613. raise CommandError(
  614. "Can not combine '--user' and '--prefix' as they imply "
  615. "different installation locations"
  616. )
  617. if virtualenv_no_global():
  618. raise InstallationError(
  619. "Can not perform a '--user' install. User site-packages "
  620. "are not visible in this virtualenv."
  621. )
  622. logger.debug("User install by explicit request")
  623. return True
  624. # If we are here, user installs have not been explicitly requested/avoided
  625. assert use_user_site is None
  626. # user install incompatible with --prefix/--target
  627. if prefix_path or target_dir:
  628. logger.debug("Non-user install due to --prefix or --target option")
  629. return False
  630. # If user installs are not enabled, choose a non-user install
  631. if not site.ENABLE_USER_SITE:
  632. logger.debug("Non-user install because user site-packages disabled")
  633. return False
  634. # If we have permission for a non-user install, do that,
  635. # otherwise do a user install.
  636. if site_packages_writable(root=root_path, isolated=isolated_mode):
  637. logger.debug("Non-user install because site-packages writeable")
  638. return False
  639. logger.info(
  640. "Defaulting to user installation because normal site-packages "
  641. "is not writeable"
  642. )
  643. return True
  644. def create_os_error_message(
  645. error: OSError, show_traceback: bool, using_user_site: bool
  646. ) -> str:
  647. """Format an error message for an OSError
  648. It may occur anytime during the execution of the install command.
  649. """
  650. parts = []
  651. # Mention the error if we are not going to show a traceback
  652. parts.append("Could not install packages due to an OSError")
  653. if not show_traceback:
  654. parts.append(": ")
  655. parts.append(str(error))
  656. else:
  657. parts.append(".")
  658. # Spilt the error indication from a helper message (if any)
  659. parts[-1] += "\n"
  660. # Suggest useful actions to the user:
  661. # (1) using user site-packages or (2) verifying the permissions
  662. if error.errno == errno.EACCES:
  663. user_option_part = "Consider using the `--user` option"
  664. permissions_part = "Check the permissions"
  665. if not running_under_virtualenv() and not using_user_site:
  666. parts.extend(
  667. [
  668. user_option_part,
  669. " or ",
  670. permissions_part.lower(),
  671. ]
  672. )
  673. else:
  674. parts.append(permissions_part)
  675. parts.append(".\n")
  676. # Suggest the user to enable Long Paths if path length is
  677. # more than 260
  678. if (
  679. WINDOWS
  680. and error.errno == errno.ENOENT
  681. and error.filename
  682. and len(error.filename) > 260
  683. ):
  684. parts.append(
  685. "HINT: This error might have occurred since "
  686. "this system does not have Windows Long Path "
  687. "support enabled. You can find information on "
  688. "how to enable this at "
  689. "https://pip.pypa.io/warnings/enable-long-paths\n"
  690. )
  691. return "".join(parts).strip() + "\n"