PageRenderTime 48ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/distutils/cmd.py

http://github.com/IronLanguages/main
Python | 457 lines | 431 code | 6 blank | 20 comment | 7 complexity | 145b3567677ffaffe70c0e272bf5fc55 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. """distutils.cmd
  2. Provides the Command class, the base class for the command classes
  3. in the distutils.command package.
  4. """
  5. __revision__ = "$Id$"
  6. import sys, os, re
  7. from distutils.errors import DistutilsOptionError
  8. from distutils import util, dir_util, file_util, archive_util, dep_util
  9. from distutils import log
  10. class Command:
  11. """Abstract base class for defining command classes, the "worker bees"
  12. of the Distutils. A useful analogy for command classes is to think of
  13. them as subroutines with local variables called "options". The options
  14. are "declared" in 'initialize_options()' and "defined" (given their
  15. final values, aka "finalized") in 'finalize_options()', both of which
  16. must be defined by every command class. The distinction between the
  17. two is necessary because option values might come from the outside
  18. world (command line, config file, ...), and any options dependent on
  19. other options must be computed *after* these outside influences have
  20. been processed -- hence 'finalize_options()'. The "body" of the
  21. subroutine, where it does all its work based on the values of its
  22. options, is the 'run()' method, which must also be implemented by every
  23. command class.
  24. """
  25. # 'sub_commands' formalizes the notion of a "family" of commands,
  26. # eg. "install" as the parent with sub-commands "install_lib",
  27. # "install_headers", etc. The parent of a family of commands
  28. # defines 'sub_commands' as a class attribute; it's a list of
  29. # (command_name : string, predicate : unbound_method | string | None)
  30. # tuples, where 'predicate' is a method of the parent command that
  31. # determines whether the corresponding command is applicable in the
  32. # current situation. (Eg. we "install_headers" is only applicable if
  33. # we have any C header files to install.) If 'predicate' is None,
  34. # that command is always applicable.
  35. #
  36. # 'sub_commands' is usually defined at the *end* of a class, because
  37. # predicates can be unbound methods, so they must already have been
  38. # defined. The canonical example is the "install" command.
  39. sub_commands = []
  40. # -- Creation/initialization methods -------------------------------
  41. def __init__(self, dist):
  42. """Create and initialize a new Command object. Most importantly,
  43. invokes the 'initialize_options()' method, which is the real
  44. initializer and depends on the actual command being
  45. instantiated.
  46. """
  47. # late import because of mutual dependence between these classes
  48. from distutils.dist import Distribution
  49. if not isinstance(dist, Distribution):
  50. raise TypeError, "dist must be a Distribution instance"
  51. if self.__class__ is Command:
  52. raise RuntimeError, "Command is an abstract class"
  53. self.distribution = dist
  54. self.initialize_options()
  55. # Per-command versions of the global flags, so that the user can
  56. # customize Distutils' behaviour command-by-command and let some
  57. # commands fall back on the Distribution's behaviour. None means
  58. # "not defined, check self.distribution's copy", while 0 or 1 mean
  59. # false and true (duh). Note that this means figuring out the real
  60. # value of each flag is a touch complicated -- hence "self._dry_run"
  61. # will be handled by __getattr__, below.
  62. # XXX This needs to be fixed.
  63. self._dry_run = None
  64. # verbose is largely ignored, but needs to be set for
  65. # backwards compatibility (I think)?
  66. self.verbose = dist.verbose
  67. # Some commands define a 'self.force' option to ignore file
  68. # timestamps, but methods defined *here* assume that
  69. # 'self.force' exists for all commands. So define it here
  70. # just to be safe.
  71. self.force = None
  72. # The 'help' flag is just used for command-line parsing, so
  73. # none of that complicated bureaucracy is needed.
  74. self.help = 0
  75. # 'finalized' records whether or not 'finalize_options()' has been
  76. # called. 'finalize_options()' itself should not pay attention to
  77. # this flag: it is the business of 'ensure_finalized()', which
  78. # always calls 'finalize_options()', to respect/update it.
  79. self.finalized = 0
  80. # XXX A more explicit way to customize dry_run would be better.
  81. def __getattr__(self, attr):
  82. if attr == 'dry_run':
  83. myval = getattr(self, "_" + attr)
  84. if myval is None:
  85. return getattr(self.distribution, attr)
  86. else:
  87. return myval
  88. else:
  89. raise AttributeError, attr
  90. def ensure_finalized(self):
  91. if not self.finalized:
  92. self.finalize_options()
  93. self.finalized = 1
  94. # Subclasses must define:
  95. # initialize_options()
  96. # provide default values for all options; may be customized by
  97. # setup script, by options from config file(s), or by command-line
  98. # options
  99. # finalize_options()
  100. # decide on the final values for all options; this is called
  101. # after all possible intervention from the outside world
  102. # (command-line, option file, etc.) has been processed
  103. # run()
  104. # run the command: do whatever it is we're here to do,
  105. # controlled by the command's various option values
  106. def initialize_options(self):
  107. """Set default values for all the options that this command
  108. supports. Note that these defaults may be overridden by other
  109. commands, by the setup script, by config files, or by the
  110. command-line. Thus, this is not the place to code dependencies
  111. between options; generally, 'initialize_options()' implementations
  112. are just a bunch of "self.foo = None" assignments.
  113. This method must be implemented by all command classes.
  114. """
  115. raise RuntimeError, \
  116. "abstract method -- subclass %s must override" % self.__class__
  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. def dump_options(self, header=None, indent=""):
  130. from distutils.fancy_getopt import longopt_xlate
  131. if header is None:
  132. header = "command options for '%s':" % self.get_command_name()
  133. self.announce(indent + header, level=log.INFO)
  134. indent = indent + " "
  135. for (option, _, _) in self.user_options:
  136. option = option.translate(longopt_xlate)
  137. if option[-1] == "=":
  138. option = option[:-1]
  139. value = getattr(self, option)
  140. self.announce(indent + "%s = %s" % (option, value),
  141. 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. def announce(self, msg, level=1):
  154. """If the current verbosity level is of greater than or equal to
  155. 'level' print 'msg' to stdout.
  156. """
  157. log.log(level, msg)
  158. def debug_print(self, msg):
  159. """Print 'msg' to stdout if the global DEBUG (taken from the
  160. DISTUTILS_DEBUG environment variable) flag is true.
  161. """
  162. from distutils.debug import DEBUG
  163. if DEBUG:
  164. print msg
  165. sys.stdout.flush()
  166. # -- Option validation methods -------------------------------------
  167. # (these are very handy in writing the 'finalize_options()' method)
  168. #
  169. # NB. the general philosophy here is to ensure that a particular option
  170. # value meets certain type and value constraints. If not, we try to
  171. # force it into conformance (eg. if we expect a list but have a string,
  172. # split the string on comma and/or whitespace). If we can't force the
  173. # option into conformance, raise DistutilsOptionError. Thus, command
  174. # classes need do nothing more than (eg.)
  175. # self.ensure_string_list('foo')
  176. # and they can be guaranteed that thereafter, self.foo will be
  177. # a list of strings.
  178. def _ensure_stringlike(self, option, what, default=None):
  179. val = getattr(self, option)
  180. if val is None:
  181. setattr(self, option, default)
  182. return default
  183. elif not isinstance(val, str):
  184. raise DistutilsOptionError, \
  185. "'%s' must be a %s (got `%s`)" % (option, what, val)
  186. return val
  187. def ensure_string(self, option, default=None):
  188. """Ensure that 'option' is a string; if not defined, set it to
  189. 'default'.
  190. """
  191. self._ensure_stringlike(option, "string", default)
  192. def ensure_string_list(self, option):
  193. """Ensure that 'option' is a list of strings. If 'option' is
  194. currently a string, we split it either on /,\s*/ or /\s+/, so
  195. "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
  196. ["foo", "bar", "baz"].
  197. """
  198. val = getattr(self, option)
  199. if val is None:
  200. return
  201. elif isinstance(val, str):
  202. setattr(self, option, re.split(r',\s*|\s+', val))
  203. else:
  204. if isinstance(val, list):
  205. # checks if all elements are str
  206. ok = 1
  207. for element in val:
  208. if not isinstance(element, str):
  209. ok = 0
  210. break
  211. else:
  212. ok = 0
  213. if not ok:
  214. raise DistutilsOptionError, \
  215. "'%s' must be a list of strings (got %r)" % \
  216. (option, val)
  217. def _ensure_tested_string(self, option, tester,
  218. what, error_fmt, default=None):
  219. val = self._ensure_stringlike(option, what, default)
  220. if val is not None and not tester(val):
  221. raise DistutilsOptionError, \
  222. ("error in '%s' option: " + error_fmt) % (option, val)
  223. def ensure_filename(self, option):
  224. """Ensure that 'option' is the name of an existing file."""
  225. self._ensure_tested_string(option, os.path.isfile,
  226. "filename",
  227. "'%s' does not exist or is not a file")
  228. def ensure_dirname(self, option):
  229. self._ensure_tested_string(option, os.path.isdir,
  230. "directory name",
  231. "'%s' does not exist or is not a directory")
  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,
  258. getattr(src_cmd_obj, src_option))
  259. def get_finalized_command(self, command, create=1):
  260. """Wrapper around Distribution's 'get_command_obj()' method: find
  261. (create if necessary and 'create' is true) the command object for
  262. 'command', call its 'ensure_finalized()' method, and return the
  263. finalized command object.
  264. """
  265. cmd_obj = self.distribution.get_command_obj(command, create)
  266. cmd_obj.ensure_finalized()
  267. return cmd_obj
  268. # XXX rename to 'get_reinitialized_command()'? (should do the
  269. # same in dist.py, if so)
  270. def reinitialize_command(self, command, reinit_subcommands=0):
  271. return self.distribution.reinitialize_command(
  272. 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" %
  294. (self.get_command_name(), msg))
  295. def execute(self, func, args, msg=None, level=1):
  296. util.execute(func, args, msg, dry_run=self.dry_run)
  297. def mkpath(self, name, mode=0777):
  298. dir_util.mkpath(name, mode, dry_run=self.dry_run)
  299. def copy_file(self, infile, outfile,
  300. preserve_mode=1, preserve_times=1, link=None, level=1):
  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, outfile,
  306. preserve_mode, preserve_times,
  307. not self.force,
  308. link,
  309. dry_run=self.dry_run)
  310. def copy_tree(self, infile, outfile,
  311. preserve_mode=1, preserve_times=1, preserve_symlinks=0,
  312. level=1):
  313. """Copy an entire directory tree respecting verbose, dry-run,
  314. and force flags.
  315. """
  316. return dir_util.copy_tree(
  317. infile, outfile,
  318. preserve_mode,preserve_times,preserve_symlinks,
  319. not self.force,
  320. dry_run=self.dry_run)
  321. def move_file (self, src, dst, level=1):
  322. """Move a file respecting dry-run flag."""
  323. return file_util.move_file(src, dst, dry_run = self.dry_run)
  324. def spawn (self, cmd, search_path=1, level=1):
  325. """Spawn an external command respecting dry-run flag."""
  326. from distutils.spawn import spawn
  327. spawn(cmd, search_path, dry_run= self.dry_run)
  328. def make_archive(self, base_name, format, root_dir=None, base_dir=None,
  329. owner=None, group=None):
  330. return archive_util.make_archive(base_name, format, root_dir,
  331. base_dir, dry_run=self.dry_run,
  332. owner=owner, group=group)
  333. def make_file(self, infiles, outfile, func, args,
  334. exec_msg=None, skip_msg=None, level=1):
  335. """Special case of 'execute()' for operations that process one or
  336. more input files and generate one output file. Works just like
  337. 'execute()', except the operation is skipped and a different
  338. message printed if 'outfile' already exists and is newer than all
  339. files listed in 'infiles'. If the command defined 'self.force',
  340. and it is true, then the command is unconditionally run -- does no
  341. timestamp checks.
  342. """
  343. if skip_msg is None:
  344. skip_msg = "skipping %s (inputs unchanged)" % outfile
  345. # Allow 'infiles' to be a single string
  346. if isinstance(infiles, str):
  347. infiles = (infiles,)
  348. elif not isinstance(infiles, (list, tuple)):
  349. raise TypeError, \
  350. "'infiles' must be a string, or a list or tuple of strings"
  351. if exec_msg is None:
  352. exec_msg = "generating %s from %s" % \
  353. (outfile, ', '.join(infiles))
  354. # If 'outfile' must be regenerated (either because it doesn't
  355. # exist, is out-of-date, or the 'force' flag is true) then
  356. # perform the action that presumably regenerates it
  357. if self.force or dep_util.newer_group(infiles, outfile):
  358. self.execute(func, args, exec_msg, level)
  359. # Otherwise, print the "skip" message
  360. else:
  361. log.debug(skip_msg)
  362. # XXX 'install_misc' class not currently used -- it was the base class for
  363. # both 'install_scripts' and 'install_data', but they outgrew it. It might
  364. # still be useful for 'install_headers', though, so I'm keeping it around
  365. # for the time being.
  366. class install_misc(Command):
  367. """Common base class for installing some files in a subdirectory.
  368. Currently used by install_data and install_scripts.
  369. """
  370. user_options = [('install-dir=', 'd', "directory to install the files to")]
  371. def initialize_options (self):
  372. self.install_dir = None
  373. self.outfiles = []
  374. def _install_dir_from(self, dirname):
  375. self.set_undefined_options('install', (dirname, 'install_dir'))
  376. def _copy_files(self, filelist):
  377. self.outfiles = []
  378. if not filelist:
  379. return
  380. self.mkpath(self.install_dir)
  381. for f in filelist:
  382. self.copy_file(f, self.install_dir)
  383. self.outfiles.append(os.path.join(self.install_dir, f))
  384. def get_outputs(self):
  385. return self.outfiles