Path: blob/main/test/lib/python3.9/site-packages/setuptools/_distutils/cmd.py
4799 views
"""distutils.cmd12Provides the Command class, the base class for the command classes3in the distutils.command package.4"""56import sys, os, re7from distutils.errors import DistutilsOptionError8from distutils import util, dir_util, file_util, archive_util, dep_util9from distutils import log1011class Command:12"""Abstract base class for defining command classes, the "worker bees"13of the Distutils. A useful analogy for command classes is to think of14them as subroutines with local variables called "options". The options15are "declared" in 'initialize_options()' and "defined" (given their16final values, aka "finalized") in 'finalize_options()', both of which17must be defined by every command class. The distinction between the18two is necessary because option values might come from the outside19world (command line, config file, ...), and any options dependent on20other options must be computed *after* these outside influences have21been processed -- hence 'finalize_options()'. The "body" of the22subroutine, where it does all its work based on the values of its23options, is the 'run()' method, which must also be implemented by every24command class.25"""2627# 'sub_commands' formalizes the notion of a "family" of commands,28# eg. "install" as the parent with sub-commands "install_lib",29# "install_headers", etc. The parent of a family of commands30# defines 'sub_commands' as a class attribute; it's a list of31# (command_name : string, predicate : unbound_method | string | None)32# tuples, where 'predicate' is a method of the parent command that33# determines whether the corresponding command is applicable in the34# current situation. (Eg. we "install_headers" is only applicable if35# we have any C header files to install.) If 'predicate' is None,36# that command is always applicable.37#38# 'sub_commands' is usually defined at the *end* of a class, because39# predicates can be unbound methods, so they must already have been40# defined. The canonical example is the "install" command.41sub_commands = []424344# -- Creation/initialization methods -------------------------------4546def __init__(self, dist):47"""Create and initialize a new Command object. Most importantly,48invokes the 'initialize_options()' method, which is the real49initializer and depends on the actual command being50instantiated.51"""52# late import because of mutual dependence between these classes53from distutils.dist import Distribution5455if not isinstance(dist, Distribution):56raise TypeError("dist must be a Distribution instance")57if self.__class__ is Command:58raise RuntimeError("Command is an abstract class")5960self.distribution = dist61self.initialize_options()6263# Per-command versions of the global flags, so that the user can64# customize Distutils' behaviour command-by-command and let some65# commands fall back on the Distribution's behaviour. None means66# "not defined, check self.distribution's copy", while 0 or 1 mean67# false and true (duh). Note that this means figuring out the real68# value of each flag is a touch complicated -- hence "self._dry_run"69# will be handled by __getattr__, below.70# XXX This needs to be fixed.71self._dry_run = None7273# verbose is largely ignored, but needs to be set for74# backwards compatibility (I think)?75self.verbose = dist.verbose7677# Some commands define a 'self.force' option to ignore file78# timestamps, but methods defined *here* assume that79# 'self.force' exists for all commands. So define it here80# just to be safe.81self.force = None8283# The 'help' flag is just used for command-line parsing, so84# none of that complicated bureaucracy is needed.85self.help = 08687# 'finalized' records whether or not 'finalize_options()' has been88# called. 'finalize_options()' itself should not pay attention to89# this flag: it is the business of 'ensure_finalized()', which90# always calls 'finalize_options()', to respect/update it.91self.finalized = 09293# XXX A more explicit way to customize dry_run would be better.94def __getattr__(self, attr):95if attr == 'dry_run':96myval = getattr(self, "_" + attr)97if myval is None:98return getattr(self.distribution, attr)99else:100return myval101else:102raise AttributeError(attr)103104def ensure_finalized(self):105if not self.finalized:106self.finalize_options()107self.finalized = 1108109# Subclasses must define:110# initialize_options()111# provide default values for all options; may be customized by112# setup script, by options from config file(s), or by command-line113# options114# finalize_options()115# decide on the final values for all options; this is called116# after all possible intervention from the outside world117# (command-line, option file, etc.) has been processed118# run()119# run the command: do whatever it is we're here to do,120# controlled by the command's various option values121122def initialize_options(self):123"""Set default values for all the options that this command124supports. Note that these defaults may be overridden by other125commands, by the setup script, by config files, or by the126command-line. Thus, this is not the place to code dependencies127between options; generally, 'initialize_options()' implementations128are just a bunch of "self.foo = None" assignments.129130This method must be implemented by all command classes.131"""132raise RuntimeError("abstract method -- subclass %s must override"133% self.__class__)134135def finalize_options(self):136"""Set final values for all the options that this command supports.137This is always called as late as possible, ie. after any option138assignments from the command-line or from other commands have been139done. Thus, this is the place to code option dependencies: if140'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as141long as 'foo' still has the same value it was assigned in142'initialize_options()'.143144This method must be implemented by all command classes.145"""146raise RuntimeError("abstract method -- subclass %s must override"147% self.__class__)148149150def dump_options(self, header=None, indent=""):151from distutils.fancy_getopt import longopt_xlate152if header is None:153header = "command options for '%s':" % self.get_command_name()154self.announce(indent + header, level=log.INFO)155indent = indent + " "156for (option, _, _) in self.user_options:157option = option.translate(longopt_xlate)158if option[-1] == "=":159option = option[:-1]160value = getattr(self, option)161self.announce(indent + "%s = %s" % (option, value),162level=log.INFO)163164def run(self):165"""A command's raison d'etre: carry out the action it exists to166perform, controlled by the options initialized in167'initialize_options()', customized by other commands, the setup168script, the command-line, and config files, and finalized in169'finalize_options()'. All terminal output and filesystem170interaction should be done by 'run()'.171172This method must be implemented by all command classes.173"""174raise RuntimeError("abstract method -- subclass %s must override"175% self.__class__)176177def announce(self, msg, level=1):178"""If the current verbosity level is of greater than or equal to179'level' print 'msg' to stdout.180"""181log.log(level, msg)182183def debug_print(self, msg):184"""Print 'msg' to stdout if the global DEBUG (taken from the185DISTUTILS_DEBUG environment variable) flag is true.186"""187from distutils.debug import DEBUG188if DEBUG:189print(msg)190sys.stdout.flush()191192193# -- Option validation methods -------------------------------------194# (these are very handy in writing the 'finalize_options()' method)195#196# NB. the general philosophy here is to ensure that a particular option197# value meets certain type and value constraints. If not, we try to198# force it into conformance (eg. if we expect a list but have a string,199# split the string on comma and/or whitespace). If we can't force the200# option into conformance, raise DistutilsOptionError. Thus, command201# classes need do nothing more than (eg.)202# self.ensure_string_list('foo')203# and they can be guaranteed that thereafter, self.foo will be204# a list of strings.205206def _ensure_stringlike(self, option, what, default=None):207val = getattr(self, option)208if val is None:209setattr(self, option, default)210return default211elif not isinstance(val, str):212raise DistutilsOptionError("'%s' must be a %s (got `%s`)"213% (option, what, val))214return val215216def ensure_string(self, option, default=None):217"""Ensure that 'option' is a string; if not defined, set it to218'default'.219"""220self._ensure_stringlike(option, "string", default)221222def ensure_string_list(self, option):223r"""Ensure that 'option' is a list of strings. If 'option' is224currently a string, we split it either on /,\s*/ or /\s+/, so225"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become226["foo", "bar", "baz"].227"""228val = getattr(self, option)229if val is None:230return231elif isinstance(val, str):232setattr(self, option, re.split(r',\s*|\s+', val))233else:234if isinstance(val, list):235ok = all(isinstance(v, str) for v in val)236else:237ok = False238if not ok:239raise DistutilsOptionError(240"'%s' must be a list of strings (got %r)"241% (option, val))242243def _ensure_tested_string(self, option, tester, what, error_fmt,244default=None):245val = self._ensure_stringlike(option, what, default)246if val is not None and not tester(val):247raise DistutilsOptionError(("error in '%s' option: " + error_fmt)248% (option, val))249250def ensure_filename(self, option):251"""Ensure that 'option' is the name of an existing file."""252self._ensure_tested_string(option, os.path.isfile,253"filename",254"'%s' does not exist or is not a file")255256def ensure_dirname(self, option):257self._ensure_tested_string(option, os.path.isdir,258"directory name",259"'%s' does not exist or is not a directory")260261262# -- Convenience methods for commands ------------------------------263264def get_command_name(self):265if hasattr(self, 'command_name'):266return self.command_name267else:268return self.__class__.__name__269270def set_undefined_options(self, src_cmd, *option_pairs):271"""Set the values of any "undefined" options from corresponding272option values in some other command object. "Undefined" here means273"is None", which is the convention used to indicate that an option274has not been changed between 'initialize_options()' and275'finalize_options()'. Usually called from 'finalize_options()' for276options that depend on some other command rather than another277option of the same command. 'src_cmd' is the other command from278which option values will be taken (a command object will be created279for it if necessary); the remaining arguments are280'(src_option,dst_option)' tuples which mean "take the value of281'src_option' in the 'src_cmd' command object, and copy it to282'dst_option' in the current command object".283"""284# Option_pairs: list of (src_option, dst_option) tuples285src_cmd_obj = self.distribution.get_command_obj(src_cmd)286src_cmd_obj.ensure_finalized()287for (src_option, dst_option) in option_pairs:288if getattr(self, dst_option) is None:289setattr(self, dst_option, getattr(src_cmd_obj, src_option))290291def get_finalized_command(self, command, create=1):292"""Wrapper around Distribution's 'get_command_obj()' method: find293(create if necessary and 'create' is true) the command object for294'command', call its 'ensure_finalized()' method, and return the295finalized command object.296"""297cmd_obj = self.distribution.get_command_obj(command, create)298cmd_obj.ensure_finalized()299return cmd_obj300301# XXX rename to 'get_reinitialized_command()'? (should do the302# same in dist.py, if so)303def reinitialize_command(self, command, reinit_subcommands=0):304return self.distribution.reinitialize_command(command,305reinit_subcommands)306307def run_command(self, command):308"""Run some other command: uses the 'run_command()' method of309Distribution, which creates and finalizes the command object if310necessary and then invokes its 'run()' method.311"""312self.distribution.run_command(command)313314def get_sub_commands(self):315"""Determine the sub-commands that are relevant in the current316distribution (ie., that need to be run). This is based on the317'sub_commands' class attribute: each tuple in that list may include318a method that we call to determine if the subcommand needs to be319run for the current distribution. Return a list of command names.320"""321commands = []322for (cmd_name, method) in self.sub_commands:323if method is None or method(self):324commands.append(cmd_name)325return commands326327328# -- External world manipulation -----------------------------------329330def warn(self, msg):331log.warn("warning: %s: %s\n", self.get_command_name(), msg)332333def execute(self, func, args, msg=None, level=1):334util.execute(func, args, msg, dry_run=self.dry_run)335336def mkpath(self, name, mode=0o777):337dir_util.mkpath(name, mode, dry_run=self.dry_run)338339def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1,340link=None, level=1):341"""Copy a file respecting verbose, dry-run and force flags. (The342former two default to whatever is in the Distribution object, and343the latter defaults to false for commands that don't define it.)"""344return file_util.copy_file(infile, outfile, preserve_mode,345preserve_times, not self.force, link,346dry_run=self.dry_run)347348def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1,349preserve_symlinks=0, level=1):350"""Copy an entire directory tree respecting verbose, dry-run,351and force flags.352"""353return dir_util.copy_tree(infile, outfile, preserve_mode,354preserve_times, preserve_symlinks,355not self.force, dry_run=self.dry_run)356357def move_file (self, src, dst, level=1):358"""Move a file respecting dry-run flag."""359return file_util.move_file(src, dst, dry_run=self.dry_run)360361def spawn(self, cmd, search_path=1, level=1):362"""Spawn an external command respecting dry-run flag."""363from distutils.spawn import spawn364spawn(cmd, search_path, dry_run=self.dry_run)365366def make_archive(self, base_name, format, root_dir=None, base_dir=None,367owner=None, group=None):368return archive_util.make_archive(base_name, format, root_dir, base_dir,369dry_run=self.dry_run,370owner=owner, group=group)371372def make_file(self, infiles, outfile, func, args,373exec_msg=None, skip_msg=None, level=1):374"""Special case of 'execute()' for operations that process one or375more input files and generate one output file. Works just like376'execute()', except the operation is skipped and a different377message printed if 'outfile' already exists and is newer than all378files listed in 'infiles'. If the command defined 'self.force',379and it is true, then the command is unconditionally run -- does no380timestamp checks.381"""382if skip_msg is None:383skip_msg = "skipping %s (inputs unchanged)" % outfile384385# Allow 'infiles' to be a single string386if isinstance(infiles, str):387infiles = (infiles,)388elif not isinstance(infiles, (list, tuple)):389raise TypeError(390"'infiles' must be a string, or a list or tuple of strings")391392if exec_msg is None:393exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles))394395# If 'outfile' must be regenerated (either because it doesn't396# exist, is out-of-date, or the 'force' flag is true) then397# perform the action that presumably regenerates it398if self.force or dep_util.newer_group(infiles, outfile):399self.execute(func, args, exec_msg, level)400# Otherwise, print the "skip" message401else:402log.debug(skip_msg)403404405