cmd.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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(
  115. "abstract method -- subclass %s must override" % self.__class__
  116. )
  117. def finalize_options(self):
  118. """Set final values for all the options that this command supports.
  119. This is always called as late as possible, ie. after any option
  120. assignments from the command-line or from other commands have been
  121. done. Thus, this is the place to code option dependencies: if
  122. 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
  123. long as 'foo' still has the same value it was assigned in
  124. 'initialize_options()'.
  125. This method must be implemented by all command classes.
  126. """
  127. raise RuntimeError(
  128. "abstract method -- subclass %s must override" % self.__class__
  129. )
  130. def dump_options(self, header=None, indent=""):
  131. from distutils.fancy_getopt import longopt_xlate
  132. if header is None:
  133. header = "command options for '%s':" % self.get_command_name()
  134. self.announce(indent + header, level=log.INFO)
  135. indent = indent + " "
  136. for (option, _, _) in self.user_options:
  137. option = option.translate(longopt_xlate)
  138. if option[-1] == "=":
  139. option = option[:-1]
  140. value = getattr(self, option)
  141. self.announce(indent + "%s = %s" % (option, value), level=log.INFO)
  142. def run(self):
  143. """A command's raison d'etre: carry out the action it exists to
  144. perform, controlled by the options initialized in
  145. 'initialize_options()', customized by other commands, the setup
  146. script, the command-line, and config files, and finalized in
  147. 'finalize_options()'. All terminal output and filesystem
  148. interaction should be done by 'run()'.
  149. This method must be implemented by all command classes.
  150. """
  151. raise RuntimeError(
  152. "abstract method -- subclass %s must override" % self.__class__
  153. )
  154. def announce(self, msg, level=1):
  155. """If the current verbosity level is of greater than or equal to
  156. 'level' print 'msg' to stdout.
  157. """
  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. "'%s' must be a %s (got `%s`)" % (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. "'%s' must be a list of strings (got %r)" % (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.warn("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 %s from %s" % (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 dep_util.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)