Path: blob/main/test/lib/python3.9/site-packages/setuptools/_distutils/command/install.py
4804 views
"""distutils.command.install12Implements the Distutils 'install' command."""34import sys5import os6import contextlib7import sysconfig8import itertools910from distutils import log11from distutils.core import Command12from distutils.debug import DEBUG13from distutils.sysconfig import get_config_vars14from distutils.errors import DistutilsPlatformError15from distutils.file_util import write_file16from distutils.util import convert_path, subst_vars, change_root17from distutils.util import get_platform18from distutils.errors import DistutilsOptionError19from .. import _collections2021from site import USER_BASE22from site import USER_SITE23HAS_USER_SITE = True2425WINDOWS_SCHEME = {26'purelib': '{base}/Lib/site-packages',27'platlib': '{base}/Lib/site-packages',28'headers': '{base}/Include/{dist_name}',29'scripts': '{base}/Scripts',30'data' : '{base}',31}3233INSTALL_SCHEMES = {34'posix_prefix': {35'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',36'platlib': '{platbase}/{platlibdir}/{implementation_lower}{py_version_short}/site-packages',37'headers': '{base}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',38'scripts': '{base}/bin',39'data' : '{base}',40},41'posix_home': {42'purelib': '{base}/lib/{implementation_lower}',43'platlib': '{base}/{platlibdir}/{implementation_lower}',44'headers': '{base}/include/{implementation_lower}/{dist_name}',45'scripts': '{base}/bin',46'data' : '{base}',47},48'nt': WINDOWS_SCHEME,49'pypy': {50'purelib': '{base}/site-packages',51'platlib': '{base}/site-packages',52'headers': '{base}/include/{dist_name}',53'scripts': '{base}/bin',54'data' : '{base}',55},56'pypy_nt': {57'purelib': '{base}/site-packages',58'platlib': '{base}/site-packages',59'headers': '{base}/include/{dist_name}',60'scripts': '{base}/Scripts',61'data' : '{base}',62},63}6465# user site schemes66if HAS_USER_SITE:67INSTALL_SCHEMES['nt_user'] = {68'purelib': '{usersite}',69'platlib': '{usersite}',70'headers': '{userbase}/{implementation}{py_version_nodot_plat}/Include/{dist_name}',71'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',72'data' : '{userbase}',73}7475INSTALL_SCHEMES['posix_user'] = {76'purelib': '{usersite}',77'platlib': '{usersite}',78'headers':79'{userbase}/include/{implementation_lower}{py_version_short}{abiflags}/{dist_name}',80'scripts': '{userbase}/bin',81'data' : '{userbase}',82}8384# The keys to an installation scheme; if any new types of files are to be85# installed, be sure to add an entry to every installation scheme above,86# and to SCHEME_KEYS here.87SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')888990def _load_sysconfig_schemes():91with contextlib.suppress(AttributeError):92return {93scheme: sysconfig.get_paths(scheme, expand=False)94for scheme in sysconfig.get_scheme_names()95}969798def _load_schemes():99"""100Extend default schemes with schemes from sysconfig.101"""102103sysconfig_schemes = _load_sysconfig_schemes() or {}104105return {106scheme: {107**INSTALL_SCHEMES.get(scheme, {}),108**sysconfig_schemes.get(scheme, {}),109}110for scheme in set(itertools.chain(INSTALL_SCHEMES, sysconfig_schemes))111}112113114def _get_implementation():115if hasattr(sys, 'pypy_version_info'):116return 'PyPy'117else:118return 'Python'119120121def _select_scheme(ob, name):122scheme = _inject_headers(name, _load_scheme(_resolve_scheme(name)))123vars(ob).update(_remove_set(ob, _scheme_attrs(scheme)))124125126def _remove_set(ob, attrs):127"""128Include only attrs that are None in ob.129"""130return {131key: value132for key, value in attrs.items()133if getattr(ob, key) is None134}135136137def _resolve_scheme(name):138os_name, sep, key = name.partition('_')139try:140resolved = sysconfig.get_preferred_scheme(key)141except Exception:142resolved = _pypy_hack(name)143return resolved144145146def _load_scheme(name):147return _load_schemes()[name]148149150def _inject_headers(name, scheme):151"""152Given a scheme name and the resolved scheme,153if the scheme does not include headers, resolve154the fallback scheme for the name and use headers155from it. pypa/distutils#88156"""157# Bypass the preferred scheme, which may not158# have defined headers.159fallback = _load_scheme(_pypy_hack(name))160scheme.setdefault('headers', fallback['headers'])161return scheme162163164def _scheme_attrs(scheme):165"""Resolve install directories by applying the install schemes."""166return {167f'install_{key}': scheme[key]168for key in SCHEME_KEYS169}170171172def _pypy_hack(name):173PY37 = sys.version_info < (3, 8)174old_pypy = hasattr(sys, 'pypy_version_info') and PY37175prefix = not name.endswith(('_user', '_home'))176pypy_name = 'pypy' + '_nt' * (os.name == 'nt')177return pypy_name if old_pypy and prefix else name178179180class install(Command):181182description = "install everything from build directory"183184user_options = [185# Select installation scheme and set base director(y|ies)186('prefix=', None,187"installation prefix"),188('exec-prefix=', None,189"(Unix only) prefix for platform-specific files"),190('home=', None,191"(Unix only) home directory to install under"),192193# Or, just set the base director(y|ies)194('install-base=', None,195"base installation directory (instead of --prefix or --home)"),196('install-platbase=', None,197"base installation directory for platform-specific files " +198"(instead of --exec-prefix or --home)"),199('root=', None,200"install everything relative to this alternate root directory"),201202# Or, explicitly set the installation scheme203('install-purelib=', None,204"installation directory for pure Python module distributions"),205('install-platlib=', None,206"installation directory for non-pure module distributions"),207('install-lib=', None,208"installation directory for all module distributions " +209"(overrides --install-purelib and --install-platlib)"),210211('install-headers=', None,212"installation directory for C/C++ headers"),213('install-scripts=', None,214"installation directory for Python scripts"),215('install-data=', None,216"installation directory for data files"),217218# Byte-compilation options -- see install_lib.py for details, as219# these are duplicated from there (but only install_lib does220# anything with them).221('compile', 'c', "compile .py to .pyc [default]"),222('no-compile', None, "don't compile .py files"),223('optimize=', 'O',224"also compile with optimization: -O1 for \"python -O\", "225"-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),226227# Miscellaneous control options228('force', 'f',229"force installation (overwrite any existing files)"),230('skip-build', None,231"skip rebuilding everything (for testing/debugging)"),232233# Where to install documentation (eventually!)234#('doc-format=', None, "format of documentation to generate"),235#('install-man=', None, "directory for Unix man pages"),236#('install-html=', None, "directory for HTML documentation"),237#('install-info=', None, "directory for GNU info files"),238239('record=', None,240"filename in which to record list of installed files"),241]242243boolean_options = ['compile', 'force', 'skip-build']244245if HAS_USER_SITE:246user_options.append(('user', None,247"install in user site-package '%s'" % USER_SITE))248boolean_options.append('user')249250negative_opt = {'no-compile' : 'compile'}251252253def initialize_options(self):254"""Initializes options."""255# High-level options: these select both an installation base256# and scheme.257self.prefix = None258self.exec_prefix = None259self.home = None260self.user = 0261262# These select only the installation base; it's up to the user to263# specify the installation scheme (currently, that means supplying264# the --install-{platlib,purelib,scripts,data} options).265self.install_base = None266self.install_platbase = None267self.root = None268269# These options are the actual installation directories; if not270# supplied by the user, they are filled in using the installation271# scheme implied by prefix/exec-prefix/home and the contents of272# that installation scheme.273self.install_purelib = None # for pure module distributions274self.install_platlib = None # non-pure (dists w/ extensions)275self.install_headers = None # for C/C++ headers276self.install_lib = None # set to either purelib or platlib277self.install_scripts = None278self.install_data = None279self.install_userbase = USER_BASE280self.install_usersite = USER_SITE281282self.compile = None283self.optimize = None284285# Deprecated286# These two are for putting non-packagized distributions into their287# own directory and creating a .pth file if it makes sense.288# 'extra_path' comes from the setup file; 'install_path_file' can289# be turned off if it makes no sense to install a .pth file. (But290# better to install it uselessly than to guess wrong and not291# install it when it's necessary and would be used!) Currently,292# 'install_path_file' is always true unless some outsider meddles293# with it.294self.extra_path = None295self.install_path_file = 1296297# 'force' forces installation, even if target files are not298# out-of-date. 'skip_build' skips running the "build" command,299# handy if you know it's not necessary. 'warn_dir' (which is *not*300# a user option, it's just there so the bdist_* commands can turn301# it off) determines whether we warn about installing to a302# directory not in sys.path.303self.force = 0304self.skip_build = 0305self.warn_dir = 1306307# These are only here as a conduit from the 'build' command to the308# 'install_*' commands that do the real work. ('build_base' isn't309# actually used anywhere, but it might be useful in future.) They310# are not user options, because if the user told the install311# command where the build directory is, that wouldn't affect the312# build command.313self.build_base = None314self.build_lib = None315316# Not defined yet because we don't know anything about317# documentation yet.318#self.install_man = None319#self.install_html = None320#self.install_info = None321322self.record = None323324325# -- Option finalizing methods -------------------------------------326# (This is rather more involved than for most commands,327# because this is where the policy for installing third-328# party Python modules on various platforms given a wide329# array of user input is decided. Yes, it's quite complex!)330331def finalize_options(self):332"""Finalizes options."""333# This method (and its helpers, like 'finalize_unix()',334# 'finalize_other()', and 'select_scheme()') is where the default335# installation directories for modules, extension modules, and336# anything else we care to install from a Python module337# distribution. Thus, this code makes a pretty important policy338# statement about how third-party stuff is added to a Python339# installation! Note that the actual work of installation is done340# by the relatively simple 'install_*' commands; they just take341# their orders from the installation directory options determined342# here.343344# Check for errors/inconsistencies in the options; first, stuff345# that's wrong on any platform.346347if ((self.prefix or self.exec_prefix or self.home) and348(self.install_base or self.install_platbase)):349raise DistutilsOptionError(350"must supply either prefix/exec-prefix/home or " +351"install-base/install-platbase -- not both")352353if self.home and (self.prefix or self.exec_prefix):354raise DistutilsOptionError(355"must supply either home or prefix/exec-prefix -- not both")356357if self.user and (self.prefix or self.exec_prefix or self.home or358self.install_base or self.install_platbase):359raise DistutilsOptionError("can't combine user with prefix, "360"exec_prefix/home, or install_(plat)base")361362# Next, stuff that's wrong (or dubious) only on certain platforms.363if os.name != "posix":364if self.exec_prefix:365self.warn("exec-prefix option ignored on this platform")366self.exec_prefix = None367368# Now the interesting logic -- so interesting that we farm it out369# to other methods. The goal of these methods is to set the final370# values for the install_{lib,scripts,data,...} options, using as371# input a heady brew of prefix, exec_prefix, home, install_base,372# install_platbase, user-supplied versions of373# install_{purelib,platlib,lib,scripts,data,...}, and the374# install schemes. Phew!375376self.dump_dirs("pre-finalize_{unix,other}")377378if os.name == 'posix':379self.finalize_unix()380else:381self.finalize_other()382383self.dump_dirs("post-finalize_{unix,other}()")384385# Expand configuration variables, tilde, etc. in self.install_base386# and self.install_platbase -- that way, we can use $base or387# $platbase in the other installation directories and not worry388# about needing recursive variable expansion (shudder).389390py_version = sys.version.split()[0]391(prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')392try:393abiflags = sys.abiflags394except AttributeError:395# sys.abiflags may not be defined on all platforms.396abiflags = ''397local_vars = {398'dist_name': self.distribution.get_name(),399'dist_version': self.distribution.get_version(),400'dist_fullname': self.distribution.get_fullname(),401'py_version': py_version,402'py_version_short': '%d.%d' % sys.version_info[:2],403'py_version_nodot': '%d%d' % sys.version_info[:2],404'sys_prefix': prefix,405'prefix': prefix,406'sys_exec_prefix': exec_prefix,407'exec_prefix': exec_prefix,408'abiflags': abiflags,409'platlibdir': getattr(sys, 'platlibdir', 'lib'),410'implementation_lower': _get_implementation().lower(),411'implementation': _get_implementation(),412}413414# vars for compatibility on older Pythons415compat_vars = dict(416# Python 3.9 and earlier417py_version_nodot_plat=getattr(sys, 'winver', '').replace('.', ''),418)419420if HAS_USER_SITE:421local_vars['userbase'] = self.install_userbase422local_vars['usersite'] = self.install_usersite423424self.config_vars = _collections.DictStack(425[compat_vars, sysconfig.get_config_vars(), local_vars])426427self.expand_basedirs()428429self.dump_dirs("post-expand_basedirs()")430431# Now define config vars for the base directories so we can expand432# everything else.433local_vars['base'] = self.install_base434local_vars['platbase'] = self.install_platbase435436if DEBUG:437from pprint import pprint438print("config vars:")439pprint(dict(self.config_vars))440441# Expand "~" and configuration variables in the installation442# directories.443self.expand_dirs()444445self.dump_dirs("post-expand_dirs()")446447# Create directories in the home dir:448if self.user:449self.create_home_path()450451# Pick the actual directory to install all modules to: either452# install_purelib or install_platlib, depending on whether this453# module distribution is pure or not. Of course, if the user454# already specified install_lib, use their selection.455if self.install_lib is None:456if self.distribution.has_ext_modules(): # has extensions: non-pure457self.install_lib = self.install_platlib458else:459self.install_lib = self.install_purelib460461462# Convert directories from Unix /-separated syntax to the local463# convention.464self.convert_paths('lib', 'purelib', 'platlib',465'scripts', 'data', 'headers',466'userbase', 'usersite')467468# Deprecated469# Well, we're not actually fully completely finalized yet: we still470# have to deal with 'extra_path', which is the hack for allowing471# non-packagized module distributions (hello, Numerical Python!) to472# get their own directories.473self.handle_extra_path()474self.install_libbase = self.install_lib # needed for .pth file475self.install_lib = os.path.join(self.install_lib, self.extra_dirs)476477# If a new root directory was supplied, make all the installation478# dirs relative to it.479if self.root is not None:480self.change_roots('libbase', 'lib', 'purelib', 'platlib',481'scripts', 'data', 'headers')482483self.dump_dirs("after prepending root")484485# Find out the build directories, ie. where to install from.486self.set_undefined_options('build',487('build_base', 'build_base'),488('build_lib', 'build_lib'))489490# Punt on doc directories for now -- after all, we're punting on491# documentation completely!492493def dump_dirs(self, msg):494"""Dumps the list of user options."""495if not DEBUG:496return497from distutils.fancy_getopt import longopt_xlate498log.debug(msg + ":")499for opt in self.user_options:500opt_name = opt[0]501if opt_name[-1] == "=":502opt_name = opt_name[0:-1]503if opt_name in self.negative_opt:504opt_name = self.negative_opt[opt_name]505opt_name = opt_name.translate(longopt_xlate)506val = not getattr(self, opt_name)507else:508opt_name = opt_name.translate(longopt_xlate)509val = getattr(self, opt_name)510log.debug(" %s: %s", opt_name, val)511512def finalize_unix(self):513"""Finalizes options for posix platforms."""514if self.install_base is not None or self.install_platbase is not None:515incomplete_scheme = (516(517self.install_lib is None and518self.install_purelib is None and519self.install_platlib is None520) or521self.install_headers is None or522self.install_scripts is None or523self.install_data is None524)525if incomplete_scheme:526raise DistutilsOptionError(527"install-base or install-platbase supplied, but "528"installation scheme is incomplete")529return530531if self.user:532if self.install_userbase is None:533raise DistutilsPlatformError(534"User base directory is not specified")535self.install_base = self.install_platbase = self.install_userbase536self.select_scheme("posix_user")537elif self.home is not None:538self.install_base = self.install_platbase = self.home539self.select_scheme("posix_home")540else:541if self.prefix is None:542if self.exec_prefix is not None:543raise DistutilsOptionError(544"must not supply exec-prefix without prefix")545546# Allow Fedora to add components to the prefix547_prefix_addition = getattr(sysconfig, '_prefix_addition', "")548549self.prefix = (550os.path.normpath(sys.prefix) + _prefix_addition)551self.exec_prefix = (552os.path.normpath(sys.exec_prefix) + _prefix_addition)553554else:555if self.exec_prefix is None:556self.exec_prefix = self.prefix557558self.install_base = self.prefix559self.install_platbase = self.exec_prefix560self.select_scheme("posix_prefix")561562def finalize_other(self):563"""Finalizes options for non-posix platforms"""564if self.user:565if self.install_userbase is None:566raise DistutilsPlatformError(567"User base directory is not specified")568self.install_base = self.install_platbase = self.install_userbase569self.select_scheme(os.name + "_user")570elif self.home is not None:571self.install_base = self.install_platbase = self.home572self.select_scheme("posix_home")573else:574if self.prefix is None:575self.prefix = os.path.normpath(sys.prefix)576577self.install_base = self.install_platbase = self.prefix578try:579self.select_scheme(os.name)580except KeyError:581raise DistutilsPlatformError(582"I don't know how to install stuff on '%s'" % os.name)583584def select_scheme(self, name):585_select_scheme(self, name)586587def _expand_attrs(self, attrs):588for attr in attrs:589val = getattr(self, attr)590if val is not None:591if os.name == 'posix' or os.name == 'nt':592val = os.path.expanduser(val)593val = subst_vars(val, self.config_vars)594setattr(self, attr, val)595596def expand_basedirs(self):597"""Calls `os.path.expanduser` on install_base, install_platbase and598root."""599self._expand_attrs(['install_base', 'install_platbase', 'root'])600601def expand_dirs(self):602"""Calls `os.path.expanduser` on install dirs."""603self._expand_attrs(['install_purelib', 'install_platlib',604'install_lib', 'install_headers',605'install_scripts', 'install_data',])606607def convert_paths(self, *names):608"""Call `convert_path` over `names`."""609for name in names:610attr = "install_" + name611setattr(self, attr, convert_path(getattr(self, attr)))612613def handle_extra_path(self):614"""Set `path_file` and `extra_dirs` using `extra_path`."""615if self.extra_path is None:616self.extra_path = self.distribution.extra_path617618if self.extra_path is not None:619log.warn(620"Distribution option extra_path is deprecated. "621"See issue27919 for details."622)623if isinstance(self.extra_path, str):624self.extra_path = self.extra_path.split(',')625626if len(self.extra_path) == 1:627path_file = extra_dirs = self.extra_path[0]628elif len(self.extra_path) == 2:629path_file, extra_dirs = self.extra_path630else:631raise DistutilsOptionError(632"'extra_path' option must be a list, tuple, or "633"comma-separated string with 1 or 2 elements")634635# convert to local form in case Unix notation used (as it636# should be in setup scripts)637extra_dirs = convert_path(extra_dirs)638else:639path_file = None640extra_dirs = ''641642# XXX should we warn if path_file and not extra_dirs? (in which643# case the path file would be harmless but pointless)644self.path_file = path_file645self.extra_dirs = extra_dirs646647def change_roots(self, *names):648"""Change the install directories pointed by name using root."""649for name in names:650attr = "install_" + name651setattr(self, attr, change_root(self.root, getattr(self, attr)))652653def create_home_path(self):654"""Create directories under ~."""655if not self.user:656return657home = convert_path(os.path.expanduser("~"))658for name, path in self.config_vars.items():659if str(path).startswith(home) and not os.path.isdir(path):660self.debug_print("os.makedirs('%s', 0o700)" % path)661os.makedirs(path, 0o700)662663# -- Command execution methods -------------------------------------664665def run(self):666"""Runs the command."""667# Obviously have to build before we can install668if not self.skip_build:669self.run_command('build')670# If we built for any other platform, we can't install.671build_plat = self.distribution.get_command_obj('build').plat_name672# check warn_dir - it is a clue that the 'install' is happening673# internally, and not to sys.path, so we don't check the platform674# matches what we are running.675if self.warn_dir and build_plat != get_platform():676raise DistutilsPlatformError("Can't install when "677"cross-compiling")678679# Run all sub-commands (at least those that need to be run)680for cmd_name in self.get_sub_commands():681self.run_command(cmd_name)682683if self.path_file:684self.create_path_file()685686# write list of installed files, if requested.687if self.record:688outputs = self.get_outputs()689if self.root: # strip any package prefix690root_len = len(self.root)691for counter in range(len(outputs)):692outputs[counter] = outputs[counter][root_len:]693self.execute(write_file,694(self.record, outputs),695"writing list of installed files to '%s'" %696self.record)697698sys_path = map(os.path.normpath, sys.path)699sys_path = map(os.path.normcase, sys_path)700install_lib = os.path.normcase(os.path.normpath(self.install_lib))701if (self.warn_dir and702not (self.path_file and self.install_path_file) and703install_lib not in sys_path):704log.debug(("modules installed to '%s', which is not in "705"Python's module search path (sys.path) -- "706"you'll have to change the search path yourself"),707self.install_lib)708709def create_path_file(self):710"""Creates the .pth file"""711filename = os.path.join(self.install_libbase,712self.path_file + ".pth")713if self.install_path_file:714self.execute(write_file,715(filename, [self.extra_dirs]),716"creating %s" % filename)717else:718self.warn("path file '%s' not created" % filename)719720721# -- Reporting methods ---------------------------------------------722723def get_outputs(self):724"""Assembles the outputs of all the sub-commands."""725outputs = []726for cmd_name in self.get_sub_commands():727cmd = self.get_finalized_command(cmd_name)728# Add the contents of cmd.get_outputs(), ensuring729# that outputs doesn't contain duplicate entries730for filename in cmd.get_outputs():731if filename not in outputs:732outputs.append(filename)733734if self.path_file and self.install_path_file:735outputs.append(os.path.join(self.install_libbase,736self.path_file + ".pth"))737738return outputs739740def get_inputs(self):741"""Returns the inputs of all the sub-commands"""742# XXX gee, this looks familiar ;-(743inputs = []744for cmd_name in self.get_sub_commands():745cmd = self.get_finalized_command(cmd_name)746inputs.extend(cmd.get_inputs())747748return inputs749750# -- Predicates for sub-command list -------------------------------751752def has_lib(self):753"""Returns true if the current distribution has any Python754modules to install."""755return (self.distribution.has_pure_modules() or756self.distribution.has_ext_modules())757758def has_headers(self):759"""Returns true if the current distribution has any headers to760install."""761return self.distribution.has_headers()762763def has_scripts(self):764"""Returns true if the current distribution has any scripts to.765install."""766return self.distribution.has_scripts()767768def has_data(self):769"""Returns true if the current distribution has any data to.770install."""771return self.distribution.has_data_files()772773# 'sub_commands': a list of commands this command might have to run to774# get its work done. See cmd.py for more info.775sub_commands = [('install_lib', has_lib),776('install_headers', has_headers),777('install_scripts', has_scripts),778('install_data', has_data),779('install_egg_info', lambda self:True),780]781782783