Path: blob/main/test/lib/python3.9/site-packages/pip/_internal/commands/install.py
4804 views
import errno1import operator2import os3import shutil4import site5from optparse import SUPPRESS_HELP, Values6from typing import Iterable, List, Optional78from pip._vendor.packaging.utils import canonicalize_name910from pip._internal.cache import WheelCache11from pip._internal.cli import cmdoptions12from pip._internal.cli.cmdoptions import make_target_python13from pip._internal.cli.req_command import (14RequirementCommand,15warn_if_run_as_root,16with_cleanup,17)18from pip._internal.cli.status_codes import ERROR, SUCCESS19from pip._internal.exceptions import CommandError, InstallationError20from pip._internal.locations import get_scheme21from pip._internal.metadata import get_environment22from pip._internal.models.format_control import FormatControl23from pip._internal.operations.build.build_tracker import get_build_tracker24from pip._internal.operations.check import ConflictDetails, check_install_conflicts25from pip._internal.req import install_given_reqs26from pip._internal.req.req_install import InstallRequirement27from pip._internal.utils.compat import WINDOWS28from pip._internal.utils.distutils_args import parse_distutils_args29from pip._internal.utils.filesystem import test_writable_dir30from pip._internal.utils.logging import getLogger31from pip._internal.utils.misc import (32ensure_dir,33get_pip_version,34protect_pip_from_modification_on_windows,35write_output,36)37from pip._internal.utils.temp_dir import TempDirectory38from pip._internal.utils.virtualenv import (39running_under_virtualenv,40virtualenv_no_global,41)42from pip._internal.wheel_builder import (43BinaryAllowedPredicate,44build,45should_build_for_install_command,46)4748logger = getLogger(__name__)495051def get_check_binary_allowed(format_control: FormatControl) -> BinaryAllowedPredicate:52def check_binary_allowed(req: InstallRequirement) -> bool:53canonical_name = canonicalize_name(req.name or "")54allowed_formats = format_control.get_allowed_formats(canonical_name)55return "binary" in allowed_formats5657return check_binary_allowed585960class InstallCommand(RequirementCommand):61"""62Install packages from:6364- PyPI (and other indexes) using requirement specifiers.65- VCS project urls.66- Local project directories.67- Local or remote source archives.6869pip also supports installing from "requirements files", which provide70an easy way to specify a whole environment to be installed.71"""7273usage = """74%prog [options] <requirement specifier> [package-index-options] ...75%prog [options] -r <requirements file> [package-index-options] ...76%prog [options] [-e] <vcs project url> ...77%prog [options] [-e] <local project path> ...78%prog [options] <archive url/path> ..."""7980def add_options(self) -> None:81self.cmd_opts.add_option(cmdoptions.requirements())82self.cmd_opts.add_option(cmdoptions.constraints())83self.cmd_opts.add_option(cmdoptions.no_deps())84self.cmd_opts.add_option(cmdoptions.pre())8586self.cmd_opts.add_option(cmdoptions.editable())87self.cmd_opts.add_option(88"-t",89"--target",90dest="target_dir",91metavar="dir",92default=None,93help=(94"Install packages into <dir>. "95"By default this will not replace existing files/folders in "96"<dir>. Use --upgrade to replace existing packages in <dir> "97"with new versions."98),99)100cmdoptions.add_target_python_options(self.cmd_opts)101102self.cmd_opts.add_option(103"--user",104dest="use_user_site",105action="store_true",106help=(107"Install to the Python user install directory for your "108"platform. Typically ~/.local/, or %APPDATA%\\Python on "109"Windows. (See the Python documentation for site.USER_BASE "110"for full details.)"111),112)113self.cmd_opts.add_option(114"--no-user",115dest="use_user_site",116action="store_false",117help=SUPPRESS_HELP,118)119self.cmd_opts.add_option(120"--root",121dest="root_path",122metavar="dir",123default=None,124help="Install everything relative to this alternate root directory.",125)126self.cmd_opts.add_option(127"--prefix",128dest="prefix_path",129metavar="dir",130default=None,131help=(132"Installation prefix where lib, bin and other top-level "133"folders are placed"134),135)136137self.cmd_opts.add_option(cmdoptions.src())138139self.cmd_opts.add_option(140"-U",141"--upgrade",142dest="upgrade",143action="store_true",144help=(145"Upgrade all specified packages to the newest available "146"version. The handling of dependencies depends on the "147"upgrade-strategy used."148),149)150151self.cmd_opts.add_option(152"--upgrade-strategy",153dest="upgrade_strategy",154default="only-if-needed",155choices=["only-if-needed", "eager"],156help=(157"Determines how dependency upgrading should be handled "158"[default: %default]. "159'"eager" - dependencies are upgraded regardless of '160"whether the currently installed version satisfies the "161"requirements of the upgraded package(s). "162'"only-if-needed" - are upgraded only when they do not '163"satisfy the requirements of the upgraded package(s)."164),165)166167self.cmd_opts.add_option(168"--force-reinstall",169dest="force_reinstall",170action="store_true",171help="Reinstall all packages even if they are already up-to-date.",172)173174self.cmd_opts.add_option(175"-I",176"--ignore-installed",177dest="ignore_installed",178action="store_true",179help=(180"Ignore the installed packages, overwriting them. "181"This can break your system if the existing package "182"is of a different version or was installed "183"with a different package manager!"184),185)186187self.cmd_opts.add_option(cmdoptions.ignore_requires_python())188self.cmd_opts.add_option(cmdoptions.no_build_isolation())189self.cmd_opts.add_option(cmdoptions.use_pep517())190self.cmd_opts.add_option(cmdoptions.no_use_pep517())191self.cmd_opts.add_option(cmdoptions.check_build_deps())192193self.cmd_opts.add_option(cmdoptions.config_settings())194self.cmd_opts.add_option(cmdoptions.install_options())195self.cmd_opts.add_option(cmdoptions.global_options())196197self.cmd_opts.add_option(198"--compile",199action="store_true",200dest="compile",201default=True,202help="Compile Python source files to bytecode",203)204205self.cmd_opts.add_option(206"--no-compile",207action="store_false",208dest="compile",209help="Do not compile Python source files to bytecode",210)211212self.cmd_opts.add_option(213"--no-warn-script-location",214action="store_false",215dest="warn_script_location",216default=True,217help="Do not warn when installing scripts outside PATH",218)219self.cmd_opts.add_option(220"--no-warn-conflicts",221action="store_false",222dest="warn_about_conflicts",223default=True,224help="Do not warn about broken dependencies",225)226self.cmd_opts.add_option(cmdoptions.no_binary())227self.cmd_opts.add_option(cmdoptions.only_binary())228self.cmd_opts.add_option(cmdoptions.prefer_binary())229self.cmd_opts.add_option(cmdoptions.require_hashes())230self.cmd_opts.add_option(cmdoptions.progress_bar())231self.cmd_opts.add_option(cmdoptions.root_user_action())232233index_opts = cmdoptions.make_option_group(234cmdoptions.index_group,235self.parser,236)237238self.parser.insert_option_group(0, index_opts)239self.parser.insert_option_group(0, self.cmd_opts)240241@with_cleanup242def run(self, options: Values, args: List[str]) -> int:243if options.use_user_site and options.target_dir is not None:244raise CommandError("Can not combine '--user' and '--target'")245246cmdoptions.check_install_build_global(options)247upgrade_strategy = "to-satisfy-only"248if options.upgrade:249upgrade_strategy = options.upgrade_strategy250251cmdoptions.check_dist_restriction(options, check_target=True)252253install_options = options.install_options or []254255logger.verbose("Using %s", get_pip_version())256options.use_user_site = decide_user_install(257options.use_user_site,258prefix_path=options.prefix_path,259target_dir=options.target_dir,260root_path=options.root_path,261isolated_mode=options.isolated_mode,262)263264target_temp_dir: Optional[TempDirectory] = None265target_temp_dir_path: Optional[str] = None266if options.target_dir:267options.ignore_installed = True268options.target_dir = os.path.abspath(options.target_dir)269if (270# fmt: off271os.path.exists(options.target_dir) and272not os.path.isdir(options.target_dir)273# fmt: on274):275raise CommandError(276"Target path exists but is not a directory, will not continue."277)278279# Create a target directory for using with the target option280target_temp_dir = TempDirectory(kind="target")281target_temp_dir_path = target_temp_dir.path282self.enter_context(target_temp_dir)283284global_options = options.global_options or []285286session = self.get_default_session(options)287288target_python = make_target_python(options)289finder = self._build_package_finder(290options=options,291session=session,292target_python=target_python,293ignore_requires_python=options.ignore_requires_python,294)295wheel_cache = WheelCache(options.cache_dir, options.format_control)296297build_tracker = self.enter_context(get_build_tracker())298299directory = TempDirectory(300delete=not options.no_clean,301kind="install",302globally_managed=True,303)304305try:306reqs = self.get_requirements(args, options, finder, session)307308# Only when installing is it permitted to use PEP 660.309# In other circumstances (pip wheel, pip download) we generate310# regular (i.e. non editable) metadata and wheels.311for req in reqs:312req.permit_editable_wheels = True313314reject_location_related_install_options(reqs, options.install_options)315316preparer = self.make_requirement_preparer(317temp_build_dir=directory,318options=options,319build_tracker=build_tracker,320session=session,321finder=finder,322use_user_site=options.use_user_site,323verbosity=self.verbosity,324)325resolver = self.make_resolver(326preparer=preparer,327finder=finder,328options=options,329wheel_cache=wheel_cache,330use_user_site=options.use_user_site,331ignore_installed=options.ignore_installed,332ignore_requires_python=options.ignore_requires_python,333force_reinstall=options.force_reinstall,334upgrade_strategy=upgrade_strategy,335use_pep517=options.use_pep517,336)337338self.trace_basic_info(finder)339340requirement_set = resolver.resolve(341reqs, check_supported_wheels=not options.target_dir342)343344try:345pip_req = requirement_set.get_requirement("pip")346except KeyError:347modifying_pip = False348else:349# If we're not replacing an already installed pip,350# we're not modifying it.351modifying_pip = pip_req.satisfied_by is None352protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)353354check_binary_allowed = get_check_binary_allowed(finder.format_control)355356reqs_to_build = [357r358for r in requirement_set.requirements.values()359if should_build_for_install_command(r, check_binary_allowed)360]361362_, build_failures = build(363reqs_to_build,364wheel_cache=wheel_cache,365verify=True,366build_options=[],367global_options=[],368)369370# If we're using PEP 517, we cannot do a legacy setup.py install371# so we fail here.372pep517_build_failure_names: List[str] = [373r.name for r in build_failures if r.use_pep517 # type: ignore374]375if pep517_build_failure_names:376raise InstallationError(377"Could not build wheels for {}, which is required to "378"install pyproject.toml-based projects".format(379", ".join(pep517_build_failure_names)380)381)382383# For now, we just warn about failures building legacy384# requirements, as we'll fall through to a setup.py install for385# those.386for r in build_failures:387if not r.use_pep517:388r.legacy_install_reason = 8368389390to_install = resolver.get_installation_order(requirement_set)391392# Check for conflicts in the package set we're installing.393conflicts: Optional[ConflictDetails] = None394should_warn_about_conflicts = (395not options.ignore_dependencies and options.warn_about_conflicts396)397if should_warn_about_conflicts:398conflicts = self._determine_conflicts(to_install)399400# Don't warn about script install locations if401# --target or --prefix has been specified402warn_script_location = options.warn_script_location403if options.target_dir or options.prefix_path:404warn_script_location = False405406installed = install_given_reqs(407to_install,408install_options,409global_options,410root=options.root_path,411home=target_temp_dir_path,412prefix=options.prefix_path,413warn_script_location=warn_script_location,414use_user_site=options.use_user_site,415pycompile=options.compile,416)417418lib_locations = get_lib_location_guesses(419user=options.use_user_site,420home=target_temp_dir_path,421root=options.root_path,422prefix=options.prefix_path,423isolated=options.isolated_mode,424)425env = get_environment(lib_locations)426427installed.sort(key=operator.attrgetter("name"))428items = []429for result in installed:430item = result.name431try:432installed_dist = env.get_distribution(item)433if installed_dist is not None:434item = f"{item}-{installed_dist.version}"435except Exception:436pass437items.append(item)438439if conflicts is not None:440self._warn_about_conflicts(441conflicts,442resolver_variant=self.determine_resolver_variant(options),443)444445installed_desc = " ".join(items)446if installed_desc:447write_output(448"Successfully installed %s",449installed_desc,450)451except OSError as error:452show_traceback = self.verbosity >= 1453454message = create_os_error_message(455error,456show_traceback,457options.use_user_site,458)459logger.error(message, exc_info=show_traceback) # noqa460461return ERROR462463if options.target_dir:464assert target_temp_dir465self._handle_target_dir(466options.target_dir, target_temp_dir, options.upgrade467)468if options.root_user_action == "warn":469warn_if_run_as_root()470return SUCCESS471472def _handle_target_dir(473self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool474) -> None:475ensure_dir(target_dir)476477# Checking both purelib and platlib directories for installed478# packages to be moved to target directory479lib_dir_list = []480481# Checking both purelib and platlib directories for installed482# packages to be moved to target directory483scheme = get_scheme("", home=target_temp_dir.path)484purelib_dir = scheme.purelib485platlib_dir = scheme.platlib486data_dir = scheme.data487488if os.path.exists(purelib_dir):489lib_dir_list.append(purelib_dir)490if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:491lib_dir_list.append(platlib_dir)492if os.path.exists(data_dir):493lib_dir_list.append(data_dir)494495for lib_dir in lib_dir_list:496for item in os.listdir(lib_dir):497if lib_dir == data_dir:498ddir = os.path.join(data_dir, item)499if any(s.startswith(ddir) for s in lib_dir_list[:-1]):500continue501target_item_dir = os.path.join(target_dir, item)502if os.path.exists(target_item_dir):503if not upgrade:504logger.warning(505"Target directory %s already exists. Specify "506"--upgrade to force replacement.",507target_item_dir,508)509continue510if os.path.islink(target_item_dir):511logger.warning(512"Target directory %s already exists and is "513"a link. pip will not automatically replace "514"links, please remove if replacement is "515"desired.",516target_item_dir,517)518continue519if os.path.isdir(target_item_dir):520shutil.rmtree(target_item_dir)521else:522os.remove(target_item_dir)523524shutil.move(os.path.join(lib_dir, item), target_item_dir)525526def _determine_conflicts(527self, to_install: List[InstallRequirement]528) -> Optional[ConflictDetails]:529try:530return check_install_conflicts(to_install)531except Exception:532logger.exception(533"Error while checking for conflicts. Please file an issue on "534"pip's issue tracker: https://github.com/pypa/pip/issues/new"535)536return None537538def _warn_about_conflicts(539self, conflict_details: ConflictDetails, resolver_variant: str540) -> None:541package_set, (missing, conflicting) = conflict_details542if not missing and not conflicting:543return544545parts: List[str] = []546if resolver_variant == "legacy":547parts.append(548"pip's legacy dependency resolver does not consider dependency "549"conflicts when selecting packages. This behaviour is the "550"source of the following dependency conflicts."551)552else:553assert resolver_variant == "2020-resolver"554parts.append(555"pip's dependency resolver does not currently take into account "556"all the packages that are installed. This behaviour is the "557"source of the following dependency conflicts."558)559560# NOTE: There is some duplication here, with commands/check.py561for project_name in missing:562version = package_set[project_name][0]563for dependency in missing[project_name]:564message = (565"{name} {version} requires {requirement}, "566"which is not installed."567).format(568name=project_name,569version=version,570requirement=dependency[1],571)572parts.append(message)573574for project_name in conflicting:575version = package_set[project_name][0]576for dep_name, dep_version, req in conflicting[project_name]:577message = (578"{name} {version} requires {requirement}, but {you} have "579"{dep_name} {dep_version} which is incompatible."580).format(581name=project_name,582version=version,583requirement=req,584dep_name=dep_name,585dep_version=dep_version,586you=("you" if resolver_variant == "2020-resolver" else "you'll"),587)588parts.append(message)589590logger.critical("\n".join(parts))591592593def get_lib_location_guesses(594user: bool = False,595home: Optional[str] = None,596root: Optional[str] = None,597isolated: bool = False,598prefix: Optional[str] = None,599) -> List[str]:600scheme = get_scheme(601"",602user=user,603home=home,604root=root,605isolated=isolated,606prefix=prefix,607)608return [scheme.purelib, scheme.platlib]609610611def site_packages_writable(root: Optional[str], isolated: bool) -> bool:612return all(613test_writable_dir(d)614for d in set(get_lib_location_guesses(root=root, isolated=isolated))615)616617618def decide_user_install(619use_user_site: Optional[bool],620prefix_path: Optional[str] = None,621target_dir: Optional[str] = None,622root_path: Optional[str] = None,623isolated_mode: bool = False,624) -> bool:625"""Determine whether to do a user install based on the input options.626627If use_user_site is False, no additional checks are done.628If use_user_site is True, it is checked for compatibility with other629options.630If use_user_site is None, the default behaviour depends on the environment,631which is provided by the other arguments.632"""633# In some cases (config from tox), use_user_site can be set to an integer634# rather than a bool, which 'use_user_site is False' wouldn't catch.635if (use_user_site is not None) and (not use_user_site):636logger.debug("Non-user install by explicit request")637return False638639if use_user_site:640if prefix_path:641raise CommandError(642"Can not combine '--user' and '--prefix' as they imply "643"different installation locations"644)645if virtualenv_no_global():646raise InstallationError(647"Can not perform a '--user' install. User site-packages "648"are not visible in this virtualenv."649)650logger.debug("User install by explicit request")651return True652653# If we are here, user installs have not been explicitly requested/avoided654assert use_user_site is None655656# user install incompatible with --prefix/--target657if prefix_path or target_dir:658logger.debug("Non-user install due to --prefix or --target option")659return False660661# If user installs are not enabled, choose a non-user install662if not site.ENABLE_USER_SITE:663logger.debug("Non-user install because user site-packages disabled")664return False665666# If we have permission for a non-user install, do that,667# otherwise do a user install.668if site_packages_writable(root=root_path, isolated=isolated_mode):669logger.debug("Non-user install because site-packages writeable")670return False671672logger.info(673"Defaulting to user installation because normal site-packages "674"is not writeable"675)676return True677678679def reject_location_related_install_options(680requirements: List[InstallRequirement], options: Optional[List[str]]681) -> None:682"""If any location-changing --install-option arguments were passed for683requirements or on the command-line, then show a deprecation warning.684"""685686def format_options(option_names: Iterable[str]) -> List[str]:687return ["--{}".format(name.replace("_", "-")) for name in option_names]688689offenders = []690691for requirement in requirements:692install_options = requirement.install_options693location_options = parse_distutils_args(install_options)694if location_options:695offenders.append(696"{!r} from {}".format(697format_options(location_options.keys()), requirement698)699)700701if options:702location_options = parse_distutils_args(options)703if location_options:704offenders.append(705"{!r} from command line".format(format_options(location_options.keys()))706)707708if not offenders:709return710711raise CommandError(712"Location-changing options found in --install-option: {}."713" This is unsupported, use pip-level options like --user,"714" --prefix, --root, and --target instead.".format("; ".join(offenders))715)716717718def create_os_error_message(719error: OSError, show_traceback: bool, using_user_site: bool720) -> str:721"""Format an error message for an OSError722723It may occur anytime during the execution of the install command.724"""725parts = []726727# Mention the error if we are not going to show a traceback728parts.append("Could not install packages due to an OSError")729if not show_traceback:730parts.append(": ")731parts.append(str(error))732else:733parts.append(".")734735# Spilt the error indication from a helper message (if any)736parts[-1] += "\n"737738# Suggest useful actions to the user:739# (1) using user site-packages or (2) verifying the permissions740if error.errno == errno.EACCES:741user_option_part = "Consider using the `--user` option"742permissions_part = "Check the permissions"743744if not running_under_virtualenv() and not using_user_site:745parts.extend(746[747user_option_part,748" or ",749permissions_part.lower(),750]751)752else:753parts.append(permissions_part)754parts.append(".\n")755756# Suggest the user to enable Long Paths if path length is757# more than 260758if (759WINDOWS760and error.errno == errno.ENOENT761and error.filename762and len(error.filename) > 260763):764parts.append(765"HINT: This error might have occurred since "766"this system does not have Windows Long Path "767"support enabled. You can find information on "768"how to enable this at "769"https://pip.pypa.io/warnings/enable-long-paths\n"770)771772return "".join(parts).strip() + "\n"773774775