blob: 9f63f838a72d10f0e1b475f7ddc35af1185b5ff0 [file] [log] [blame]
Greg Wardfe6462c2000-04-04 01:40:52 +00001"""distutils.cmd
2
3Provides the Command class, the base class for the command classes
Greg Ward8ff5a3f2000-06-02 00:44:53 +00004in the distutils.command package.
5"""
Greg Wardfe6462c2000-04-04 01:40:52 +00006
7# created 2000/04/03, Greg Ward
8# (extricated from core.py; actually dates back to the beginning)
9
10__revision__ = "$Id$"
11
Greg Ward31413a72000-06-04 14:21:28 +000012import sys, os, string, re
Greg Wardfe6462c2000-04-04 01:40:52 +000013from types import *
14from distutils.errors import *
15from distutils import util
16
17
18class Command:
19 """Abstract base class for defining command classes, the "worker bees"
Greg Ward8ff5a3f2000-06-02 00:44:53 +000020 of the Distutils. A useful analogy for command classes is to think of
21 them as subroutines with local variables called "options". The options
22 are "declared" in 'initialize_options()' and "defined" (given their
23 final values, aka "finalized") in 'finalize_options()', both of which
24 must be defined by every command class. The distinction between the
25 two is necessary because option values might come from the outside
26 world (command line, config file, ...), and any options dependent on
27 other options must be computed *after* these outside influences have
28 been processed -- hence 'finalize_options()'. The "body" of the
29 subroutine, where it does all its work based on the values of its
30 options, is the 'run()' method, which must also be implemented by every
31 command class.
32 """
Greg Wardfe6462c2000-04-04 01:40:52 +000033
34 # -- Creation/initialization methods -------------------------------
35
36 def __init__ (self, dist):
37 """Create and initialize a new Command object. Most importantly,
Greg Ward8ff5a3f2000-06-02 00:44:53 +000038 invokes the 'initialize_options()' method, which is the real
39 initializer and depends on the actual command being
40 instantiated.
41 """
Greg Wardfe6462c2000-04-04 01:40:52 +000042 # late import because of mutual dependence between these classes
43 from distutils.dist import Distribution
44
45 if not isinstance (dist, Distribution):
46 raise TypeError, "dist must be a Distribution instance"
47 if self.__class__ is Command:
48 raise RuntimeError, "Command is an abstract class"
49
50 self.distribution = dist
51 self.initialize_options ()
52
53 # Per-command versions of the global flags, so that the user can
54 # customize Distutils' behaviour command-by-command and let some
55 # commands fallback on the Distribution's behaviour. None means
56 # "not defined, check self.distribution's copy", while 0 or 1 mean
57 # false and true (duh). Note that this means figuring out the real
58 # value of each flag is a touch complicatd -- hence "self.verbose"
59 # (etc.) will be handled by __getattr__, below.
60 self._verbose = None
61 self._dry_run = None
Greg Wardfe6462c2000-04-04 01:40:52 +000062
Greg Wardd197a3a2000-04-10 13:11:51 +000063 # Some commands define a 'self.force' option to ignore file
64 # timestamps, but methods defined *here* assume that
65 # 'self.force' exists for all commands. So define it here
66 # just to be safe.
67 self.force = None
68
Greg Wardfe6462c2000-04-04 01:40:52 +000069 # The 'help' flag is just used for command-line parsing, so
70 # none of that complicated bureaucracy is needed.
71 self.help = 0
72
Greg Ward4fb29e52000-05-27 17:27:23 +000073 # 'finalized' records whether or not 'finalize_options()' has been
Greg Wardfe6462c2000-04-04 01:40:52 +000074 # called. 'finalize_options()' itself should not pay attention to
Greg Ward4fb29e52000-05-27 17:27:23 +000075 # this flag: it is the business of 'ensure_finalized()', which
76 # always calls 'finalize_options()', to respect/update it.
77 self.finalized = 0
Greg Wardfe6462c2000-04-04 01:40:52 +000078
79 # __init__ ()
80
81
82 def __getattr__ (self, attr):
Greg Ward68a07572000-04-10 00:18:16 +000083 if attr in ('verbose', 'dry_run'):
Greg Wardfe6462c2000-04-04 01:40:52 +000084 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
92
Greg Ward4fb29e52000-05-27 17:27:23 +000093 def ensure_finalized (self):
94 if not self.finalized:
Greg Wardfe6462c2000-04-04 01:40:52 +000095 self.finalize_options ()
Greg Ward4fb29e52000-05-27 17:27:23 +000096 self.finalized = 1
Greg Wardfe6462c2000-04-04 01:40:52 +000097
98
99 # Subclasses must define:
100 # initialize_options()
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000101 # provide default values for all options; may be customized by
102 # setup script, by options from config file(s), or by command-line
103 # options
Greg Wardfe6462c2000-04-04 01:40:52 +0000104 # finalize_options()
105 # decide on the final values for all options; this is called
106 # after all possible intervention from the outside world
107 # (command-line, option file, etc.) has been processed
108 # run()
109 # run the command: do whatever it is we're here to do,
110 # controlled by the command's various option values
111
112 def initialize_options (self):
113 """Set default values for all the options that this command
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000114 supports. Note that these defaults may be overridden by other
115 commands, by the setup script, by config files, or by the
116 command-line. Thus, this is not the place to code dependencies
117 between options; generally, 'initialize_options()' implementations
118 are just a bunch of "self.foo = None" assignments.
Greg Wardfe6462c2000-04-04 01:40:52 +0000119
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000120 This method must be implemented by all command classes.
121 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000122 raise RuntimeError, \
123 "abstract method -- subclass %s must override" % self.__class__
124
125 def finalize_options (self):
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000126 """Set final values for all the options that this command supports.
127 This is always called as late as possible, ie. after any option
128 assignments from the command-line or from other commands have been
129 done. Thus, this is the place to to code option dependencies: if
130 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
131 long as 'foo' still has the same value it was assigned in
132 'initialize_options()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000133
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000134 This method must be implemented by all command classes.
135 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000136 raise RuntimeError, \
137 "abstract method -- subclass %s must override" % self.__class__
138
Greg Wardadda1562000-05-28 23:54:00 +0000139
140 def dump_options (self, header=None, indent=""):
141 from distutils.fancy_getopt import longopt_xlate
142 if header is None:
143 header = "command options for '%s':" % self.get_command_name()
144 print indent + header
145 indent = indent + " "
146 for (option, _, _) in self.user_options:
147 option = string.translate(option, longopt_xlate)
148 if option[-1] == "=":
149 option = option[:-1]
150 value = getattr(self, option)
151 print indent + "%s = %s" % (option, value)
152
153
Greg Wardfe6462c2000-04-04 01:40:52 +0000154 def run (self):
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000155 """A command's raison d'etre: carry out the action it exists to
156 perform, controlled by the options initialized in
157 'initialize_options()', customized by other commands, the setup
158 script, the command-line, and config files, and finalized in
159 'finalize_options()'. All terminal output and filesystem
160 interaction should be done by 'run()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000161
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000162 This method must be implemented by all command classes.
163 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000164
165 raise RuntimeError, \
166 "abstract method -- subclass %s must override" % self.__class__
167
168 def announce (self, msg, level=1):
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000169 """If the current verbosity level is of greater than or equal to
170 'level' print 'msg' to stdout.
171 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000172 if self.verbose >= level:
173 print msg
174
175
Greg Ward31413a72000-06-04 14:21:28 +0000176 # -- Option validation methods -------------------------------------
177 # (these are very handy in writing the 'finalize_options()' method)
178 #
179 # NB. the general philosophy here is to ensure that a particular option
180 # value meets certain type and value constraints. If not, we try to
181 # force it into conformance (eg. if we expect a list but have a string,
182 # split the string on comma and/or whitespace). If we can't force the
183 # option into conformance, raise DistutilsOptionError. Thus, command
184 # classes need do nothing more than (eg.)
185 # self.ensure_string_list('foo')
186 # and they can be guaranteed that thereafter, self.foo will be
187 # a list of strings.
188
189 def _ensure_stringlike (self, option, what, default=None):
190 val = getattr(self, option)
191 if val is None:
192 setattr(self, option, default)
193 return default
194 elif type(val) is not StringType:
195 raise DistutilsOptionError, \
196 "'%s' must be a %s (got `%s`)" % (option, what, val)
197 return val
198
199 def ensure_string (self, option, default=None):
200 """Ensure that 'option' is a string; if not defined, set it to
201 'default'.
202 """
203 self._ensure_stringlike(option, "string", default)
204
205 def ensure_string_list (self, option):
206 """Ensure that 'option' is a list of strings. If 'option' is
207 currently a string, we split it either on /,\s*/ or /\s+/, so
208 "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
209 ["foo", "bar", "baz"].
210 """
211 val = getattr(self, option)
212 if val is None:
213 return
214 elif type(val) is StringType:
215 setattr(self, option, re.split(r',\s*|\s+', val))
216 else:
217 if type(val) is ListType:
218 types = map(type, val)
219 ok = (types == [StringType] * len(val))
220 else:
221 ok = 0
222
223 if not ok:
224 raise DistutilsOptionError, \
225 "'%s' must be a list of strings (got %s)" % \
226 (option, `val`)
227
228 def _ensure_tested_string (self, option, tester,
229 what, error_fmt, default=None):
230 val = self._ensure_stringlike(option, what, default)
231 if val is not None and not tester(val):
232 raise DistutilsOptionError, \
233 ("error in '%s' option: " + error_fmt) % (option, val)
234
235 def ensure_filename (self, option):
236 """Ensure that 'option' is the name of an existing file."""
237 self._ensure_tested_string(option, os.path.isfile,
238 "filename",
239 "'%s' does not exist or is not a file")
240
241 def ensure_dirname (self, option):
242 self._ensure_tested_string(option, os.path.isdir,
243 "directory name",
244 "'%s' does not exist or is not a directory")
245
246
Greg Wardfe6462c2000-04-04 01:40:52 +0000247 # -- Convenience methods for commands ------------------------------
248
249 def get_command_name (self):
250 if hasattr (self, 'command_name'):
251 return self.command_name
252 else:
253 return self.__class__.__name__
254
255
256 def set_undefined_options (self, src_cmd, *option_pairs):
257 """Set the values of any "undefined" options from corresponding
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000258 option values in some other command object. "Undefined" here means
259 "is None", which is the convention used to indicate that an option
260 has not been changed between 'initialize_options()' and
261 'finalize_options()'. Usually called from 'finalize_options()' for
262 options that depend on some other command rather than another
263 option of the same command. 'src_cmd' is the other command from
264 which option values will be taken (a command object will be created
265 for it if necessary); the remaining arguments are
266 '(src_option,dst_option)' tuples which mean "take the value of
267 'src_option' in the 'src_cmd' command object, and copy it to
268 'dst_option' in the current command object".
269 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000270
271 # Option_pairs: list of (src_option, dst_option) tuples
272
Greg Ward5edcd902000-05-23 01:55:01 +0000273 src_cmd_obj = self.distribution.get_command_obj (src_cmd)
Greg Ward4fb29e52000-05-27 17:27:23 +0000274 src_cmd_obj.ensure_finalized ()
Greg Ward02a1a2b2000-04-15 22:15:07 +0000275 for (src_option, dst_option) in option_pairs:
276 if getattr (self, dst_option) is None:
Greg Wardf4f8e642000-05-07 15:29:15 +0000277 setattr (self, dst_option,
278 getattr (src_cmd_obj, src_option))
Greg Wardfe6462c2000-04-04 01:40:52 +0000279
280
Greg Ward4fb29e52000-05-27 17:27:23 +0000281 def get_finalized_command (self, command, create=1):
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000282 """Wrapper around Distribution's 'get_command_obj()' method: find
283 (create if necessary and 'create' is true) the command object for
284 'command', call its 'ensure_finalized()' method, and return the
285 finalized command object.
286 """
Greg Ward5edcd902000-05-23 01:55:01 +0000287 cmd_obj = self.distribution.get_command_obj (command, create)
Greg Ward4fb29e52000-05-27 17:27:23 +0000288 cmd_obj.ensure_finalized ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000289 return cmd_obj
290
Greg Ward308acf02000-06-01 01:08:52 +0000291 # XXX rename to 'get_reinitialized_command()'? (should do the
292 # same in dist.py, if so)
293 def reinitialize_command (self, command):
294 return self.distribution.reinitialize_command(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000295
Greg Ward4fb29e52000-05-27 17:27:23 +0000296 def run_command (self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000297 """Run some other command: uses the 'run_command()' method of
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000298 Distribution, which creates and finalizes the command object if
299 necessary and then invokes its 'run()' method.
300 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000301 self.distribution.run_command (command)
302
303
304 # -- External world manipulation -----------------------------------
305
306 def warn (self, msg):
307 sys.stderr.write ("warning: %s: %s\n" %
308 (self.get_command_name(), msg))
309
310
311 def execute (self, func, args, msg=None, level=1):
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000312 """Perform some action that affects the outside world (eg. by
313 writing to the filesystem). Such actions are special because they
314 should be disabled by the "dry run" flag, and should announce
315 themselves if the current verbosity level is high enough. This
316 method takes care of all that bureaucracy for you; all you have to
317 do is supply the funtion to call and an argument tuple for it (to
318 embody the "external action" being performed), a message to print
319 if the verbosity level is high enough, and an optional verbosity
320 threshold.
321 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000322
323 # Generate a message if we weren't passed one
324 if msg is None:
325 msg = "%s %s" % (func.__name__, `args`)
326 if msg[-2:] == ',)': # correct for singleton tuple
327 msg = msg[0:-2] + ')'
328
329 # Print it if verbosity level is high enough
330 self.announce (msg, level)
331
332 # And do it, as long as we're not in dry-run mode
333 if not self.dry_run:
334 apply (func, args)
335
336 # execute()
337
338
339 def mkpath (self, name, mode=0777):
340 util.mkpath (name, mode,
341 self.verbose, self.dry_run)
342
343
344 def copy_file (self, infile, outfile,
345 preserve_mode=1, preserve_times=1, link=None, level=1):
Greg Warde9613ae2000-04-10 01:30:44 +0000346 """Copy a file respecting verbose, dry-run and force flags. (The
347 former two default to whatever is in the Distribution object, and
348 the latter defaults to false for commands that don't define it.)"""
Greg Wardfe6462c2000-04-04 01:40:52 +0000349
350 return util.copy_file (infile, outfile,
351 preserve_mode, preserve_times,
352 not self.force,
353 link,
354 self.verbose >= level,
355 self.dry_run)
356
357
358 def copy_tree (self, infile, outfile,
359 preserve_mode=1, preserve_times=1, preserve_symlinks=0,
360 level=1):
361 """Copy an entire directory tree respecting verbose, dry-run,
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000362 and force flags.
363 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000364 return util.copy_tree (infile, outfile,
365 preserve_mode,preserve_times,preserve_symlinks,
366 not self.force,
367 self.verbose >= level,
368 self.dry_run)
369
370
371 def move_file (self, src, dst, level=1):
372 """Move a file respecting verbose and dry-run flags."""
373 return util.move_file (src, dst,
374 self.verbose >= level,
375 self.dry_run)
376
377
378 def spawn (self, cmd, search_path=1, level=1):
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000379 """Spawn an external command respecting verbose and dry-run flags."""
Greg Wardfe6462c2000-04-04 01:40:52 +0000380 from distutils.spawn import spawn
381 spawn (cmd, search_path,
382 self.verbose >= level,
383 self.dry_run)
384
385
386 def make_archive (self, base_name, format,
387 root_dir=None, base_dir=None):
Greg Ward308acf02000-06-01 01:08:52 +0000388 return util.make_archive (base_name, format, root_dir, base_dir,
389 self.verbose, self.dry_run)
Greg Wardfe6462c2000-04-04 01:40:52 +0000390
391
392 def make_file (self, infiles, outfile, func, args,
Greg Ward68a07572000-04-10 00:18:16 +0000393 exec_msg=None, skip_msg=None, level=1):
Greg Wardfe6462c2000-04-04 01:40:52 +0000394 """Special case of 'execute()' for operations that process one or
Greg Ward68a07572000-04-10 00:18:16 +0000395 more input files and generate one output file. Works just like
396 'execute()', except the operation is skipped and a different
397 message printed if 'outfile' already exists and is newer than all
398 files listed in 'infiles'. If the command defined 'self.force',
399 and it is true, then the command is unconditionally run -- does no
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000400 timestamp checks.
401 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000402 if exec_msg is None:
403 exec_msg = "generating %s from %s" % \
404 (outfile, string.join (infiles, ', '))
405 if skip_msg is None:
406 skip_msg = "skipping %s (inputs unchanged)" % outfile
407
408
409 # Allow 'infiles' to be a single string
410 if type (infiles) is StringType:
411 infiles = (infiles,)
412 elif type (infiles) not in (ListType, TupleType):
413 raise TypeError, \
414 "'infiles' must be a string, or a list or tuple of strings"
415
416 # If 'outfile' must be regenerated (either because it doesn't
417 # exist, is out-of-date, or the 'force' flag is true) then
418 # perform the action that presumably regenerates it
Greg Warde9613ae2000-04-10 01:30:44 +0000419 if self.force or util.newer_group (infiles, outfile):
Greg Wardfe6462c2000-04-04 01:40:52 +0000420 self.execute (func, args, exec_msg, level)
421
422 # Otherwise, print the "skip" message
423 else:
424 self.announce (skip_msg, level)
425
426 # make_file ()
427
428# class Command
Greg Wardb3612332000-04-09 03:48:37 +0000429
430
Greg Ward029e3022000-05-25 01:26:23 +0000431# XXX 'install_misc' class not currently used -- it was the base class for
432# both 'install_scripts' and 'install_data', but they outgrew it. It might
433# still be useful for 'install_headers', though, so I'm keeping it around
434# for the time being.
435
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000436class install_misc (Command):
437 """Common base class for installing some files in a subdirectory.
438 Currently used by install_data and install_scripts.
439 """
440
441 user_options = [('install-dir=', 'd', "directory to install the files to")]
442
443 def initialize_options (self):
444 self.install_dir = None
Gregory P. Smith21b9e912000-05-13 03:10:30 +0000445 self.outfiles = []
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000446
Gregory P. Smithce2b6b82000-05-12 01:31:37 +0000447 def _install_dir_from (self, dirname):
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000448 self.set_undefined_options('install', (dirname, 'install_dir'))
449
Gregory P. Smithce2b6b82000-05-12 01:31:37 +0000450 def _copy_files (self, filelist):
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000451 self.outfiles = []
452 if not filelist:
453 return
454 self.mkpath(self.install_dir)
455 for f in filelist:
Gregory P. Smithce2b6b82000-05-12 01:31:37 +0000456 self.copy_file(f, self.install_dir)
457 self.outfiles.append(os.path.join(self.install_dir, f))
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000458
Gregory P. Smithce2b6b82000-05-12 01:31:37 +0000459 def get_outputs (self):
460 return self.outfiles
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000461
462
Greg Wardb3612332000-04-09 03:48:37 +0000463if __name__ == "__main__":
464 print "ok"