cmd.py 17 KB

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