install.py 30 KB

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