cmd.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. """distutils.cmd
  2. Provides the Command class, the base class for the command classes
  3. in the distutils.command package.
  4. """
  5. import sys, os, re
  6. from distutils.errors import DistutilsOptionError
  7. from distutils import util, dir_util, file_util, archive_util, dep_util
  8. from distutils import log
  9. class Command:
  10. """Abstract base class for defining command classes, the "worker bees"
  11. of the Distutils. A useful analogy for command classes is to think of
  12. them as subroutines with local variables called "options". The options
  13. are "declared" in 'initialize_options()' and "defined" (given their
  14. final values, aka "finalized") in 'finalize_options()', both of which
  15. must be defined by every command class. The distinction between the
  16. two is necessary because option values might come from the outside
  17. world (command line, config file, ...), and any options dependent on
  18. other options must be computed *after* these outside influences have
  19. been processed -- hence 'finalize_options()'. The "body" of the
  20. subroutine, where it does all its work based on the values of its
  21. options, is the 'run()' method, which must also be implemented by every
  22. command class.
  23. """
  24. # 'sub_commands' formalizes the notion of a "family" of commands,
  25. # eg. "install" as the parent with sub-commands "install_lib",
  26. # "install_headers", etc. The parent of a family of commands
  27. # defines 'sub_commands' as a class attribute; it's a list of
  28. # (command_name : string, predicate : unbound_method | string | None)
  29. # tuples, where 'predicate' is a method of the parent command that
  30. # determines whether the corresponding command is applicable in the
  31. # current situation. (Eg. we "install_headers" is only applicable if
  32. # we have any C header files to install.) If 'predicate' is None,
  33. # that command is always applicable.
  34. #
  35. # 'sub_commands' is usually defined at the *end* of a class, because
  36. # predicates can be unbound methods, so they must already have been
  37. # defined. The canonical example is the "install" command.
  38. sub_commands = []
  39. # -- Creation/initialization methods -------------------------------
  40. def __init__(self, dist):
  41. """Create and initialize a new Command object. Most importantly,
  42. invokes the 'initialize_options()' method, which is the real
  43. initializer and depends on the actual command being
  44. instantiated.
  45. """
  46. # late import because of mutual dependence between these classes
  47. from distutils.dist import Distribution
  48. if not isinstance(dist, Distribution):
  49. raise TypeError("dist must be a Distribution instance")
  50. if self.__class__ is Command:
  51. raise RuntimeError("Command is an abstract class")
  52. self.distribution = dist
  53. self.initialize_options()
  54. # Per-command versions of the global flags, so that the user can
  55. # customize Distutils' behaviour command-by-command and let some
  56. # commands fall back on the Distribution's behaviour. None means
  57. # "not defined, check self.distribution's copy", while 0 or 1 mean
  58. # false and true (duh). Note that this means figuring out the real
  59. # value of each flag is a touch complicated -- hence "self._dry_run"
  60. # will be handled by __getattr__, below.
  61. # XXX This needs to be fixed.
  62. self._dry_run = None
  63. # verbose is largely ignored, but needs to be set for
  64. # backwards compatibility (I think)?
  65. self.verbose = dist.verbose
  66. # Some commands define a 'self.force' option to ignore file
  67. # timestamps, but methods defined *here* assume that
  68. # 'self.force' exists for all commands. So define it here
  69. # just to be safe.
  70. self.force = None
  71. # The 'help' flag is just used for command-line parsing, so
  72. # none of that complicated bureaucracy is needed.
  73. self.help = 0
  74. # 'finalized' records whether or not 'finalize_options()' has been
  75. # called. 'finalize_options()' itself should not pay attention to
  76. # this flag: it is the business of 'ensure_finalized()', which
  77. # always calls 'finalize_options()', to respect/update it.
  78. self.finalized = 0
  79. # XXX A more explicit way to customize dry_run would be better.
  80. def __getattr__(self, attr):
  81. if attr == 'dry_run':
  82. myval = getattr(self, "_" + attr)
  83. if myval is None:
  84. return getattr(self.distribution, attr)
  85. else:
  86. return myval
  87. else:
  88. raise AttributeError(attr)
  89. def ensure_finalized(self):
  90. if not self.finalized:
  91. self.finalize_options()
  92. self.finalized = 1
  93. # Subclasses must define:
  94. # initialize_options()
  95. # provide default values for all options; may be customized by
  96. # setup script, by options from config file(s), or by command-line
  97. # options
  98. # finalize_options()
  99. # decide on the final values for all options; this is called
  100. # after all possible intervention from the outside world
  101. # (command-line, option file, etc.) has been processed
  102. # run()
  103. # run the command: do whatever it is we're here to do,
  104. # controlled by the command's various option values
  105. def initialize_options(self):
  106. """Set default values for all the options that this command
  107. supports. Note that these defaults may be overridden by other
  108. commands, by the setup script, by config files, or by the
  109. command-line. Thus, this is not the place to code dependencies
  110. between options; generally, 'initialize_options()' implementations
  111. are just a bunch of "self.foo = None" assignments.
  112. This method must be implemented by all command classes.
  113. """
  114. raise RuntimeError("abstract method -- subclass %s must override"
  115. % self.__class__)
  116. def finalize_options(self):
  117. """Set final values for all the options that this command supports.
  118. This is always called as late as possible, ie. after any option
  119. assignments from the command-line or from other commands have been
  120. done. Thus, this is the place to code option dependencies: if
  121. 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
  122. long as 'foo' still has the same value it was assigned in
  123. 'initialize_options()'.
  124. This method must be implemented by all command classes.
  125. """
  126. raise RuntimeError("abstract method -- subclass %s must override"
  127. % self.__class__)
  128. def dump_options(self, header=None, indent=""):
  129. from distutils.fancy_getopt import longopt_xlate
  130. if header is None:
  131. header = "command options for '%s':" % self.get_command_name()
  132. self.announce(indent + header, level=log.INFO)
  133. indent = indent + " "
  134. for (option, _, _) in self.user_options:
  135. option = option.translate(longopt_xlate)
  136. if option[-1] == "=":
  137. option = option[:-1]
  138. value = getattr(self, option)
  139. self.announce(indent + "%s = %s" % (option, value),
  140. level=log.INFO)
  141. def run(self):
  142. """A command's raison d'etre: carry out the action it exists to
  143. perform, controlled by the options initialized in
  144. 'initialize_options()', customized by other commands, the setup
  145. script, the command-line, and config files, and finalized in
  146. 'finalize_options()'. All terminal output and filesystem
  147. interaction should be done by 'run()'.
  148. This method must be implemented by all command classes.
  149. """
  150. raise RuntimeError("abstract method -- subclass %s must override"
  151. % self.__class__)
  152. def announce(self, msg, level=1):
  153. """If the current verbosity level is of greater than or equal to
  154. 'level' print 'msg' to stdout.
  155. """
  156. log.log(level, msg)
  157. def debug_print(self, msg):
  158. """Print 'msg' to stdout if the global DEBUG (taken from the
  159. DISTUTILS_DEBUG environment variable) flag is true.
  160. """
  161. from distutils.debug import DEBUG
  162. if DEBUG:
  163. print(msg)
  164. sys.stdout.flush()
  165. # -- Option validation methods -------------------------------------
  166. # (these are very handy in writing the 'finalize_options()' method)
  167. #
  168. # NB. the general philosophy here is to ensure that a particular option
  169. # value meets certain type and value constraints. If not, we try to
  170. # force it into conformance (eg. if we expect a list but have a string,
  171. # split the string on comma and/or whitespace). If we can't force the
  172. # option into conformance, raise DistutilsOptionError. Thus, command
  173. # classes need do nothing more than (eg.)
  174. # self.ensure_string_list('foo')
  175. # and they can be guaranteed that thereafter, self.foo will be
  176. # a list of strings.
  177. def _ensure_stringlike(self, option, what, default=None):
  178. val = getattr(self, option)
  179. if val is None:
  180. setattr(self, option, default)
  181. return default
  182. elif not isinstance(val, str):
  183. raise DistutilsOptionError("'%s' must be a %s (got `%s`)"
  184. % (option, what, val))
  185. return val
  186. def ensure_string(self, option, default=None):
  187. """Ensure that 'option' is a string; if not defined, set it to
  188. 'default'.
  189. """
  190. self._ensure_stringlike(option, "string", default)
  191. def ensure_string_list(self, option):
  192. r"""Ensure that 'option' is a list of strings. If 'option' is
  193. currently a string, we split it either on /,\s*/ or /\s+/, so
  194. "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
  195. ["foo", "bar", "baz"].
  196. """
  197. val = getattr(self, option)
  198. if val is None:
  199. return
  200. elif isinstance(val, str):
  201. setattr(self, option, re.split(r',\s*|\s+', val))
  202. else:
  203. if isinstance(val, list):
  204. ok = all(isinstance(v, str) for v in val)
  205. else:
  206. ok = False
  207. if not ok:
  208. raise DistutilsOptionError(
  209. "'%s' must be a list of strings (got %r)"
  210. % (option, val))
  211. def _ensure_tested_string(self, option, tester, what, error_fmt,
  212. default=None):
  213. val = self._ensure_stringlike(option, what, default)
  214. if val is not None and not tester(val):
  215. raise DistutilsOptionError(("error in '%s' option: " + error_fmt)
  216. % (option, val))
  217. def ensure_filename(self, option):
  218. """Ensure that 'option' is the name of an existing file."""
  219. self._ensure_tested_string(option, os.path.isfile,
  220. "filename",
  221. "'%s' does not exist or is not a file")
  222. def ensure_dirname(self, option):
  223. self._ensure_tested_string(option, os.path.isdir,
  224. "directory name",
  225. "'%s' does not exist or is not a directory")
  226. # -- Convenience methods for commands ------------------------------
  227. def get_command_name(self):
  228. if hasattr(self, 'command_name'):
  229. return self.command_name
  230. else:
  231. return self.__class__.__name__
  232. def set_undefined_options(self, src_cmd, *option_pairs):
  233. """Set the values of any "undefined" options from corresponding
  234. option values in some other command object. "Undefined" here means
  235. "is None", which is the convention used to indicate that an option
  236. has not been changed between 'initialize_options()' and
  237. 'finalize_options()'. Usually called from 'finalize_options()' for
  238. options that depend on some other command rather than another
  239. option of the same command. 'src_cmd' is the other command from
  240. which option values will be taken (a command object will be created
  241. for it if necessary); the remaining arguments are
  242. '(src_option,dst_option)' tuples which mean "take the value of
  243. 'src_option' in the 'src_cmd' command object, and copy it to
  244. 'dst_option' in the current command object".
  245. """
  246. # Option_pairs: list of (src_option, dst_option) tuples
  247. src_cmd_obj = self.distribution.get_command_obj(src_cmd)
  248. src_cmd_obj.ensure_finalized()
  249. for (src_option, dst_option) in option_pairs:
  250. if getattr(self, dst_option) is None:
  251. setattr(self, dst_option, getattr(src_cmd_obj, src_option))
  252. def get_finalized_command(self, command, create=1):
  253. """Wrapper around Distribution's 'get_command_obj()' method: find
  254. (create if necessary and 'create' is true) the command object for
  255. 'command', call its 'ensure_finalized()' method, and return the
  256. finalized command object.
  257. """
  258. cmd_obj = self.distribution.get_command_obj(command, create)
  259. cmd_obj.ensure_finalized()
  260. return cmd_obj
  261. # XXX rename to 'get_reinitialized_command()'? (should do the
  262. # same in dist.py, if so)
  263. def reinitialize_command(self, command, reinit_subcommands=0):
  264. return self.distribution.reinitialize_command(command,
  265. reinit_subcommands)
  266. def run_command(self, command):
  267. """Run some other command: uses the 'run_command()' method of
  268. Distribution, which creates and finalizes the command object if
  269. necessary and then invokes its 'run()' method.
  270. """
  271. self.distribution.run_command(command)
  272. def get_sub_commands(self):
  273. """Determine the sub-commands that are relevant in the current
  274. distribution (ie., that need to be run). This is based on the
  275. 'sub_commands' class attribute: each tuple in that list may include
  276. a method that we call to determine if the subcommand needs to be
  277. run for the current distribution. Return a list of command names.
  278. """
  279. commands = []
  280. for (cmd_name, method) in self.sub_commands:
  281. if method is None or method(self):
  282. commands.append(cmd_name)
  283. return commands
  284. # -- External world manipulation -----------------------------------
  285. def warn(self, msg):
  286. log.warn("warning: %s: %s\n", self.get_command_name(), msg)
  287. def execute(self, func, args, msg=None, level=1):
  288. util.execute(func, args, msg, dry_run=self.dry_run)
  289. def mkpath(self, name, mode=0o777):
  290. dir_util.mkpath(name, mode, dry_run=self.dry_run)
  291. def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1,
  292. link=None, level=1):
  293. """Copy a file respecting verbose, dry-run and force flags. (The
  294. former two default to whatever is in the Distribution object, and
  295. the latter defaults to false for commands that don't define it.)"""
  296. return file_util.copy_file(infile, outfile, preserve_mode,
  297. preserve_times, not self.force, link,
  298. dry_run=self.dry_run)
  299. def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1,
  300. preserve_symlinks=0, level=1):
  301. """Copy an entire directory tree respecting verbose, dry-run,
  302. and force flags.
  303. """
  304. return dir_util.copy_tree(infile, outfile, preserve_mode,
  305. preserve_times, preserve_symlinks,
  306. not self.force, dry_run=self.dry_run)
  307. def move_file (self, src, dst, level=1):
  308. """Move a file respecting dry-run flag."""
  309. return file_util.move_file(src, dst, dry_run=self.dry_run)
  310. def spawn(self, cmd, search_path=1, level=1):
  311. """Spawn an external command respecting dry-run flag."""
  312. from distutils.spawn import spawn
  313. spawn(cmd, search_path, dry_run=self.dry_run)
  314. def make_archive(self, base_name, format, root_dir=None, base_dir=None,
  315. owner=None, group=None):
  316. return archive_util.make_archive(base_name, format, root_dir, base_dir,
  317. dry_run=self.dry_run,
  318. owner=owner, group=group)
  319. def make_file(self, infiles, outfile, func, args,
  320. exec_msg=None, skip_msg=None, level=1):
  321. """Special case of 'execute()' for operations that process one or
  322. more input files and generate one output file. Works just like
  323. 'execute()', except the operation is skipped and a different
  324. message printed if 'outfile' already exists and is newer than all
  325. files listed in 'infiles'. If the command defined 'self.force',
  326. and it is true, then the command is unconditionally run -- does no
  327. timestamp checks.
  328. """
  329. if skip_msg is None:
  330. skip_msg = "skipping %s (inputs unchanged)" % outfile
  331. # Allow 'infiles' to be a single string
  332. if isinstance(infiles, str):
  333. infiles = (infiles,)
  334. elif not isinstance(infiles, (list, tuple)):
  335. raise TypeError(
  336. "'infiles' must be a string, or a list or tuple of strings")
  337. if exec_msg is None:
  338. exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles))
  339. # If 'outfile' must be regenerated (either because it doesn't
  340. # exist, is out-of-date, or the 'force' flag is true) then
  341. # perform the action that presumably regenerates it
  342. if self.force or dep_util.newer_group(infiles, outfile):
  343. self.execute(func, args, exec_msg, level)
  344. # Otherwise, print the "skip" message
  345. else:
  346. log.debug(skip_msg)