cmd.py 18 KB

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