Path: blob/master/venv/Lib/site-packages/pip/_internal/commands/install.py
811 views
# The following comment should be removed at some point in the future.1# It's included for now because without it InstallCommand.run() has a2# couple errors where we have to know req.name is str rather than3# Optional[str] for the InstallRequirement req.4# mypy: strict-optional=False5# mypy: disallow-untyped-defs=False67from __future__ import absolute_import89import errno10import logging11import operator12import os13import shutil14import site15from optparse import SUPPRESS_HELP1617from pip._vendor import pkg_resources18from pip._vendor.packaging.utils import canonicalize_name1920from pip._internal.cache import WheelCache21from pip._internal.cli import cmdoptions22from pip._internal.cli.cmdoptions import make_target_python23from pip._internal.cli.req_command import RequirementCommand, with_cleanup24from pip._internal.cli.status_codes import ERROR, SUCCESS25from pip._internal.exceptions import CommandError, InstallationError26from pip._internal.locations import distutils_scheme27from pip._internal.operations.check import check_install_conflicts28from pip._internal.req import install_given_reqs29from pip._internal.req.req_tracker import get_requirement_tracker30from pip._internal.utils.deprecation import deprecated31from pip._internal.utils.distutils_args import parse_distutils_args32from pip._internal.utils.filesystem import test_writable_dir33from pip._internal.utils.misc import (34ensure_dir,35get_installed_version,36protect_pip_from_modification_on_windows,37write_output,38)39from pip._internal.utils.temp_dir import TempDirectory40from pip._internal.utils.typing import MYPY_CHECK_RUNNING41from pip._internal.utils.virtualenv import virtualenv_no_global42from pip._internal.wheel_builder import build, should_build_for_install_command4344if MYPY_CHECK_RUNNING:45from optparse import Values46from typing import Any, Iterable, List, Optional4748from pip._internal.models.format_control import FormatControl49from pip._internal.req.req_install import InstallRequirement50from pip._internal.wheel_builder import BinaryAllowedPredicate515253logger = logging.getLogger(__name__)545556def get_check_binary_allowed(format_control):57# type: (FormatControl) -> BinaryAllowedPredicate58def check_binary_allowed(req):59# type: (InstallRequirement) -> bool60if req.use_pep517:61return True62canonical_name = canonicalize_name(req.name)63allowed_formats = format_control.get_allowed_formats(canonical_name)64return "binary" in allowed_formats6566return check_binary_allowed676869class InstallCommand(RequirementCommand):70"""71Install packages from:7273- PyPI (and other indexes) using requirement specifiers.74- VCS project urls.75- Local project directories.76- Local or remote source archives.7778pip also supports installing from "requirements files", which provide79an easy way to specify a whole environment to be installed.80"""8182usage = """83%prog [options] <requirement specifier> [package-index-options] ...84%prog [options] -r <requirements file> [package-index-options] ...85%prog [options] [-e] <vcs project url> ...86%prog [options] [-e] <local project path> ...87%prog [options] <archive url/path> ..."""8889def __init__(self, *args, **kw):90super(InstallCommand, self).__init__(*args, **kw)9192cmd_opts = self.cmd_opts9394cmd_opts.add_option(cmdoptions.requirements())95cmd_opts.add_option(cmdoptions.constraints())96cmd_opts.add_option(cmdoptions.no_deps())97cmd_opts.add_option(cmdoptions.pre())9899cmd_opts.add_option(cmdoptions.editable())100cmd_opts.add_option(101'-t', '--target',102dest='target_dir',103metavar='dir',104default=None,105help='Install packages into <dir>. '106'By default this will not replace existing files/folders in '107'<dir>. Use --upgrade to replace existing packages in <dir> '108'with new versions.'109)110cmdoptions.add_target_python_options(cmd_opts)111112cmd_opts.add_option(113'--user',114dest='use_user_site',115action='store_true',116help="Install to the Python user install directory for your "117"platform. Typically ~/.local/, or %APPDATA%\\Python on "118"Windows. (See the Python documentation for site.USER_BASE "119"for full details.)")120cmd_opts.add_option(121'--no-user',122dest='use_user_site',123action='store_false',124help=SUPPRESS_HELP)125cmd_opts.add_option(126'--root',127dest='root_path',128metavar='dir',129default=None,130help="Install everything relative to this alternate root "131"directory.")132cmd_opts.add_option(133'--prefix',134dest='prefix_path',135metavar='dir',136default=None,137help="Installation prefix where lib, bin and other top-level "138"folders are placed")139140cmd_opts.add_option(cmdoptions.build_dir())141142cmd_opts.add_option(cmdoptions.src())143144cmd_opts.add_option(145'-U', '--upgrade',146dest='upgrade',147action='store_true',148help='Upgrade all specified packages to the newest available '149'version. The handling of dependencies depends on the '150'upgrade-strategy used.'151)152153cmd_opts.add_option(154'--upgrade-strategy',155dest='upgrade_strategy',156default='only-if-needed',157choices=['only-if-needed', 'eager'],158help='Determines how dependency upgrading should be handled '159'[default: %default]. '160'"eager" - dependencies are upgraded regardless of '161'whether the currently installed version satisfies the '162'requirements of the upgraded package(s). '163'"only-if-needed" - are upgraded only when they do not '164'satisfy the requirements of the upgraded package(s).'165)166167cmd_opts.add_option(168'--force-reinstall',169dest='force_reinstall',170action='store_true',171help='Reinstall all packages even if they are already '172'up-to-date.')173174cmd_opts.add_option(175'-I', '--ignore-installed',176dest='ignore_installed',177action='store_true',178help='Ignore the installed packages, overwriting them. '179'This can break your system if the existing package '180'is of a different version or was installed '181'with a different package manager!'182)183184cmd_opts.add_option(cmdoptions.ignore_requires_python())185cmd_opts.add_option(cmdoptions.no_build_isolation())186cmd_opts.add_option(cmdoptions.use_pep517())187cmd_opts.add_option(cmdoptions.no_use_pep517())188189cmd_opts.add_option(cmdoptions.install_options())190cmd_opts.add_option(cmdoptions.global_options())191192cmd_opts.add_option(193"--compile",194action="store_true",195dest="compile",196default=True,197help="Compile Python source files to bytecode",198)199200cmd_opts.add_option(201"--no-compile",202action="store_false",203dest="compile",204help="Do not compile Python source files to bytecode",205)206207cmd_opts.add_option(208"--no-warn-script-location",209action="store_false",210dest="warn_script_location",211default=True,212help="Do not warn when installing scripts outside PATH",213)214cmd_opts.add_option(215"--no-warn-conflicts",216action="store_false",217dest="warn_about_conflicts",218default=True,219help="Do not warn about broken dependencies",220)221222cmd_opts.add_option(cmdoptions.no_binary())223cmd_opts.add_option(cmdoptions.only_binary())224cmd_opts.add_option(cmdoptions.prefer_binary())225cmd_opts.add_option(cmdoptions.require_hashes())226cmd_opts.add_option(cmdoptions.progress_bar())227228index_opts = cmdoptions.make_option_group(229cmdoptions.index_group,230self.parser,231)232233self.parser.insert_option_group(0, index_opts)234self.parser.insert_option_group(0, cmd_opts)235236@with_cleanup237def run(self, options, args):238# type: (Values, List[Any]) -> int239if options.use_user_site and options.target_dir is not None:240raise CommandError("Can not combine '--user' and '--target'")241242cmdoptions.check_install_build_global(options)243upgrade_strategy = "to-satisfy-only"244if options.upgrade:245upgrade_strategy = options.upgrade_strategy246247cmdoptions.check_dist_restriction(options, check_target=True)248249install_options = options.install_options or []250251options.use_user_site = decide_user_install(252options.use_user_site,253prefix_path=options.prefix_path,254target_dir=options.target_dir,255root_path=options.root_path,256isolated_mode=options.isolated_mode,257)258259target_temp_dir = None # type: Optional[TempDirectory]260target_temp_dir_path = None # type: Optional[str]261if options.target_dir:262options.ignore_installed = True263options.target_dir = os.path.abspath(options.target_dir)264if (os.path.exists(options.target_dir) and not265os.path.isdir(options.target_dir)):266raise CommandError(267"Target path exists but is not a directory, will not "268"continue."269)270271# Create a target directory for using with the target option272target_temp_dir = TempDirectory(kind="target")273target_temp_dir_path = target_temp_dir.path274275global_options = options.global_options or []276277session = self.get_default_session(options)278279target_python = make_target_python(options)280finder = self._build_package_finder(281options=options,282session=session,283target_python=target_python,284ignore_requires_python=options.ignore_requires_python,285)286build_delete = (not (options.no_clean or options.build_dir))287wheel_cache = WheelCache(options.cache_dir, options.format_control)288289req_tracker = self.enter_context(get_requirement_tracker())290291directory = TempDirectory(292options.build_dir,293delete=build_delete,294kind="install",295globally_managed=True,296)297298try:299reqs = self.get_requirements(300args, options, finder, session,301check_supported_wheels=not options.target_dir,302)303304warn_deprecated_install_options(305reqs, options.install_options306)307308preparer = self.make_requirement_preparer(309temp_build_dir=directory,310options=options,311req_tracker=req_tracker,312session=session,313finder=finder,314use_user_site=options.use_user_site,315)316resolver = self.make_resolver(317preparer=preparer,318finder=finder,319options=options,320wheel_cache=wheel_cache,321use_user_site=options.use_user_site,322ignore_installed=options.ignore_installed,323ignore_requires_python=options.ignore_requires_python,324force_reinstall=options.force_reinstall,325upgrade_strategy=upgrade_strategy,326use_pep517=options.use_pep517,327)328329self.trace_basic_info(finder)330331requirement_set = resolver.resolve(332reqs, check_supported_wheels=not options.target_dir333)334335try:336pip_req = requirement_set.get_requirement("pip")337except KeyError:338modifying_pip = None339else:340# If we're not replacing an already installed pip,341# we're not modifying it.342modifying_pip = pip_req.satisfied_by is None343protect_pip_from_modification_on_windows(344modifying_pip=modifying_pip345)346347check_binary_allowed = get_check_binary_allowed(348finder.format_control349)350351reqs_to_build = [352r for r in requirement_set.requirements.values()353if should_build_for_install_command(354r, check_binary_allowed355)356]357358_, build_failures = build(359reqs_to_build,360wheel_cache=wheel_cache,361build_options=[],362global_options=[],363)364365# If we're using PEP 517, we cannot do a direct install366# so we fail here.367# We don't care about failures building legacy368# requirements, as we'll fall through to a direct369# install for those.370pep517_build_failures = [371r for r in build_failures if r.use_pep517372]373if pep517_build_failures:374raise InstallationError(375"Could not build wheels for {} which use"376" PEP 517 and cannot be installed directly".format(377", ".join(r.name for r in pep517_build_failures)))378379to_install = resolver.get_installation_order(380requirement_set381)382383# Consistency Checking of the package set we're installing.384should_warn_about_conflicts = (385not options.ignore_dependencies and386options.warn_about_conflicts387)388if should_warn_about_conflicts:389self._warn_about_conflicts(to_install)390391# Don't warn about script install locations if392# --target has been specified393warn_script_location = options.warn_script_location394if options.target_dir:395warn_script_location = False396397installed = install_given_reqs(398to_install,399install_options,400global_options,401root=options.root_path,402home=target_temp_dir_path,403prefix=options.prefix_path,404pycompile=options.compile,405warn_script_location=warn_script_location,406use_user_site=options.use_user_site,407)408409lib_locations = get_lib_location_guesses(410user=options.use_user_site,411home=target_temp_dir_path,412root=options.root_path,413prefix=options.prefix_path,414isolated=options.isolated_mode,415)416working_set = pkg_resources.WorkingSet(lib_locations)417418installed.sort(key=operator.attrgetter('name'))419items = []420for result in installed:421item = result.name422try:423installed_version = get_installed_version(424result.name, working_set=working_set425)426if installed_version:427item += '-' + installed_version428except Exception:429pass430items.append(item)431installed_desc = ' '.join(items)432if installed_desc:433write_output(434'Successfully installed %s', installed_desc,435)436except EnvironmentError as error:437show_traceback = (self.verbosity >= 1)438439message = create_env_error_message(440error, show_traceback, options.use_user_site,441)442logger.error(message, exc_info=show_traceback)443444return ERROR445446if options.target_dir:447self._handle_target_dir(448options.target_dir, target_temp_dir, options.upgrade449)450451return SUCCESS452453def _handle_target_dir(self, target_dir, target_temp_dir, upgrade):454ensure_dir(target_dir)455456# Checking both purelib and platlib directories for installed457# packages to be moved to target directory458lib_dir_list = []459460with target_temp_dir:461# Checking both purelib and platlib directories for installed462# packages to be moved to target directory463scheme = distutils_scheme('', home=target_temp_dir.path)464purelib_dir = scheme['purelib']465platlib_dir = scheme['platlib']466data_dir = scheme['data']467468if os.path.exists(purelib_dir):469lib_dir_list.append(purelib_dir)470if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:471lib_dir_list.append(platlib_dir)472if os.path.exists(data_dir):473lib_dir_list.append(data_dir)474475for lib_dir in lib_dir_list:476for item in os.listdir(lib_dir):477if lib_dir == data_dir:478ddir = os.path.join(data_dir, item)479if any(s.startswith(ddir) for s in lib_dir_list[:-1]):480continue481target_item_dir = os.path.join(target_dir, item)482if os.path.exists(target_item_dir):483if not upgrade:484logger.warning(485'Target directory %s already exists. Specify '486'--upgrade to force replacement.',487target_item_dir488)489continue490if os.path.islink(target_item_dir):491logger.warning(492'Target directory %s already exists and is '493'a link. pip will not automatically replace '494'links, please remove if replacement is '495'desired.',496target_item_dir497)498continue499if os.path.isdir(target_item_dir):500shutil.rmtree(target_item_dir)501else:502os.remove(target_item_dir)503504shutil.move(505os.path.join(lib_dir, item),506target_item_dir507)508509def _warn_about_conflicts(self, to_install):510try:511package_set, _dep_info = check_install_conflicts(to_install)512except Exception:513logger.error("Error checking for conflicts.", exc_info=True)514return515missing, conflicting = _dep_info516517# NOTE: There is some duplication here from pip check518for project_name in missing:519version = package_set[project_name][0]520for dependency in missing[project_name]:521logger.critical(522"%s %s requires %s, which is not installed.",523project_name, version, dependency[1],524)525526for project_name in conflicting:527version = package_set[project_name][0]528for dep_name, dep_version, req in conflicting[project_name]:529logger.critical(530"%s %s has requirement %s, but you'll have %s %s which is "531"incompatible.",532project_name, version, req, dep_name, dep_version,533)534535536def get_lib_location_guesses(*args, **kwargs):537scheme = distutils_scheme('', *args, **kwargs)538return [scheme['purelib'], scheme['platlib']]539540541def site_packages_writable(**kwargs):542return all(543test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs))544)545546547def decide_user_install(548use_user_site, # type: Optional[bool]549prefix_path=None, # type: Optional[str]550target_dir=None, # type: Optional[str]551root_path=None, # type: Optional[str]552isolated_mode=False, # type: bool553):554# type: (...) -> bool555"""Determine whether to do a user install based on the input options.556557If use_user_site is False, no additional checks are done.558If use_user_site is True, it is checked for compatibility with other559options.560If use_user_site is None, the default behaviour depends on the environment,561which is provided by the other arguments.562"""563# In some cases (config from tox), use_user_site can be set to an integer564# rather than a bool, which 'use_user_site is False' wouldn't catch.565if (use_user_site is not None) and (not use_user_site):566logger.debug("Non-user install by explicit request")567return False568569if use_user_site:570if prefix_path:571raise CommandError(572"Can not combine '--user' and '--prefix' as they imply "573"different installation locations"574)575if virtualenv_no_global():576raise InstallationError(577"Can not perform a '--user' install. User site-packages "578"are not visible in this virtualenv."579)580logger.debug("User install by explicit request")581return True582583# If we are here, user installs have not been explicitly requested/avoided584assert use_user_site is None585586# user install incompatible with --prefix/--target587if prefix_path or target_dir:588logger.debug("Non-user install due to --prefix or --target option")589return False590591# If user installs are not enabled, choose a non-user install592if not site.ENABLE_USER_SITE:593logger.debug("Non-user install because user site-packages disabled")594return False595596# If we have permission for a non-user install, do that,597# otherwise do a user install.598if site_packages_writable(root=root_path, isolated=isolated_mode):599logger.debug("Non-user install because site-packages writeable")600return False601602logger.info("Defaulting to user installation because normal site-packages "603"is not writeable")604return True605606607def warn_deprecated_install_options(requirements, options):608# type: (List[InstallRequirement], Optional[List[str]]) -> None609"""If any location-changing --install-option arguments were passed for610requirements or on the command-line, then show a deprecation warning.611"""612def format_options(option_names):613# type: (Iterable[str]) -> List[str]614return ["--{}".format(name.replace("_", "-")) for name in option_names]615616offenders = []617618for requirement in requirements:619install_options = requirement.install_options620location_options = parse_distutils_args(install_options)621if location_options:622offenders.append(623"{!r} from {}".format(624format_options(location_options.keys()), requirement625)626)627628if options:629location_options = parse_distutils_args(options)630if location_options:631offenders.append(632"{!r} from command line".format(633format_options(location_options.keys())634)635)636637if not offenders:638return639640deprecated(641reason=(642"Location-changing options found in --install-option: {}. "643"This configuration may cause unexpected behavior and is "644"unsupported.".format(645"; ".join(offenders)646)647),648replacement=(649"using pip-level options like --user, --prefix, --root, and "650"--target"651),652gone_in="20.2",653issue=7309,654)655656657def create_env_error_message(error, show_traceback, using_user_site):658"""Format an error message for an EnvironmentError659660It may occur anytime during the execution of the install command.661"""662parts = []663664# Mention the error if we are not going to show a traceback665parts.append("Could not install packages due to an EnvironmentError")666if not show_traceback:667parts.append(": ")668parts.append(str(error))669else:670parts.append(".")671672# Spilt the error indication from a helper message (if any)673parts[-1] += "\n"674675# Suggest useful actions to the user:676# (1) using user site-packages or (2) verifying the permissions677if error.errno == errno.EACCES:678user_option_part = "Consider using the `--user` option"679permissions_part = "Check the permissions"680681if not using_user_site:682parts.extend([683user_option_part, " or ",684permissions_part.lower(),685])686else:687parts.append(permissions_part)688parts.append(".\n")689690return "".join(parts).strip() + "\n"691692693