Path: blob/master/venv/Lib/site-packages/setuptools/_distutils/command/install.py
811 views
"""distutils.command.install12Implements the Distutils 'install' command."""34import sys5import os67from distutils import log8from distutils.core import Command9from distutils.debug import DEBUG10from distutils.sysconfig import get_config_vars11from distutils.errors import DistutilsPlatformError12from distutils.file_util import write_file13from distutils.util import convert_path, subst_vars, change_root14from distutils.util import get_platform15from distutils.errors import DistutilsOptionError1617from site import USER_BASE18from site import USER_SITE19HAS_USER_SITE = True2021WINDOWS_SCHEME = {22'purelib': '$base/Lib/site-packages',23'platlib': '$base/Lib/site-packages',24'headers': '$base/Include/$dist_name',25'scripts': '$base/Scripts',26'data' : '$base',27}2829INSTALL_SCHEMES = {30'unix_prefix': {31'purelib': '$base/lib/python$py_version_short/site-packages',32'platlib': '$platbase/$platlibdir/python$py_version_short/site-packages',33'headers': '$base/include/python$py_version_short$abiflags/$dist_name',34'scripts': '$base/bin',35'data' : '$base',36},37'unix_home': {38'purelib': '$base/lib/python',39'platlib': '$base/$platlibdir/python',40'headers': '$base/include/python/$dist_name',41'scripts': '$base/bin',42'data' : '$base',43},44'nt': WINDOWS_SCHEME,45'pypy': {46'purelib': '$base/site-packages',47'platlib': '$base/site-packages',48'headers': '$base/include/$dist_name',49'scripts': '$base/bin',50'data' : '$base',51},52'pypy_nt': {53'purelib': '$base/site-packages',54'platlib': '$base/site-packages',55'headers': '$base/include/$dist_name',56'scripts': '$base/Scripts',57'data' : '$base',58},59}6061# user site schemes62if HAS_USER_SITE:63INSTALL_SCHEMES['nt_user'] = {64'purelib': '$usersite',65'platlib': '$usersite',66'headers': '$userbase/Python$py_version_nodot/Include/$dist_name',67'scripts': '$userbase/Python$py_version_nodot/Scripts',68'data' : '$userbase',69}7071INSTALL_SCHEMES['unix_user'] = {72'purelib': '$usersite',73'platlib': '$usersite',74'headers':75'$userbase/include/python$py_version_short$abiflags/$dist_name',76'scripts': '$userbase/bin',77'data' : '$userbase',78}7980# The keys to an installation scheme; if any new types of files are to be81# installed, be sure to add an entry to every installation scheme above,82# and to SCHEME_KEYS here.83SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')848586class install(Command):8788description = "install everything from build directory"8990user_options = [91# Select installation scheme and set base director(y|ies)92('prefix=', None,93"installation prefix"),94('exec-prefix=', None,95"(Unix only) prefix for platform-specific files"),96('home=', None,97"(Unix only) home directory to install under"),9899# Or, just set the base director(y|ies)100('install-base=', None,101"base installation directory (instead of --prefix or --home)"),102('install-platbase=', None,103"base installation directory for platform-specific files " +104"(instead of --exec-prefix or --home)"),105('root=', None,106"install everything relative to this alternate root directory"),107108# Or, explicitly set the installation scheme109('install-purelib=', None,110"installation directory for pure Python module distributions"),111('install-platlib=', None,112"installation directory for non-pure module distributions"),113('install-lib=', None,114"installation directory for all module distributions " +115"(overrides --install-purelib and --install-platlib)"),116117('install-headers=', None,118"installation directory for C/C++ headers"),119('install-scripts=', None,120"installation directory for Python scripts"),121('install-data=', None,122"installation directory for data files"),123124# Byte-compilation options -- see install_lib.py for details, as125# these are duplicated from there (but only install_lib does126# anything with them).127('compile', 'c', "compile .py to .pyc [default]"),128('no-compile', None, "don't compile .py files"),129('optimize=', 'O',130"also compile with optimization: -O1 for \"python -O\", "131"-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),132133# Miscellaneous control options134('force', 'f',135"force installation (overwrite any existing files)"),136('skip-build', None,137"skip rebuilding everything (for testing/debugging)"),138139# Where to install documentation (eventually!)140#('doc-format=', None, "format of documentation to generate"),141#('install-man=', None, "directory for Unix man pages"),142#('install-html=', None, "directory for HTML documentation"),143#('install-info=', None, "directory for GNU info files"),144145('record=', None,146"filename in which to record list of installed files"),147]148149boolean_options = ['compile', 'force', 'skip-build']150151if HAS_USER_SITE:152user_options.append(('user', None,153"install in user site-package '%s'" % USER_SITE))154boolean_options.append('user')155156negative_opt = {'no-compile' : 'compile'}157158159def initialize_options(self):160"""Initializes options."""161# High-level options: these select both an installation base162# and scheme.163self.prefix = None164self.exec_prefix = None165self.home = None166self.user = 0167168# These select only the installation base; it's up to the user to169# specify the installation scheme (currently, that means supplying170# the --install-{platlib,purelib,scripts,data} options).171self.install_base = None172self.install_platbase = None173self.root = None174175# These options are the actual installation directories; if not176# supplied by the user, they are filled in using the installation177# scheme implied by prefix/exec-prefix/home and the contents of178# that installation scheme.179self.install_purelib = None # for pure module distributions180self.install_platlib = None # non-pure (dists w/ extensions)181self.install_headers = None # for C/C++ headers182self.install_lib = None # set to either purelib or platlib183self.install_scripts = None184self.install_data = None185self.install_userbase = USER_BASE186self.install_usersite = USER_SITE187188self.compile = None189self.optimize = None190191# Deprecated192# These two are for putting non-packagized distributions into their193# own directory and creating a .pth file if it makes sense.194# 'extra_path' comes from the setup file; 'install_path_file' can195# be turned off if it makes no sense to install a .pth file. (But196# better to install it uselessly than to guess wrong and not197# install it when it's necessary and would be used!) Currently,198# 'install_path_file' is always true unless some outsider meddles199# with it.200self.extra_path = None201self.install_path_file = 1202203# 'force' forces installation, even if target files are not204# out-of-date. 'skip_build' skips running the "build" command,205# handy if you know it's not necessary. 'warn_dir' (which is *not*206# a user option, it's just there so the bdist_* commands can turn207# it off) determines whether we warn about installing to a208# directory not in sys.path.209self.force = 0210self.skip_build = 0211self.warn_dir = 1212213# These are only here as a conduit from the 'build' command to the214# 'install_*' commands that do the real work. ('build_base' isn't215# actually used anywhere, but it might be useful in future.) They216# are not user options, because if the user told the install217# command where the build directory is, that wouldn't affect the218# build command.219self.build_base = None220self.build_lib = None221222# Not defined yet because we don't know anything about223# documentation yet.224#self.install_man = None225#self.install_html = None226#self.install_info = None227228self.record = None229230231# -- Option finalizing methods -------------------------------------232# (This is rather more involved than for most commands,233# because this is where the policy for installing third-234# party Python modules on various platforms given a wide235# array of user input is decided. Yes, it's quite complex!)236237def finalize_options(self):238"""Finalizes options."""239# This method (and its helpers, like 'finalize_unix()',240# 'finalize_other()', and 'select_scheme()') is where the default241# installation directories for modules, extension modules, and242# anything else we care to install from a Python module243# distribution. Thus, this code makes a pretty important policy244# statement about how third-party stuff is added to a Python245# installation! Note that the actual work of installation is done246# by the relatively simple 'install_*' commands; they just take247# their orders from the installation directory options determined248# here.249250# Check for errors/inconsistencies in the options; first, stuff251# that's wrong on any platform.252253if ((self.prefix or self.exec_prefix or self.home) and254(self.install_base or self.install_platbase)):255raise DistutilsOptionError(256"must supply either prefix/exec-prefix/home or " +257"install-base/install-platbase -- not both")258259if self.home and (self.prefix or self.exec_prefix):260raise DistutilsOptionError(261"must supply either home or prefix/exec-prefix -- not both")262263if self.user and (self.prefix or self.exec_prefix or self.home or264self.install_base or self.install_platbase):265raise DistutilsOptionError("can't combine user with prefix, "266"exec_prefix/home, or install_(plat)base")267268# Next, stuff that's wrong (or dubious) only on certain platforms.269if os.name != "posix":270if self.exec_prefix:271self.warn("exec-prefix option ignored on this platform")272self.exec_prefix = None273274# Now the interesting logic -- so interesting that we farm it out275# to other methods. The goal of these methods is to set the final276# values for the install_{lib,scripts,data,...} options, using as277# input a heady brew of prefix, exec_prefix, home, install_base,278# install_platbase, user-supplied versions of279# install_{purelib,platlib,lib,scripts,data,...}, and the280# INSTALL_SCHEME dictionary above. Phew!281282self.dump_dirs("pre-finalize_{unix,other}")283284if os.name == 'posix':285self.finalize_unix()286else:287self.finalize_other()288289self.dump_dirs("post-finalize_{unix,other}()")290291# Expand configuration variables, tilde, etc. in self.install_base292# and self.install_platbase -- that way, we can use $base or293# $platbase in the other installation directories and not worry294# about needing recursive variable expansion (shudder).295296py_version = sys.version.split()[0]297(prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')298try:299abiflags = sys.abiflags300except AttributeError:301# sys.abiflags may not be defined on all platforms.302abiflags = ''303self.config_vars = {'dist_name': self.distribution.get_name(),304'dist_version': self.distribution.get_version(),305'dist_fullname': self.distribution.get_fullname(),306'py_version': py_version,307'py_version_short': '%d.%d' % sys.version_info[:2],308'py_version_nodot': '%d%d' % sys.version_info[:2],309'sys_prefix': prefix,310'prefix': prefix,311'sys_exec_prefix': exec_prefix,312'exec_prefix': exec_prefix,313'abiflags': abiflags,314'platlibdir': getattr(sys, 'platlibdir', 'lib'),315}316317if HAS_USER_SITE:318self.config_vars['userbase'] = self.install_userbase319self.config_vars['usersite'] = self.install_usersite320321self.expand_basedirs()322323self.dump_dirs("post-expand_basedirs()")324325# Now define config vars for the base directories so we can expand326# everything else.327self.config_vars['base'] = self.install_base328self.config_vars['platbase'] = self.install_platbase329330if DEBUG:331from pprint import pprint332print("config vars:")333pprint(self.config_vars)334335# Expand "~" and configuration variables in the installation336# directories.337self.expand_dirs()338339self.dump_dirs("post-expand_dirs()")340341# Create directories in the home dir:342if self.user:343self.create_home_path()344345# Pick the actual directory to install all modules to: either346# install_purelib or install_platlib, depending on whether this347# module distribution is pure or not. Of course, if the user348# already specified install_lib, use their selection.349if self.install_lib is None:350if self.distribution.ext_modules: # has extensions: non-pure351self.install_lib = self.install_platlib352else:353self.install_lib = self.install_purelib354355356# Convert directories from Unix /-separated syntax to the local357# convention.358self.convert_paths('lib', 'purelib', 'platlib',359'scripts', 'data', 'headers',360'userbase', 'usersite')361362# Deprecated363# Well, we're not actually fully completely finalized yet: we still364# have to deal with 'extra_path', which is the hack for allowing365# non-packagized module distributions (hello, Numerical Python!) to366# get their own directories.367self.handle_extra_path()368self.install_libbase = self.install_lib # needed for .pth file369self.install_lib = os.path.join(self.install_lib, self.extra_dirs)370371# If a new root directory was supplied, make all the installation372# dirs relative to it.373if self.root is not None:374self.change_roots('libbase', 'lib', 'purelib', 'platlib',375'scripts', 'data', 'headers')376377self.dump_dirs("after prepending root")378379# Find out the build directories, ie. where to install from.380self.set_undefined_options('build',381('build_base', 'build_base'),382('build_lib', 'build_lib'))383384# Punt on doc directories for now -- after all, we're punting on385# documentation completely!386387def dump_dirs(self, msg):388"""Dumps the list of user options."""389if not DEBUG:390return391from distutils.fancy_getopt import longopt_xlate392log.debug(msg + ":")393for opt in self.user_options:394opt_name = opt[0]395if opt_name[-1] == "=":396opt_name = opt_name[0:-1]397if opt_name in self.negative_opt:398opt_name = self.negative_opt[opt_name]399opt_name = opt_name.translate(longopt_xlate)400val = not getattr(self, opt_name)401else:402opt_name = opt_name.translate(longopt_xlate)403val = getattr(self, opt_name)404log.debug(" %s: %s", opt_name, val)405406def finalize_unix(self):407"""Finalizes options for posix platforms."""408if self.install_base is not None or self.install_platbase is not None:409if ((self.install_lib is None and410self.install_purelib is None and411self.install_platlib is None) or412self.install_headers is None or413self.install_scripts is None or414self.install_data is None):415raise DistutilsOptionError(416"install-base or install-platbase supplied, but "417"installation scheme is incomplete")418return419420if self.user:421if self.install_userbase is None:422raise DistutilsPlatformError(423"User base directory is not specified")424self.install_base = self.install_platbase = self.install_userbase425self.select_scheme("unix_user")426elif self.home is not None:427self.install_base = self.install_platbase = self.home428self.select_scheme("unix_home")429else:430if self.prefix is None:431if self.exec_prefix is not None:432raise DistutilsOptionError(433"must not supply exec-prefix without prefix")434435self.prefix = os.path.normpath(sys.prefix)436self.exec_prefix = os.path.normpath(sys.exec_prefix)437438else:439if self.exec_prefix is None:440self.exec_prefix = self.prefix441442self.install_base = self.prefix443self.install_platbase = self.exec_prefix444self.select_scheme("unix_prefix")445446def finalize_other(self):447"""Finalizes options for non-posix platforms"""448if self.user:449if self.install_userbase is None:450raise DistutilsPlatformError(451"User base directory is not specified")452self.install_base = self.install_platbase = self.install_userbase453self.select_scheme(os.name + "_user")454elif self.home is not None:455self.install_base = self.install_platbase = self.home456self.select_scheme("unix_home")457else:458if self.prefix is None:459self.prefix = os.path.normpath(sys.prefix)460461self.install_base = self.install_platbase = self.prefix462try:463self.select_scheme(os.name)464except KeyError:465raise DistutilsPlatformError(466"I don't know how to install stuff on '%s'" % os.name)467468def select_scheme(self, name):469"""Sets the install directories by applying the install schemes."""470# it's the caller's problem if they supply a bad name!471if (hasattr(sys, 'pypy_version_info') and472not name.endswith(('_user', '_home'))):473if os.name == 'nt':474name = 'pypy_nt'475else:476name = 'pypy'477scheme = INSTALL_SCHEMES[name]478for key in SCHEME_KEYS:479attrname = 'install_' + key480if getattr(self, attrname) is None:481setattr(self, attrname, scheme[key])482483def _expand_attrs(self, attrs):484for attr in attrs:485val = getattr(self, attr)486if val is not None:487if os.name == 'posix' or os.name == 'nt':488val = os.path.expanduser(val)489val = subst_vars(val, self.config_vars)490setattr(self, attr, val)491492def expand_basedirs(self):493"""Calls `os.path.expanduser` on install_base, install_platbase and494root."""495self._expand_attrs(['install_base', 'install_platbase', 'root'])496497def expand_dirs(self):498"""Calls `os.path.expanduser` on install dirs."""499self._expand_attrs(['install_purelib', 'install_platlib',500'install_lib', 'install_headers',501'install_scripts', 'install_data',])502503def convert_paths(self, *names):504"""Call `convert_path` over `names`."""505for name in names:506attr = "install_" + name507setattr(self, attr, convert_path(getattr(self, attr)))508509def handle_extra_path(self):510"""Set `path_file` and `extra_dirs` using `extra_path`."""511if self.extra_path is None:512self.extra_path = self.distribution.extra_path513514if self.extra_path is not None:515log.warn(516"Distribution option extra_path is deprecated. "517"See issue27919 for details."518)519if isinstance(self.extra_path, str):520self.extra_path = self.extra_path.split(',')521522if len(self.extra_path) == 1:523path_file = extra_dirs = self.extra_path[0]524elif len(self.extra_path) == 2:525path_file, extra_dirs = self.extra_path526else:527raise DistutilsOptionError(528"'extra_path' option must be a list, tuple, or "529"comma-separated string with 1 or 2 elements")530531# convert to local form in case Unix notation used (as it532# should be in setup scripts)533extra_dirs = convert_path(extra_dirs)534else:535path_file = None536extra_dirs = ''537538# XXX should we warn if path_file and not extra_dirs? (in which539# case the path file would be harmless but pointless)540self.path_file = path_file541self.extra_dirs = extra_dirs542543def change_roots(self, *names):544"""Change the install directories pointed by name using root."""545for name in names:546attr = "install_" + name547setattr(self, attr, change_root(self.root, getattr(self, attr)))548549def create_home_path(self):550"""Create directories under ~."""551if not self.user:552return553home = convert_path(os.path.expanduser("~"))554for name, path in self.config_vars.items():555if path.startswith(home) and not os.path.isdir(path):556self.debug_print("os.makedirs('%s', 0o700)" % path)557os.makedirs(path, 0o700)558559# -- Command execution methods -------------------------------------560561def run(self):562"""Runs the command."""563# Obviously have to build before we can install564if not self.skip_build:565self.run_command('build')566# If we built for any other platform, we can't install.567build_plat = self.distribution.get_command_obj('build').plat_name568# check warn_dir - it is a clue that the 'install' is happening569# internally, and not to sys.path, so we don't check the platform570# matches what we are running.571if self.warn_dir and build_plat != get_platform():572raise DistutilsPlatformError("Can't install when "573"cross-compiling")574575# Run all sub-commands (at least those that need to be run)576for cmd_name in self.get_sub_commands():577self.run_command(cmd_name)578579if self.path_file:580self.create_path_file()581582# write list of installed files, if requested.583if self.record:584outputs = self.get_outputs()585if self.root: # strip any package prefix586root_len = len(self.root)587for counter in range(len(outputs)):588outputs[counter] = outputs[counter][root_len:]589self.execute(write_file,590(self.record, outputs),591"writing list of installed files to '%s'" %592self.record)593594sys_path = map(os.path.normpath, sys.path)595sys_path = map(os.path.normcase, sys_path)596install_lib = os.path.normcase(os.path.normpath(self.install_lib))597if (self.warn_dir and598not (self.path_file and self.install_path_file) and599install_lib not in sys_path):600log.debug(("modules installed to '%s', which is not in "601"Python's module search path (sys.path) -- "602"you'll have to change the search path yourself"),603self.install_lib)604605def create_path_file(self):606"""Creates the .pth file"""607filename = os.path.join(self.install_libbase,608self.path_file + ".pth")609if self.install_path_file:610self.execute(write_file,611(filename, [self.extra_dirs]),612"creating %s" % filename)613else:614self.warn("path file '%s' not created" % filename)615616617# -- Reporting methods ---------------------------------------------618619def get_outputs(self):620"""Assembles the outputs of all the sub-commands."""621outputs = []622for cmd_name in self.get_sub_commands():623cmd = self.get_finalized_command(cmd_name)624# Add the contents of cmd.get_outputs(), ensuring625# that outputs doesn't contain duplicate entries626for filename in cmd.get_outputs():627if filename not in outputs:628outputs.append(filename)629630if self.path_file and self.install_path_file:631outputs.append(os.path.join(self.install_libbase,632self.path_file + ".pth"))633634return outputs635636def get_inputs(self):637"""Returns the inputs of all the sub-commands"""638# XXX gee, this looks familiar ;-(639inputs = []640for cmd_name in self.get_sub_commands():641cmd = self.get_finalized_command(cmd_name)642inputs.extend(cmd.get_inputs())643644return inputs645646# -- Predicates for sub-command list -------------------------------647648def has_lib(self):649"""Returns true if the current distribution has any Python650modules to install."""651return (self.distribution.has_pure_modules() or652self.distribution.has_ext_modules())653654def has_headers(self):655"""Returns true if the current distribution has any headers to656install."""657return self.distribution.has_headers()658659def has_scripts(self):660"""Returns true if the current distribution has any scripts to.661install."""662return self.distribution.has_scripts()663664def has_data(self):665"""Returns true if the current distribution has any data to.666install."""667return self.distribution.has_data_files()668669# 'sub_commands': a list of commands this command might have to run to670# get its work done. See cmd.py for more info.671sub_commands = [('install_lib', has_lib),672('install_headers', has_headers),673('install_scripts', has_scripts),674('install_data', has_data),675('install_egg_info', lambda self:True),676]677678679