Path: blob/main/test/lib/python3.9/site-packages/setuptools/_distutils/dist.py
4799 views
"""distutils.dist12Provides the Distribution class, which represents the module distribution3being built/installed/distributed.4"""56import sys7import os8import re9from email import message_from_file1011try:12import warnings13except ImportError:14warnings = None1516from distutils.errors import *17from distutils.fancy_getopt import FancyGetopt, translate_longopt18from distutils.util import check_environ, strtobool, rfc822_escape19from distutils import log20from distutils.debug import DEBUG2122# Regex to define acceptable Distutils command names. This is not *quite*23# the same as a Python NAME -- I don't allow leading underscores. The fact24# that they're very similar is no coincidence; the default naming scheme is25# to look for a Python module named after the command.26command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')272829def _ensure_list(value, fieldname):30if isinstance(value, str):31# a string containing comma separated values is okay. It will32# be converted to a list by Distribution.finalize_options().33pass34elif not isinstance(value, list):35# passing a tuple or an iterator perhaps, warn and convert36typename = type(value).__name__37msg = "Warning: '{fieldname}' should be a list, got type '{typename}'"38msg = msg.format(**locals())39log.log(log.WARN, msg)40value = list(value)41return value424344class Distribution:45"""The core of the Distutils. Most of the work hiding behind 'setup'46is really done within a Distribution instance, which farms the work out47to the Distutils commands specified on the command line.4849Setup scripts will almost never instantiate Distribution directly,50unless the 'setup()' function is totally inadequate to their needs.51However, it is conceivable that a setup script might wish to subclass52Distribution for some specialized purpose, and then pass the subclass53to 'setup()' as the 'distclass' keyword argument. If so, it is54necessary to respect the expectations that 'setup' has of Distribution.55See the code for 'setup()', in core.py, for details.56"""5758# 'global_options' describes the command-line options that may be59# supplied to the setup script prior to any actual commands.60# Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of61# these global options. This list should be kept to a bare minimum,62# since every global option is also valid as a command option -- and we63# don't want to pollute the commands with too many options that they64# have minimal control over.65# The fourth entry for verbose means that it can be repeated.66global_options = [67('verbose', 'v', "run verbosely (default)", 1),68('quiet', 'q', "run quietly (turns verbosity off)"),69('dry-run', 'n', "don't actually do anything"),70('help', 'h', "show detailed help message"),71('no-user-cfg', None,72'ignore pydistutils.cfg in your home directory'),73]7475# 'common_usage' is a short (2-3 line) string describing the common76# usage of the setup script.77common_usage = """\78Common commands: (see '--help-commands' for more)7980setup.py build will build the package underneath 'build/'81setup.py install will install the package82"""8384# options that are not propagated to the commands85display_options = [86('help-commands', None,87"list all available commands"),88('name', None,89"print package name"),90('version', 'V',91"print package version"),92('fullname', None,93"print <package name>-<version>"),94('author', None,95"print the author's name"),96('author-email', None,97"print the author's email address"),98('maintainer', None,99"print the maintainer's name"),100('maintainer-email', None,101"print the maintainer's email address"),102('contact', None,103"print the maintainer's name if known, else the author's"),104('contact-email', None,105"print the maintainer's email address if known, else the author's"),106('url', None,107"print the URL for this package"),108('license', None,109"print the license of the package"),110('licence', None,111"alias for --license"),112('description', None,113"print the package description"),114('long-description', None,115"print the long package description"),116('platforms', None,117"print the list of platforms"),118('classifiers', None,119"print the list of classifiers"),120('keywords', None,121"print the list of keywords"),122('provides', None,123"print the list of packages/modules provided"),124('requires', None,125"print the list of packages/modules required"),126('obsoletes', None,127"print the list of packages/modules made obsolete")128]129display_option_names = [translate_longopt(x[0]) for x in display_options]130131# negative options are options that exclude other options132negative_opt = {'quiet': 'verbose'}133134# -- Creation/initialization methods -------------------------------135136def __init__(self, attrs=None):137"""Construct a new Distribution instance: initialize all the138attributes of a Distribution, and then use 'attrs' (a dictionary139mapping attribute names to values) to assign some of those140attributes their "real" values. (Any attributes not mentioned in141'attrs' will be assigned to some null value: 0, None, an empty list142or dictionary, etc.) Most importantly, initialize the143'command_obj' attribute to the empty dictionary; this will be144filled in with real command objects by 'parse_command_line()'.145"""146147# Default values for our command-line options148self.verbose = 1149self.dry_run = 0150self.help = 0151for attr in self.display_option_names:152setattr(self, attr, 0)153154# Store the distribution meta-data (name, version, author, and so155# forth) in a separate object -- we're getting to have enough156# information here (and enough command-line options) that it's157# worth it. Also delegate 'get_XXX()' methods to the 'metadata'158# object in a sneaky and underhanded (but efficient!) way.159self.metadata = DistributionMetadata()160for basename in self.metadata._METHOD_BASENAMES:161method_name = "get_" + basename162setattr(self, method_name, getattr(self.metadata, method_name))163164# 'cmdclass' maps command names to class objects, so we165# can 1) quickly figure out which class to instantiate when166# we need to create a new command object, and 2) have a way167# for the setup script to override command classes168self.cmdclass = {}169170# 'command_packages' is a list of packages in which commands171# are searched for. The factory for command 'foo' is expected172# to be named 'foo' in the module 'foo' in one of the packages173# named here. This list is searched from the left; an error174# is raised if no named package provides the command being175# searched for. (Always access using get_command_packages().)176self.command_packages = None177178# 'script_name' and 'script_args' are usually set to sys.argv[0]179# and sys.argv[1:], but they can be overridden when the caller is180# not necessarily a setup script run from the command-line.181self.script_name = None182self.script_args = None183184# 'command_options' is where we store command options between185# parsing them (from config files, the command-line, etc.) and when186# they are actually needed -- ie. when the command in question is187# instantiated. It is a dictionary of dictionaries of 2-tuples:188# command_options = { command_name : { option : (source, value) } }189self.command_options = {}190191# 'dist_files' is the list of (command, pyversion, file) that192# have been created by any dist commands run so far. This is193# filled regardless of whether the run is dry or not. pyversion194# gives sysconfig.get_python_version() if the dist file is195# specific to a Python version, 'any' if it is good for all196# Python versions on the target platform, and '' for a source197# file. pyversion should not be used to specify minimum or198# maximum required Python versions; use the metainfo for that199# instead.200self.dist_files = []201202# These options are really the business of various commands, rather203# than of the Distribution itself. We provide aliases for them in204# Distribution as a convenience to the developer.205self.packages = None206self.package_data = {}207self.package_dir = None208self.py_modules = None209self.libraries = None210self.headers = None211self.ext_modules = None212self.ext_package = None213self.include_dirs = None214self.extra_path = None215self.scripts = None216self.data_files = None217self.password = ''218219# And now initialize bookkeeping stuff that can't be supplied by220# the caller at all. 'command_obj' maps command names to221# Command instances -- that's how we enforce that every command222# class is a singleton.223self.command_obj = {}224225# 'have_run' maps command names to boolean values; it keeps track226# of whether we have actually run a particular command, to make it227# cheap to "run" a command whenever we think we might need to -- if228# it's already been done, no need for expensive filesystem229# operations, we just check the 'have_run' dictionary and carry on.230# It's only safe to query 'have_run' for a command class that has231# been instantiated -- a false value will be inserted when the232# command object is created, and replaced with a true value when233# the command is successfully run. Thus it's probably best to use234# '.get()' rather than a straight lookup.235self.have_run = {}236237# Now we'll use the attrs dictionary (ultimately, keyword args from238# the setup script) to possibly override any or all of these239# distribution options.240241if attrs:242# Pull out the set of command options and work on them243# specifically. Note that this order guarantees that aliased244# command options will override any supplied redundantly245# through the general options dictionary.246options = attrs.get('options')247if options is not None:248del attrs['options']249for (command, cmd_options) in options.items():250opt_dict = self.get_option_dict(command)251for (opt, val) in cmd_options.items():252opt_dict[opt] = ("setup script", val)253254if 'licence' in attrs:255attrs['license'] = attrs['licence']256del attrs['licence']257msg = "'licence' distribution option is deprecated; use 'license'"258if warnings is not None:259warnings.warn(msg)260else:261sys.stderr.write(msg + "\n")262263# Now work on the rest of the attributes. Any attribute that's264# not already defined is invalid!265for (key, val) in attrs.items():266if hasattr(self.metadata, "set_" + key):267getattr(self.metadata, "set_" + key)(val)268elif hasattr(self.metadata, key):269setattr(self.metadata, key, val)270elif hasattr(self, key):271setattr(self, key, val)272else:273msg = "Unknown distribution option: %s" % repr(key)274warnings.warn(msg)275276# no-user-cfg is handled before other command line args277# because other args override the config files, and this278# one is needed before we can load the config files.279# If attrs['script_args'] wasn't passed, assume false.280#281# This also make sure we just look at the global options282self.want_user_cfg = True283284if self.script_args is not None:285for arg in self.script_args:286if not arg.startswith('-'):287break288if arg == '--no-user-cfg':289self.want_user_cfg = False290break291292self.finalize_options()293294def get_option_dict(self, command):295"""Get the option dictionary for a given command. If that296command's option dictionary hasn't been created yet, then create it297and return the new dictionary; otherwise, return the existing298option dictionary.299"""300dict = self.command_options.get(command)301if dict is None:302dict = self.command_options[command] = {}303return dict304305def dump_option_dicts(self, header=None, commands=None, indent=""):306from pprint import pformat307308if commands is None: # dump all command option dicts309commands = sorted(self.command_options.keys())310311if header is not None:312self.announce(indent + header)313indent = indent + " "314315if not commands:316self.announce(indent + "no commands known yet")317return318319for cmd_name in commands:320opt_dict = self.command_options.get(cmd_name)321if opt_dict is None:322self.announce(indent +323"no option dict for '%s' command" % cmd_name)324else:325self.announce(indent +326"option dict for '%s' command:" % cmd_name)327out = pformat(opt_dict)328for line in out.split('\n'):329self.announce(indent + " " + line)330331# -- Config file finding/parsing methods ---------------------------332333def find_config_files(self):334"""Find as many configuration files as should be processed for this335platform, and return a list of filenames in the order in which they336should be parsed. The filenames returned are guaranteed to exist337(modulo nasty race conditions).338339There are three possible config files: distutils.cfg in the340Distutils installation directory (ie. where the top-level341Distutils __inst__.py file lives), a file in the user's home342directory named .pydistutils.cfg on Unix and pydistutils.cfg343on Windows/Mac; and setup.cfg in the current directory.344345The file in the user's home directory can be disabled with the346--no-user-cfg option.347"""348files = []349check_environ()350351# Where to look for the system-wide Distutils config file352sys_dir = os.path.dirname(sys.modules['distutils'].__file__)353354# Look for the system config file355sys_file = os.path.join(sys_dir, "distutils.cfg")356if os.path.isfile(sys_file):357files.append(sys_file)358359# What to call the per-user config file360if os.name == 'posix':361user_filename = ".pydistutils.cfg"362else:363user_filename = "pydistutils.cfg"364365# And look for the user config file366if self.want_user_cfg:367user_file = os.path.join(os.path.expanduser('~'), user_filename)368if os.path.isfile(user_file):369files.append(user_file)370371# All platforms support local setup.cfg372local_file = "setup.cfg"373if os.path.isfile(local_file):374files.append(local_file)375376if DEBUG:377self.announce("using config files: %s" % ', '.join(files))378379return files380381def parse_config_files(self, filenames=None):382from configparser import ConfigParser383384# Ignore install directory options if we have a venv385if sys.prefix != sys.base_prefix:386ignore_options = [387'install-base', 'install-platbase', 'install-lib',388'install-platlib', 'install-purelib', 'install-headers',389'install-scripts', 'install-data', 'prefix', 'exec-prefix',390'home', 'user', 'root']391else:392ignore_options = []393394ignore_options = frozenset(ignore_options)395396if filenames is None:397filenames = self.find_config_files()398399if DEBUG:400self.announce("Distribution.parse_config_files():")401402parser = ConfigParser()403for filename in filenames:404if DEBUG:405self.announce(" reading %s" % filename)406parser.read(filename)407for section in parser.sections():408options = parser.options(section)409opt_dict = self.get_option_dict(section)410411for opt in options:412if opt != '__name__' and opt not in ignore_options:413val = parser.get(section,opt)414opt = opt.replace('-', '_')415opt_dict[opt] = (filename, val)416417# Make the ConfigParser forget everything (so we retain418# the original filenames that options come from)419parser.__init__()420421# If there was a "global" section in the config file, use it422# to set Distribution options.423424if 'global' in self.command_options:425for (opt, (src, val)) in self.command_options['global'].items():426alias = self.negative_opt.get(opt)427try:428if alias:429setattr(self, alias, not strtobool(val))430elif opt in ('verbose', 'dry_run'): # ugh!431setattr(self, opt, strtobool(val))432else:433setattr(self, opt, val)434except ValueError as msg:435raise DistutilsOptionError(msg)436437# -- Command-line parsing methods ----------------------------------438439def parse_command_line(self):440"""Parse the setup script's command line, taken from the441'script_args' instance attribute (which defaults to 'sys.argv[1:]'442-- see 'setup()' in core.py). This list is first processed for443"global options" -- options that set attributes of the Distribution444instance. Then, it is alternately scanned for Distutils commands445and options for that command. Each new command terminates the446options for the previous command. The allowed options for a447command are determined by the 'user_options' attribute of the448command class -- thus, we have to be able to load command classes449in order to parse the command line. Any error in that 'options'450attribute raises DistutilsGetoptError; any error on the451command-line raises DistutilsArgError. If no Distutils commands452were found on the command line, raises DistutilsArgError. Return453true if command-line was successfully parsed and we should carry454on with executing commands; false if no errors but we shouldn't455execute commands (currently, this only happens if user asks for456help).457"""458#459# We now have enough information to show the Macintosh dialog460# that allows the user to interactively specify the "command line".461#462toplevel_options = self._get_toplevel_options()463464# We have to parse the command line a bit at a time -- global465# options, then the first command, then its options, and so on --466# because each command will be handled by a different class, and467# the options that are valid for a particular class aren't known468# until we have loaded the command class, which doesn't happen469# until we know what the command is.470471self.commands = []472parser = FancyGetopt(toplevel_options + self.display_options)473parser.set_negative_aliases(self.negative_opt)474parser.set_aliases({'licence': 'license'})475args = parser.getopt(args=self.script_args, object=self)476option_order = parser.get_option_order()477log.set_verbosity(self.verbose)478479# for display options we return immediately480if self.handle_display_options(option_order):481return482while args:483args = self._parse_command_opts(parser, args)484if args is None: # user asked for help (and got it)485return486487# Handle the cases of --help as a "global" option, ie.488# "setup.py --help" and "setup.py --help command ...". For the489# former, we show global options (--verbose, --dry-run, etc.)490# and display-only options (--name, --version, etc.); for the491# latter, we omit the display-only options and show help for492# each command listed on the command line.493if self.help:494self._show_help(parser,495display_options=len(self.commands) == 0,496commands=self.commands)497return498499# Oops, no commands found -- an end-user error500if not self.commands:501raise DistutilsArgError("no commands supplied")502503# All is well: return true504return True505506def _get_toplevel_options(self):507"""Return the non-display options recognized at the top level.508509This includes options that are recognized *only* at the top510level as well as options recognized for commands.511"""512return self.global_options + [513("command-packages=", None,514"list of packages that provide distutils commands"),515]516517def _parse_command_opts(self, parser, args):518"""Parse the command-line options for a single command.519'parser' must be a FancyGetopt instance; 'args' must be the list520of arguments, starting with the current command (whose options521we are about to parse). Returns a new version of 'args' with522the next command at the front of the list; will be the empty523list if there are no more commands on the command line. Returns524None if the user asked for help on this command.525"""526# late import because of mutual dependence between these modules527from distutils.cmd import Command528529# Pull the current command from the head of the command line530command = args[0]531if not command_re.match(command):532raise SystemExit("invalid command name '%s'" % command)533self.commands.append(command)534535# Dig up the command class that implements this command, so we536# 1) know that it's a valid command, and 2) know which options537# it takes.538try:539cmd_class = self.get_command_class(command)540except DistutilsModuleError as msg:541raise DistutilsArgError(msg)542543# Require that the command class be derived from Command -- want544# to be sure that the basic "command" interface is implemented.545if not issubclass(cmd_class, Command):546raise DistutilsClassError(547"command class %s must subclass Command" % cmd_class)548549# Also make sure that the command object provides a list of its550# known options.551if not (hasattr(cmd_class, 'user_options') and552isinstance(cmd_class.user_options, list)):553msg = ("command class %s must provide "554"'user_options' attribute (a list of tuples)")555raise DistutilsClassError(msg % cmd_class)556557# If the command class has a list of negative alias options,558# merge it in with the global negative aliases.559negative_opt = self.negative_opt560if hasattr(cmd_class, 'negative_opt'):561negative_opt = negative_opt.copy()562negative_opt.update(cmd_class.negative_opt)563564# Check for help_options in command class. They have a different565# format (tuple of four) so we need to preprocess them here.566if (hasattr(cmd_class, 'help_options') and567isinstance(cmd_class.help_options, list)):568help_options = fix_help_options(cmd_class.help_options)569else:570help_options = []571572# All commands support the global options too, just by adding573# in 'global_options'.574parser.set_option_table(self.global_options +575cmd_class.user_options +576help_options)577parser.set_negative_aliases(negative_opt)578(args, opts) = parser.getopt(args[1:])579if hasattr(opts, 'help') and opts.help:580self._show_help(parser, display_options=0, commands=[cmd_class])581return582583if (hasattr(cmd_class, 'help_options') and584isinstance(cmd_class.help_options, list)):585help_option_found=0586for (help_option, short, desc, func) in cmd_class.help_options:587if hasattr(opts, parser.get_attr_name(help_option)):588help_option_found=1589if callable(func):590func()591else:592raise DistutilsClassError(593"invalid help function %r for help option '%s': "594"must be a callable object (function, etc.)"595% (func, help_option))596597if help_option_found:598return599600# Put the options from the command-line into their official601# holding pen, the 'command_options' dictionary.602opt_dict = self.get_option_dict(command)603for (name, value) in vars(opts).items():604opt_dict[name] = ("command line", value)605606return args607608def finalize_options(self):609"""Set final values for all the options on the Distribution610instance, analogous to the .finalize_options() method of Command611objects.612"""613for attr in ('keywords', 'platforms'):614value = getattr(self.metadata, attr)615if value is None:616continue617if isinstance(value, str):618value = [elm.strip() for elm in value.split(',')]619setattr(self.metadata, attr, value)620621def _show_help(self, parser, global_options=1, display_options=1,622commands=[]):623"""Show help for the setup script command-line in the form of624several lists of command-line options. 'parser' should be a625FancyGetopt instance; do not expect it to be returned in the626same state, as its option table will be reset to make it627generate the correct help text.628629If 'global_options' is true, lists the global options:630--verbose, --dry-run, etc. If 'display_options' is true, lists631the "display-only" options: --name, --version, etc. Finally,632lists per-command help for every command name or command class633in 'commands'.634"""635# late import because of mutual dependence between these modules636from distutils.core import gen_usage637from distutils.cmd import Command638639if global_options:640if display_options:641options = self._get_toplevel_options()642else:643options = self.global_options644parser.set_option_table(options)645parser.print_help(self.common_usage + "\nGlobal options:")646print('')647648if display_options:649parser.set_option_table(self.display_options)650parser.print_help(651"Information display options (just display " +652"information, ignore any commands)")653print('')654655for command in self.commands:656if isinstance(command, type) and issubclass(command, Command):657klass = command658else:659klass = self.get_command_class(command)660if (hasattr(klass, 'help_options') and661isinstance(klass.help_options, list)):662parser.set_option_table(klass.user_options +663fix_help_options(klass.help_options))664else:665parser.set_option_table(klass.user_options)666parser.print_help("Options for '%s' command:" % klass.__name__)667print('')668669print(gen_usage(self.script_name))670671def handle_display_options(self, option_order):672"""If there were any non-global "display-only" options673(--help-commands or the metadata display options) on the command674line, display the requested info and return true; else return675false.676"""677from distutils.core import gen_usage678679# User just wants a list of commands -- we'll print it out and stop680# processing now (ie. if they ran "setup --help-commands foo bar",681# we ignore "foo bar").682if self.help_commands:683self.print_commands()684print('')685print(gen_usage(self.script_name))686return 1687688# If user supplied any of the "display metadata" options, then689# display that metadata in the order in which the user supplied the690# metadata options.691any_display_options = 0692is_display_option = {}693for option in self.display_options:694is_display_option[option[0]] = 1695696for (opt, val) in option_order:697if val and is_display_option.get(opt):698opt = translate_longopt(opt)699value = getattr(self.metadata, "get_"+opt)()700if opt in ['keywords', 'platforms']:701print(','.join(value))702elif opt in ('classifiers', 'provides', 'requires',703'obsoletes'):704print('\n'.join(value))705else:706print(value)707any_display_options = 1708709return any_display_options710711def print_command_list(self, commands, header, max_length):712"""Print a subset of the list of all commands -- used by713'print_commands()'.714"""715print(header + ":")716717for cmd in commands:718klass = self.cmdclass.get(cmd)719if not klass:720klass = self.get_command_class(cmd)721try:722description = klass.description723except AttributeError:724description = "(no description available)"725726print(" %-*s %s" % (max_length, cmd, description))727728def print_commands(self):729"""Print out a help message listing all available commands with a730description of each. The list is divided into "standard commands"731(listed in distutils.command.__all__) and "extra commands"732(mentioned in self.cmdclass, but not a standard command). The733descriptions come from the command class attribute734'description'.735"""736import distutils.command737std_commands = distutils.command.__all__738is_std = {}739for cmd in std_commands:740is_std[cmd] = 1741742extra_commands = []743for cmd in self.cmdclass.keys():744if not is_std.get(cmd):745extra_commands.append(cmd)746747max_length = 0748for cmd in (std_commands + extra_commands):749if len(cmd) > max_length:750max_length = len(cmd)751752self.print_command_list(std_commands,753"Standard commands",754max_length)755if extra_commands:756print()757self.print_command_list(extra_commands,758"Extra commands",759max_length)760761def get_command_list(self):762"""Get a list of (command, description) tuples.763The list is divided into "standard commands" (listed in764distutils.command.__all__) and "extra commands" (mentioned in765self.cmdclass, but not a standard command). The descriptions come766from the command class attribute 'description'.767"""768# Currently this is only used on Mac OS, for the Mac-only GUI769# Distutils interface (by Jack Jansen)770import distutils.command771std_commands = distutils.command.__all__772is_std = {}773for cmd in std_commands:774is_std[cmd] = 1775776extra_commands = []777for cmd in self.cmdclass.keys():778if not is_std.get(cmd):779extra_commands.append(cmd)780781rv = []782for cmd in (std_commands + extra_commands):783klass = self.cmdclass.get(cmd)784if not klass:785klass = self.get_command_class(cmd)786try:787description = klass.description788except AttributeError:789description = "(no description available)"790rv.append((cmd, description))791return rv792793# -- Command class/object methods ----------------------------------794795def get_command_packages(self):796"""Return a list of packages from which commands are loaded."""797pkgs = self.command_packages798if not isinstance(pkgs, list):799if pkgs is None:800pkgs = ''801pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']802if "distutils.command" not in pkgs:803pkgs.insert(0, "distutils.command")804self.command_packages = pkgs805return pkgs806807def get_command_class(self, command):808"""Return the class that implements the Distutils command named by809'command'. First we check the 'cmdclass' dictionary; if the810command is mentioned there, we fetch the class object from the811dictionary and return it. Otherwise we load the command module812("distutils.command." + command) and fetch the command class from813the module. The loaded class is also stored in 'cmdclass'814to speed future calls to 'get_command_class()'.815816Raises DistutilsModuleError if the expected module could not be817found, or if that module does not define the expected class.818"""819klass = self.cmdclass.get(command)820if klass:821return klass822823for pkgname in self.get_command_packages():824module_name = "%s.%s" % (pkgname, command)825klass_name = command826827try:828__import__(module_name)829module = sys.modules[module_name]830except ImportError:831continue832833try:834klass = getattr(module, klass_name)835except AttributeError:836raise DistutilsModuleError(837"invalid command '%s' (no class '%s' in module '%s')"838% (command, klass_name, module_name))839840self.cmdclass[command] = klass841return klass842843raise DistutilsModuleError("invalid command '%s'" % command)844845def get_command_obj(self, command, create=1):846"""Return the command object for 'command'. Normally this object847is cached on a previous call to 'get_command_obj()'; if no command848object for 'command' is in the cache, then we either create and849return it (if 'create' is true) or return None.850"""851cmd_obj = self.command_obj.get(command)852if not cmd_obj and create:853if DEBUG:854self.announce("Distribution.get_command_obj(): "855"creating '%s' command object" % command)856857klass = self.get_command_class(command)858cmd_obj = self.command_obj[command] = klass(self)859self.have_run[command] = 0860861# Set any options that were supplied in config files862# or on the command line. (NB. support for error863# reporting is lame here: any errors aren't reported864# until 'finalize_options()' is called, which means865# we won't report the source of the error.)866options = self.command_options.get(command)867if options:868self._set_command_options(cmd_obj, options)869870return cmd_obj871872def _set_command_options(self, command_obj, option_dict=None):873"""Set the options for 'command_obj' from 'option_dict'. Basically874this means copying elements of a dictionary ('option_dict') to875attributes of an instance ('command').876877'command_obj' must be a Command instance. If 'option_dict' is not878supplied, uses the standard option dictionary for this command879(from 'self.command_options').880"""881command_name = command_obj.get_command_name()882if option_dict is None:883option_dict = self.get_option_dict(command_name)884885if DEBUG:886self.announce(" setting options for '%s' command:" % command_name)887for (option, (source, value)) in option_dict.items():888if DEBUG:889self.announce(" %s = %s (from %s)" % (option, value,890source))891try:892bool_opts = [translate_longopt(o)893for o in command_obj.boolean_options]894except AttributeError:895bool_opts = []896try:897neg_opt = command_obj.negative_opt898except AttributeError:899neg_opt = {}900901try:902is_string = isinstance(value, str)903if option in neg_opt and is_string:904setattr(command_obj, neg_opt[option], not strtobool(value))905elif option in bool_opts and is_string:906setattr(command_obj, option, strtobool(value))907elif hasattr(command_obj, option):908setattr(command_obj, option, value)909else:910raise DistutilsOptionError(911"error in %s: command '%s' has no such option '%s'"912% (source, command_name, option))913except ValueError as msg:914raise DistutilsOptionError(msg)915916def reinitialize_command(self, command, reinit_subcommands=0):917"""Reinitializes a command to the state it was in when first918returned by 'get_command_obj()': ie., initialized but not yet919finalized. This provides the opportunity to sneak option920values in programmatically, overriding or supplementing921user-supplied values from the config files and command line.922You'll have to re-finalize the command object (by calling923'finalize_options()' or 'ensure_finalized()') before using it for924real.925926'command' should be a command name (string) or command object. If927'reinit_subcommands' is true, also reinitializes the command's928sub-commands, as declared by the 'sub_commands' class attribute (if929it has one). See the "install" command for an example. Only930reinitializes the sub-commands that actually matter, ie. those931whose test predicates return true.932933Returns the reinitialized command object.934"""935from distutils.cmd import Command936if not isinstance(command, Command):937command_name = command938command = self.get_command_obj(command_name)939else:940command_name = command.get_command_name()941942if not command.finalized:943return command944command.initialize_options()945command.finalized = 0946self.have_run[command_name] = 0947self._set_command_options(command)948949if reinit_subcommands:950for sub in command.get_sub_commands():951self.reinitialize_command(sub, reinit_subcommands)952953return command954955# -- Methods that operate on the Distribution ----------------------956957def announce(self, msg, level=log.INFO):958log.log(level, msg)959960def run_commands(self):961"""Run each command that was seen on the setup script command line.962Uses the list of commands found and cache of command objects963created by 'get_command_obj()'.964"""965for cmd in self.commands:966self.run_command(cmd)967968# -- Methods that operate on its Commands --------------------------969970def run_command(self, command):971"""Do whatever it takes to run a command (including nothing at all,972if the command has already been run). Specifically: if we have973already created and run the command named by 'command', return974silently without doing anything. If the command named by 'command'975doesn't even have a command object yet, create one. Then invoke976'run()' on that command object (or an existing one).977"""978# Already been here, done that? then return silently.979if self.have_run.get(command):980return981982log.info("running %s", command)983cmd_obj = self.get_command_obj(command)984cmd_obj.ensure_finalized()985cmd_obj.run()986self.have_run[command] = 1987988# -- Distribution query methods ------------------------------------989990def has_pure_modules(self):991return len(self.packages or self.py_modules or []) > 0992993def has_ext_modules(self):994return self.ext_modules and len(self.ext_modules) > 0995996def has_c_libraries(self):997return self.libraries and len(self.libraries) > 0998999def has_modules(self):1000return self.has_pure_modules() or self.has_ext_modules()10011002def has_headers(self):1003return self.headers and len(self.headers) > 010041005def has_scripts(self):1006return self.scripts and len(self.scripts) > 010071008def has_data_files(self):1009return self.data_files and len(self.data_files) > 010101011def is_pure(self):1012return (self.has_pure_modules() and1013not self.has_ext_modules() and1014not self.has_c_libraries())10151016# -- Metadata query methods ----------------------------------------10171018# If you're looking for 'get_name()', 'get_version()', and so forth,1019# they are defined in a sneaky way: the constructor binds self.get_XXX1020# to self.metadata.get_XXX. The actual code is in the1021# DistributionMetadata class, below.10221023class DistributionMetadata:1024"""Dummy class to hold the distribution meta-data: name, version,1025author, and so forth.1026"""10271028_METHOD_BASENAMES = ("name", "version", "author", "author_email",1029"maintainer", "maintainer_email", "url",1030"license", "description", "long_description",1031"keywords", "platforms", "fullname", "contact",1032"contact_email", "classifiers", "download_url",1033# PEP 3141034"provides", "requires", "obsoletes",1035)10361037def __init__(self, path=None):1038if path is not None:1039self.read_pkg_file(open(path))1040else:1041self.name = None1042self.version = None1043self.author = None1044self.author_email = None1045self.maintainer = None1046self.maintainer_email = None1047self.url = None1048self.license = None1049self.description = None1050self.long_description = None1051self.keywords = None1052self.platforms = None1053self.classifiers = None1054self.download_url = None1055# PEP 3141056self.provides = None1057self.requires = None1058self.obsoletes = None10591060def read_pkg_file(self, file):1061"""Reads the metadata values from a file object."""1062msg = message_from_file(file)10631064def _read_field(name):1065value = msg[name]1066if value and value != "UNKNOWN":1067return value10681069def _read_list(name):1070values = msg.get_all(name, None)1071if values == []:1072return None1073return values10741075metadata_version = msg['metadata-version']1076self.name = _read_field('name')1077self.version = _read_field('version')1078self.description = _read_field('summary')1079# we are filling author only.1080self.author = _read_field('author')1081self.maintainer = None1082self.author_email = _read_field('author-email')1083self.maintainer_email = None1084self.url = _read_field('home-page')1085self.license = _read_field('license')10861087if 'download-url' in msg:1088self.download_url = _read_field('download-url')1089else:1090self.download_url = None10911092self.long_description = _read_field('description')1093self.description = _read_field('summary')10941095if 'keywords' in msg:1096self.keywords = _read_field('keywords').split(',')10971098self.platforms = _read_list('platform')1099self.classifiers = _read_list('classifier')11001101# PEP 314 - these fields only exist in 1.11102if metadata_version == '1.1':1103self.requires = _read_list('requires')1104self.provides = _read_list('provides')1105self.obsoletes = _read_list('obsoletes')1106else:1107self.requires = None1108self.provides = None1109self.obsoletes = None11101111def write_pkg_info(self, base_dir):1112"""Write the PKG-INFO file into the release tree.1113"""1114with open(os.path.join(base_dir, 'PKG-INFO'), 'w',1115encoding='UTF-8') as pkg_info:1116self.write_pkg_file(pkg_info)11171118def write_pkg_file(self, file):1119"""Write the PKG-INFO format data to a file object.1120"""1121version = '1.0'1122if (self.provides or self.requires or self.obsoletes or1123self.classifiers or self.download_url):1124version = '1.1'11251126# required fields1127file.write('Metadata-Version: %s\n' % version)1128file.write('Name: %s\n' % self.get_name())1129file.write('Version: %s\n' % self.get_version())11301131def maybe_write(header, val):1132if val:1133file.write("{}: {}\n".format(header, val))11341135# optional fields1136maybe_write("Summary", self.get_description())1137maybe_write("Home-page", self.get_url())1138maybe_write("Author", self.get_contact())1139maybe_write("Author-email", self.get_contact_email())1140maybe_write("License", self.get_license())1141maybe_write("Download-URL", self.download_url)1142maybe_write("Description", rfc822_escape(self.get_long_description() or ""))1143maybe_write("Keywords", ",".join(self.get_keywords()))11441145self._write_list(file, 'Platform', self.get_platforms())1146self._write_list(file, 'Classifier', self.get_classifiers())11471148# PEP 3141149self._write_list(file, 'Requires', self.get_requires())1150self._write_list(file, 'Provides', self.get_provides())1151self._write_list(file, 'Obsoletes', self.get_obsoletes())11521153def _write_list(self, file, name, values):1154values = values or []1155for value in values:1156file.write('%s: %s\n' % (name, value))11571158# -- Metadata query methods ----------------------------------------11591160def get_name(self):1161return self.name or "UNKNOWN"11621163def get_version(self):1164return self.version or "0.0.0"11651166def get_fullname(self):1167return "%s-%s" % (self.get_name(), self.get_version())11681169def get_author(self):1170return self.author11711172def get_author_email(self):1173return self.author_email11741175def get_maintainer(self):1176return self.maintainer11771178def get_maintainer_email(self):1179return self.maintainer_email11801181def get_contact(self):1182return self.maintainer or self.author11831184def get_contact_email(self):1185return self.maintainer_email or self.author_email11861187def get_url(self):1188return self.url11891190def get_license(self):1191return self.license1192get_licence = get_license11931194def get_description(self):1195return self.description11961197def get_long_description(self):1198return self.long_description11991200def get_keywords(self):1201return self.keywords or []12021203def set_keywords(self, value):1204self.keywords = _ensure_list(value, 'keywords')12051206def get_platforms(self):1207return self.platforms12081209def set_platforms(self, value):1210self.platforms = _ensure_list(value, 'platforms')12111212def get_classifiers(self):1213return self.classifiers or []12141215def set_classifiers(self, value):1216self.classifiers = _ensure_list(value, 'classifiers')12171218def get_download_url(self):1219return self.download_url12201221# PEP 3141222def get_requires(self):1223return self.requires or []12241225def set_requires(self, value):1226import distutils.versionpredicate1227for v in value:1228distutils.versionpredicate.VersionPredicate(v)1229self.requires = list(value)12301231def get_provides(self):1232return self.provides or []12331234def set_provides(self, value):1235value = [v.strip() for v in value]1236for v in value:1237import distutils.versionpredicate1238distutils.versionpredicate.split_provision(v)1239self.provides = value12401241def get_obsoletes(self):1242return self.obsoletes or []12431244def set_obsoletes(self, value):1245import distutils.versionpredicate1246for v in value:1247distutils.versionpredicate.VersionPredicate(v)1248self.obsoletes = list(value)12491250def fix_help_options(options):1251"""Convert a 4-tuple 'help_options' list as found in various command1252classes to the 3-tuple form required by FancyGetopt.1253"""1254new_options = []1255for help_tuple in options:1256new_options.append(help_tuple[0:3])1257return new_options125812591260