cmd.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. """distutils.cmd
  2. Provides the Command class, the base class for the command classes
  3. in the distutils.command package.
  4. """
  5. # This module should be kept compatible with Python 2.1.
  6. __revision__ = "$Id: cmd.py 37828 2004-11-10 22:23:15Z loewis $"
  7. import sys, os, string, re
  8. from types import *
  9. from distutils.errors import *
  10. from distutils import util, dir_util, file_util, archive_util, dep_util
  11. from distutils 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. # __init__ ()
  83. # XXX A more explicit way to customize dry_run would be better.
  84. def __getattr__ (self, attr):
  85. if attr == 'dry_run':
  86. myval = getattr(self, "_" + attr)
  87. if myval is None:
  88. return getattr(self.distribution, attr)
  89. else:
  90. return myval
  91. else:
  92. raise AttributeError, attr
  93. def ensure_finalized (self):
  94. if not self.finalized:
  95. self.finalize_options()
  96. self.finalized = 1
  97. # Subclasses must define:
  98. # initialize_options()
  99. # provide default values for all options; may be customized by
  100. # setup script, by options from config file(s), or by command-line
  101. # options
  102. # finalize_options()
  103. # decide on the final values for all options; this is called
  104. # after all possible intervention from the outside world
  105. # (command-line, option file, etc.) has been processed
  106. # run()
  107. # run the command: do whatever it is we're here to do,
  108. # controlled by the command's various option values
  109. def initialize_options (self):
  110. """Set default values for all the options that this command
  111. supports. Note that these defaults may be overridden by other
  112. commands, by the setup script, by config files, or by the
  113. command-line. Thus, this is not the place to code dependencies
  114. between options; generally, 'initialize_options()' implementations
  115. are just a bunch of "self.foo = None" assignments.
  116. This method must be implemented by all command classes.
  117. """
  118. raise RuntimeError, \
  119. "abstract method -- subclass %s must override" % self.__class__
  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. 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. print indent + header
  137. indent = indent + " "
  138. for (option, _, _) in self.user_options:
  139. option = string.translate(option, longopt_xlate)
  140. if option[-1] == "=":
  141. option = option[:-1]
  142. value = getattr(self, option)
  143. print indent + "%s = %s" % (option, value)
  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. def announce (self, msg, level=1):
  156. """If the current verbosity level is of greater than or equal to
  157. 'level' print 'msg' to stdout.
  158. """
  159. log.log(level, msg)
  160. def debug_print (self, msg):
  161. """Print 'msg' to stdout if the global DEBUG (taken from the
  162. DISTUTILS_DEBUG environment variable) flag is true.
  163. """
  164. from distutils.debug import DEBUG
  165. if DEBUG:
  166. print msg
  167. sys.stdout.flush()
  168. # -- Option validation methods -------------------------------------
  169. # (these are very handy in writing the 'finalize_options()' method)
  170. #
  171. # NB. the general philosophy here is to ensure that a particular option
  172. # value meets certain type and value constraints. If not, we try to
  173. # force it into conformance (eg. if we expect a list but have a string,
  174. # split the string on comma and/or whitespace). If we can't force the
  175. # option into conformance, raise DistutilsOptionError. Thus, command
  176. # classes need do nothing more than (eg.)
  177. # self.ensure_string_list('foo')
  178. # and they can be guaranteed that thereafter, self.foo will be
  179. # a list of strings.
  180. def _ensure_stringlike (self, option, what, default=None):
  181. val = getattr(self, option)
  182. if val is None:
  183. setattr(self, option, default)
  184. return default
  185. elif type(val) is not StringType:
  186. raise DistutilsOptionError, \
  187. "'%s' must be a %s (got `%s`)" % (option, what, val)
  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. """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 type(val) is StringType:
  204. setattr(self, option, re.split(r',\s*|\s+', val))
  205. else:
  206. if type(val) is ListType:
  207. types = map(type, val)
  208. ok = (types == [StringType] * len(val))
  209. else:
  210. ok = 0
  211. if not ok:
  212. raise DistutilsOptionError, \
  213. "'%s' must be a list of strings (got %r)" % \
  214. (option, val)
  215. def _ensure_tested_string (self, option, tester,
  216. 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. def ensure_filename (self, option):
  222. """Ensure that 'option' is the name of an existing file."""
  223. self._ensure_tested_string(option, os.path.isfile,
  224. "filename",
  225. "'%s' does not exist or is not a file")
  226. def ensure_dirname (self, option):
  227. self._ensure_tested_string(option, os.path.isdir,
  228. "directory name",
  229. "'%s' does not exist or is not a directory")
  230. # -- Convenience methods for commands ------------------------------
  231. def get_command_name (self):
  232. if hasattr(self, 'command_name'):
  233. return self.command_name
  234. else:
  235. return self.__class__.__name__
  236. def set_undefined_options (self, src_cmd, *option_pairs):
  237. """Set the values of any "undefined" options from corresponding
  238. option values in some other command object. "Undefined" here means
  239. "is None", which is the convention used to indicate that an option
  240. has not been changed between 'initialize_options()' and
  241. 'finalize_options()'. Usually called from 'finalize_options()' for
  242. options that depend on some other command rather than another
  243. option of the same command. 'src_cmd' is the other command from
  244. which option values will be taken (a command object will be created
  245. for it if necessary); the remaining arguments are
  246. '(src_option,dst_option)' tuples which mean "take the value of
  247. 'src_option' in the 'src_cmd' command object, and copy it to
  248. 'dst_option' in the current command object".
  249. """
  250. # Option_pairs: list of (src_option, dst_option) tuples
  251. src_cmd_obj = self.distribution.get_command_obj(src_cmd)
  252. src_cmd_obj.ensure_finalized()
  253. for (src_option, dst_option) in option_pairs:
  254. if getattr(self, dst_option) is None:
  255. setattr(self, dst_option,
  256. getattr(src_cmd_obj, src_option))
  257. def get_finalized_command (self, command, create=1):
  258. """Wrapper around Distribution's 'get_command_obj()' method: find
  259. (create if necessary and 'create' is true) the command object for
  260. 'command', call its 'ensure_finalized()' method, and return the
  261. finalized command object.
  262. """
  263. cmd_obj = self.distribution.get_command_obj(command, create)
  264. cmd_obj.ensure_finalized()
  265. return cmd_obj
  266. # XXX rename to 'get_reinitialized_command()'? (should do the
  267. # same in dist.py, if so)
  268. def reinitialize_command (self, command, reinit_subcommands=0):
  269. return self.distribution.reinitialize_command(
  270. 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. sys.stderr.write("warning: %s: %s\n" %
  292. (self.get_command_name(), msg))
  293. def execute (self, func, args, msg=None, level=1):
  294. util.execute(func, args, msg, dry_run=self.dry_run)
  295. def mkpath (self, name, mode=0777):
  296. dir_util.mkpath(name, mode, dry_run=self.dry_run)
  297. def copy_file (self, infile, outfile,
  298. preserve_mode=1, preserve_times=1, link=None, level=1):
  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, outfile,
  304. preserve_mode, preserve_times,
  305. not self.force,
  306. link,
  307. dry_run=self.dry_run)
  308. def copy_tree (self, infile, outfile,
  309. preserve_mode=1, preserve_times=1, preserve_symlinks=0,
  310. level=1):
  311. """Copy an entire directory tree respecting verbose, dry-run,
  312. and force flags.
  313. """
  314. return dir_util.copy_tree(
  315. infile, outfile,
  316. preserve_mode,preserve_times,preserve_symlinks,
  317. not self.force,
  318. dry_run=self.dry_run)
  319. def move_file (self, src, dst, level=1):
  320. """Move a file respectin dry-run flag."""
  321. return file_util.move_file(src, dst, dry_run = self.dry_run)
  322. def spawn (self, cmd, search_path=1, level=1):
  323. """Spawn an external command respecting dry-run flag."""
  324. from distutils.spawn import spawn
  325. spawn(cmd, search_path, dry_run= self.dry_run)
  326. def make_archive (self, base_name, format,
  327. root_dir=None, base_dir=None):
  328. return archive_util.make_archive(
  329. base_name, format, root_dir, base_dir, dry_run=self.dry_run)
  330. def make_file (self, infiles, outfile, func, args,
  331. exec_msg=None, skip_msg=None, level=1):
  332. """Special case of 'execute()' for operations that process one or
  333. more input files and generate one output file. Works just like
  334. 'execute()', except the operation is skipped and a different
  335. message printed if 'outfile' already exists and is newer than all
  336. files listed in 'infiles'. If the command defined 'self.force',
  337. and it is true, then the command is unconditionally run -- does no
  338. timestamp checks.
  339. """
  340. if exec_msg is None:
  341. exec_msg = "generating %s from %s" % \
  342. (outfile, string.join(infiles, ', '))
  343. if skip_msg is None:
  344. skip_msg = "skipping %s (inputs unchanged)" % outfile
  345. # Allow 'infiles' to be a single string
  346. if type(infiles) is StringType:
  347. infiles = (infiles,)
  348. elif type(infiles) not in (ListType, TupleType):
  349. raise TypeError, \
  350. "'infiles' must be a string, or a list or tuple of strings"
  351. # If 'outfile' must be regenerated (either because it doesn't
  352. # exist, is out-of-date, or the 'force' flag is true) then
  353. # perform the action that presumably regenerates it
  354. if self.force or dep_util.newer_group (infiles, outfile):
  355. self.execute(func, args, exec_msg, level)
  356. # Otherwise, print the "skip" message
  357. else:
  358. log.debug(skip_msg)
  359. # make_file ()
  360. # class Command
  361. # XXX 'install_misc' class not currently used -- it was the base class for
  362. # both 'install_scripts' and 'install_data', but they outgrew it. It might
  363. # still be useful for 'install_headers', though, so I'm keeping it around
  364. # for the time being.
  365. class install_misc (Command):
  366. """Common base class for installing some files in a subdirectory.
  367. Currently used by install_data and install_scripts.
  368. """
  369. user_options = [('install-dir=', 'd', "directory to install the files to")]
  370. def initialize_options (self):
  371. self.install_dir = None
  372. self.outfiles = []
  373. def _install_dir_from (self, dirname):
  374. self.set_undefined_options('install', (dirname, 'install_dir'))
  375. def _copy_files (self, filelist):
  376. self.outfiles = []
  377. if not filelist:
  378. return
  379. self.mkpath(self.install_dir)
  380. for f in filelist:
  381. self.copy_file(f, self.install_dir)
  382. self.outfiles.append(os.path.join(self.install_dir, f))
  383. def get_outputs (self):
  384. return self.outfiles
  385. if __name__ == "__main__":
  386. print "ok"