Quick update to the README file. For intros and books we now point to
[python/dscho.git] / Lib / distutils / core.py
blob025e1c0df509786bf39176306ec68010087a2371
1 """distutils.core
3 The only module that needs to be imported to use the Distutils; provides
4 the 'setup' function (which must be called); the 'Distribution' class
5 (which may be subclassed if additional functionality is desired), and
6 the 'Command' class (which is used both internally by Distutils, and
7 may be subclassed by clients for still more flexibility)."""
9 # created 1999/03/01, Greg Ward
11 __revision__ = "$Id$"
13 import sys, os
14 import string, re
15 from types import *
16 from copy import copy
17 from distutils.errors import *
18 from distutils.fancy_getopt import fancy_getopt, print_help
19 from distutils import util
21 # Regex to define acceptable Distutils command names. This is not *quite*
22 # the same as a Python NAME -- I don't allow leading underscores. The fact
23 # that they're very similar is no coincidence; the default naming scheme is
24 # to look for a Python module named after the command.
25 command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
27 # This is a barebones help message generated displayed when the user
28 # runs the setup script with no arguments at all. More useful help
29 # is generated with various --help options: global help, list commands,
30 # and per-command help.
31 usage = """\
32 usage: %s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
33 or: %s --help
34 or: %s --help-commands
35 or: %s cmd --help
36 """ % ((sys.argv[0],) * 4)
39 def setup (**attrs):
40 """The gateway to the Distutils: do everything your setup script
41 needs to do, in a highly flexible and user-driven way. Briefly:
42 create a Distribution instance; parse the command-line, creating
43 and customizing instances of the command class for each command
44 found on the command-line; run each of those commands.
46 The Distribution instance might be an instance of a class
47 supplied via the 'distclass' keyword argument to 'setup'; if no
48 such class is supplied, then the 'Distribution' class (also in
49 this module) is instantiated. All other arguments to 'setup'
50 (except for 'cmdclass') are used to set attributes of the
51 Distribution instance.
53 The 'cmdclass' argument, if supplied, is a dictionary mapping
54 command names to command classes. Each command encountered on
55 the command line will be turned into a command class, which is in
56 turn instantiated; any class found in 'cmdclass' is used in place
57 of the default, which is (for command 'foo_bar') class 'foo_bar'
58 in module 'distutils.command.foo_bar'. The command class must
59 provide a 'user_options' attribute which is a list of option
60 specifiers for 'distutils.fancy_getopt'. Any command-line
61 options between the current and the next command are used to set
62 attributes of the current command object.
64 When the entire command-line has been successfully parsed, calls
65 the 'run()' method on each command object in turn. This method
66 will be driven entirely by the Distribution object (which each
67 command object has a reference to, thanks to its constructor),
68 and the command-specific options that became attributes of each
69 command object."""
71 # Determine the distribution class -- either caller-supplied or
72 # our Distribution (see below).
73 klass = attrs.get ('distclass')
74 if klass:
75 del attrs['distclass']
76 else:
77 klass = Distribution
79 # Create the Distribution instance, using the remaining arguments
80 # (ie. everything except distclass) to initialize it
81 dist = klass (attrs)
83 # If we had a config file, this is where we would parse it: override
84 # the client-supplied command options, but be overridden by the
85 # command line.
87 # Parse the command line; any command-line errors are the end-users
88 # fault, so turn them into SystemExit to suppress tracebacks.
89 try:
90 ok = dist.parse_command_line (sys.argv[1:])
91 except DistutilsArgError, msg:
92 sys.stderr.write (usage + "\n")
93 raise SystemExit, "error: %s" % msg
95 # And finally, run all the commands found on the command line.
96 if ok:
97 try:
98 dist.run_commands ()
99 except KeyboardInterrupt:
100 raise SystemExit, "interrupted"
101 except (OSError, IOError), exc:
102 # arg, try to work with Python pre-1.5.2
103 if hasattr (exc, 'filename') and hasattr (exc, 'strerror'):
104 raise SystemExit, \
105 "error: %s: %s" % (exc.filename, exc.strerror)
106 else:
107 raise SystemExit, str (exc)
108 except DistutilsExecError, msg:
109 raise SystemExit, "error: " + str (msg)
111 # setup ()
114 class Distribution:
115 """The core of the Distutils. Most of the work hiding behind
116 'setup' is really done within a Distribution instance, which
117 farms the work out to the Distutils commands specified on the
118 command line.
120 Clients will almost never instantiate Distribution directly,
121 unless the 'setup' function is totally inadequate to their needs.
122 However, it is conceivable that a client might wish to subclass
123 Distribution for some specialized purpose, and then pass the
124 subclass to 'setup' as the 'distclass' keyword argument. If so,
125 it is necessary to respect the expectations that 'setup' has of
126 Distribution: it must have a constructor and methods
127 'parse_command_line()' and 'run_commands()' with signatures like
128 those described below."""
131 # 'global_options' describes the command-line options that may be
132 # supplied to the client (setup.py) prior to any actual commands.
133 # Eg. "./setup.py -nv" or "./setup.py --verbose" both take advantage of
134 # these global options. This list should be kept to a bare minimum,
135 # since every global option is also valid as a command option -- and we
136 # don't want to pollute the commands with too many options that they
137 # have minimal control over.
138 global_options = [('verbose', 'v',
139 "run verbosely (default)"),
140 ('quiet', 'q',
141 "run quietly (turns verbosity off)"),
142 ('dry-run', 'n',
143 "don't actually do anything"),
144 ('force', 'f',
145 "skip dependency checking between files"),
146 ('help', 'h',
147 "show this help message"),
149 negative_opt = {'quiet': 'verbose'}
152 # -- Creation/initialization methods -------------------------------
154 def __init__ (self, attrs=None):
155 """Construct a new Distribution instance: initialize all the
156 attributes of a Distribution, and then uses 'attrs' (a
157 dictionary mapping attribute names to values) to assign
158 some of those attributes their "real" values. (Any attributes
159 not mentioned in 'attrs' will be assigned to some null
160 value: 0, None, an empty list or dictionary, etc.) Most
161 importantly, initialize the 'command_obj' attribute
162 to the empty dictionary; this will be filled in with real
163 command objects by 'parse_command_line()'."""
165 # Default values for our command-line options
166 self.verbose = 1
167 self.dry_run = 0
168 self.force = 0
169 self.help = 0
170 self.help_commands = 0
172 # And the "distribution meta-data" options -- these can only
173 # come from setup.py (the caller), not the command line
174 # (or a hypothetical config file).
175 self.name = None
176 self.version = None
177 self.author = None
178 self.author_email = None
179 self.maintainer = None
180 self.maintainer_email = None
181 self.url = None
182 self.licence = None
183 self.description = None
185 # 'cmdclass' maps command names to class objects, so we
186 # can 1) quickly figure out which class to instantiate when
187 # we need to create a new command object, and 2) have a way
188 # for the client to override command classes
189 self.cmdclass = {}
191 # These options are really the business of various commands, rather
192 # than of the Distribution itself. We provide aliases for them in
193 # Distribution as a convenience to the developer.
194 # dictionary.
195 self.packages = None
196 self.package_dir = None
197 self.py_modules = None
198 self.libraries = None
199 self.ext_modules = None
200 self.ext_package = None
201 self.include_dirs = None
202 self.extra_path = None
204 # And now initialize bookkeeping stuff that can't be supplied by
205 # the caller at all. 'command_obj' maps command names to
206 # Command instances -- that's how we enforce that every command
207 # class is a singleton.
208 self.command_obj = {}
210 # 'have_run' maps command names to boolean values; it keeps track
211 # of whether we have actually run a particular command, to make it
212 # cheap to "run" a command whenever we think we might need to -- if
213 # it's already been done, no need for expensive filesystem
214 # operations, we just check the 'have_run' dictionary and carry on.
215 # It's only safe to query 'have_run' for a command class that has
216 # been instantiated -- a false value will be inserted when the
217 # command object is created, and replaced with a true value when
218 # the command is succesfully run. Thus it's probably best to use
219 # '.get()' rather than a straight lookup.
220 self.have_run = {}
222 # Now we'll use the attrs dictionary (ultimately, keyword args from
223 # the client) to possibly override any or all of these distribution
224 # options.
225 if attrs:
227 # Pull out the set of command options and work on them
228 # specifically. Note that this order guarantees that aliased
229 # command options will override any supplied redundantly
230 # through the general options dictionary.
231 options = attrs.get ('options')
232 if options:
233 del attrs['options']
234 for (command, cmd_options) in options.items():
235 cmd_obj = self.find_command_obj (command)
236 for (key, val) in cmd_options.items():
237 cmd_obj.set_option (key, val)
238 # loop over commands
239 # if any command options
241 # Now work on the rest of the attributes. Any attribute that's
242 # not already defined is invalid!
243 for (key,val) in attrs.items():
244 if hasattr (self, key):
245 setattr (self, key, val)
246 else:
247 raise DistutilsOptionError, \
248 "invalid distribution option '%s'" % key
250 # __init__ ()
253 def parse_command_line (self, args):
254 """Parse the setup script's command line: set any Distribution
255 attributes tied to command-line options, create all command
256 objects, and set their options from the command-line. 'args'
257 must be a list of command-line arguments, most likely
258 'sys.argv[1:]' (see the 'setup()' function). This list is first
259 processed for "global options" -- options that set attributes of
260 the Distribution instance. Then, it is alternately scanned for
261 Distutils command and options for that command. Each new
262 command terminates the options for the previous command. The
263 allowed options for a command are determined by the 'options'
264 attribute of the command object -- thus, we instantiate (and
265 cache) every command object here, in order to access its
266 'options' attribute. Any error in that 'options' attribute
267 raises DistutilsGetoptError; any error on the command-line
268 raises DistutilsArgError. If no Distutils commands were found
269 on the command line, raises DistutilsArgError. Return true if
270 command-line successfully parsed and we should carry on with
271 executing commands; false if no errors but we shouldn't execute
272 commands (currently, this only happens if user asks for
273 help)."""
275 # We have to parse the command line a bit at a time -- global
276 # options, then the first command, then its options, and so on --
277 # because each command will be handled by a different class, and
278 # the options that are valid for a particular class aren't
279 # known until we instantiate the command class, which doesn't
280 # happen until we know what the command is.
282 self.commands = []
283 options = self.global_options + \
284 [('help-commands', None,
285 "list all available commands")]
286 args = fancy_getopt (options, self.negative_opt,
287 self, sys.argv[1:])
289 # User just wants a list of commands -- we'll print it out and stop
290 # processing now (ie. if they ran "setup --help-commands foo bar",
291 # we ignore "foo bar").
292 if self.help_commands:
293 self.print_commands ()
294 print
295 print usage
296 return
298 while args:
299 # Pull the current command from the head of the command line
300 command = args[0]
301 if not command_re.match (command):
302 raise SystemExit, "invalid command name '%s'" % command
303 self.commands.append (command)
305 # Make sure we have a command object to put the options into
306 # (this either pulls it out of a cache of command objects,
307 # or finds and instantiates the command class).
308 try:
309 cmd_obj = self.find_command_obj (command)
310 except DistutilsModuleError, msg:
311 raise DistutilsArgError, msg
313 # Require that the command class be derived from Command --
314 # that way, we can be sure that we at least have the 'run'
315 # and 'get_option' methods.
316 if not isinstance (cmd_obj, Command):
317 raise DistutilsClassError, \
318 "command class %s must subclass Command" % \
319 cmd_obj.__class__
321 # Also make sure that the command object provides a list of its
322 # known options
323 if not (hasattr (cmd_obj, 'user_options') and
324 type (cmd_obj.user_options) is ListType):
325 raise DistutilsClassError, \
326 ("command class %s must provide " +
327 "'user_options' attribute (a list of tuples)") % \
328 cmd_obj.__class__
330 # Poof! like magic, all commands support the global
331 # options too, just by adding in 'global_options'.
332 negative_opt = self.negative_opt
333 if hasattr (cmd_obj, 'negative_opt'):
334 negative_opt = copy (negative_opt)
335 negative_opt.update (cmd_obj.negative_opt)
337 options = self.global_options + cmd_obj.user_options
338 args = fancy_getopt (options, negative_opt,
339 cmd_obj, args[1:])
340 if cmd_obj.help:
341 print_help (self.global_options,
342 header="Global options:")
343 print
344 print_help (cmd_obj.user_options,
345 header="Options for '%s' command:" % command)
346 print
347 print usage
348 return
350 self.command_obj[command] = cmd_obj
351 self.have_run[command] = 0
353 # while args
355 # If the user wants help -- ie. they gave the "--help" option --
356 # give it to 'em. We do this *after* processing the commands in
357 # case they want help on any particular command, eg.
358 # "setup.py --help foo". (This isn't the documented way to
359 # get help on a command, but I support it because that's how
360 # CVS does it -- might as well be consistent.)
361 if self.help:
362 print_help (self.global_options, header="Global options:")
363 print
365 for command in self.commands:
366 klass = self.find_command_class (command)
367 print_help (klass.user_options,
368 header="Options for '%s' command:" % command)
369 print
371 print usage
372 return
374 # Oops, no commands found -- an end-user error
375 if not self.commands:
376 raise DistutilsArgError, "no commands supplied"
378 # All is well: return true
379 return 1
381 # parse_command_line()
384 def print_command_list (self, commands, header, max_length):
385 """Print a subset of the list of all commands -- used by
386 'print_commands()'."""
388 print header + ":"
390 for cmd in commands:
391 klass = self.cmdclass.get (cmd)
392 if not klass:
393 klass = self.find_command_class (cmd)
394 try:
395 description = klass.description
396 except AttributeError:
397 description = "(no description available)"
399 print " %-*s %s" % (max_length, cmd, description)
401 # print_command_list ()
404 def print_commands (self):
405 """Print out a help message listing all available commands with
406 a description of each. The list is divided into "standard
407 commands" (listed in distutils.command.__all__) and "extra
408 commands" (mentioned in self.cmdclass, but not a standard
409 command). The descriptions come from the command class
410 attribute 'description'."""
412 import distutils.command
413 std_commands = distutils.command.__all__
414 is_std = {}
415 for cmd in std_commands:
416 is_std[cmd] = 1
418 extra_commands = []
419 for cmd in self.cmdclass.keys():
420 if not is_std.get(cmd):
421 extra_commands.append (cmd)
423 max_length = 0
424 for cmd in (std_commands + extra_commands):
425 if len (cmd) > max_length:
426 max_length = len (cmd)
428 self.print_command_list (std_commands,
429 "Standard commands",
430 max_length)
431 if extra_commands:
432 print
433 self.print_command_list (extra_commands,
434 "Extra commands",
435 max_length)
437 # print_commands ()
441 # -- Command class/object methods ----------------------------------
443 # This is a method just so it can be overridden if desired; it doesn't
444 # actually use or change any attributes of the Distribution instance.
445 def find_command_class (self, command):
446 """Given a command, derives the names of the module and class
447 expected to implement the command: eg. 'foo_bar' becomes
448 'distutils.command.foo_bar' (the module) and 'FooBar' (the
449 class within that module). Loads the module, extracts the
450 class from it, and returns the class object.
452 Raises DistutilsModuleError with a semi-user-targeted error
453 message if the expected module could not be loaded, or the
454 expected class was not found in it."""
456 module_name = 'distutils.command.' + command
457 klass_name = command
459 try:
460 __import__ (module_name)
461 module = sys.modules[module_name]
462 except ImportError:
463 raise DistutilsModuleError, \
464 "invalid command '%s' (no module named '%s')" % \
465 (command, module_name)
467 try:
468 klass = vars(module)[klass_name]
469 except KeyError:
470 raise DistutilsModuleError, \
471 "invalid command '%s' (no class '%s' in module '%s')" \
472 % (command, klass_name, module_name)
474 return klass
476 # find_command_class ()
479 def create_command_obj (self, command):
480 """Figure out the class that should implement a command,
481 instantiate it, cache and return the new "command object".
482 The "command class" is determined either by looking it up in
483 the 'cmdclass' attribute (this is the mechanism whereby
484 clients may override default Distutils commands or add their
485 own), or by calling the 'find_command_class()' method (if the
486 command name is not in 'cmdclass'."""
488 # Determine the command class -- either it's in the command_class
489 # dictionary, or we have to divine the module and class name
490 klass = self.cmdclass.get(command)
491 if not klass:
492 klass = self.find_command_class (command)
493 self.cmdclass[command] = klass
495 # Found the class OK -- instantiate it
496 cmd_obj = klass (self)
497 return cmd_obj
500 def find_command_obj (self, command, create=1):
501 """Look up and return a command object in the cache maintained by
502 'create_command_obj()'. If none found, the action taken
503 depends on 'create': if true (the default), create a new
504 command object by calling 'create_command_obj()' and return
505 it; otherwise, return None. If 'command' is an invalid
506 command name, then DistutilsModuleError will be raised."""
508 cmd_obj = self.command_obj.get (command)
509 if not cmd_obj and create:
510 cmd_obj = self.create_command_obj (command)
511 self.command_obj[command] = cmd_obj
513 return cmd_obj
516 # -- Methods that operate on the Distribution ----------------------
518 def announce (self, msg, level=1):
519 """Print 'msg' if 'level' is greater than or equal to the verbosity
520 level recorded in the 'verbose' attribute (which, currently,
521 can be only 0 or 1)."""
523 if self.verbose >= level:
524 print msg
527 def run_commands (self):
528 """Run each command that was seen on the client command line.
529 Uses the list of commands found and cache of command objects
530 created by 'create_command_obj()'."""
532 for cmd in self.commands:
533 self.run_command (cmd)
536 def get_option (self, option):
537 """Return the value of a distribution option. Raise
538 DistutilsOptionError if 'option' is not known."""
540 try:
541 return getattr (self, opt)
542 except AttributeError:
543 raise DistutilsOptionError, \
544 "unknown distribution option %s" % option
547 def get_options (self, *options):
548 """Return (as a tuple) the values of several distribution
549 options. Raise DistutilsOptionError if any element of
550 'options' is not known."""
552 values = []
553 try:
554 for opt in options:
555 values.append (getattr (self, opt))
556 except AttributeError, name:
557 raise DistutilsOptionError, \
558 "unknown distribution option %s" % name
560 return tuple (values)
563 # -- Methods that operate on its Commands --------------------------
565 def run_command (self, command):
567 """Do whatever it takes to run a command (including nothing at all,
568 if the command has already been run). Specifically: if we have
569 already created and run the command named by 'command', return
570 silently without doing anything. If the command named by
571 'command' doesn't even have a command object yet, create one.
572 Then invoke 'run()' on that command object (or an existing
573 one)."""
575 # Already been here, done that? then return silently.
576 if self.have_run.get (command):
577 return
579 self.announce ("running " + command)
580 cmd_obj = self.find_command_obj (command)
581 cmd_obj.ensure_ready ()
582 cmd_obj.run ()
583 self.have_run[command] = 1
586 def get_command_option (self, command, option):
587 """Create a command object for 'command' if necessary, ensure that
588 its option values are all set to their final values, and return
589 the value of its 'option' option. Raise DistutilsOptionError if
590 'option' is not known for that 'command'."""
592 cmd_obj = self.find_command_obj (command)
593 cmd_obj.ensure_ready ()
594 return cmd_obj.get_option (option)
595 try:
596 return getattr (cmd_obj, option)
597 except AttributeError:
598 raise DistutilsOptionError, \
599 "command %s: no such option %s" % (command, option)
602 def get_command_options (self, command, *options):
603 """Create a command object for 'command' if necessary, ensure that
604 its option values are all set to their final values, and return
605 a tuple containing the values of all the options listed in
606 'options' for that command. Raise DistutilsOptionError if any
607 invalid option is supplied in 'options'."""
609 cmd_obj = self.find_command_obj (command)
610 cmd_obj.ensure_ready ()
611 values = []
612 try:
613 for opt in options:
614 values.append (getattr (cmd_obj, option))
615 except AttributeError, name:
616 raise DistutilsOptionError, \
617 "command %s: no such option %s" % (command, name)
619 return tuple (values)
622 # -- Distribution query methods ------------------------------------
624 def has_pure_modules (self):
625 return len (self.packages or self.py_modules or []) > 0
627 def has_ext_modules (self):
628 return self.ext_modules and len (self.ext_modules) > 0
630 def has_c_libraries (self):
631 return self.libraries and len (self.libraries) > 0
633 def has_modules (self):
634 return self.has_pure_modules() or self.has_ext_modules()
636 def is_pure (self):
637 return (self.has_pure_modules() and
638 not self.has_ext_modules() and
639 not self.has_c_libraries())
641 def get_name (self):
642 return self.name or "UNKNOWN"
644 def get_full_name (self):
645 return "%s-%s" % ((self.name or "UNKNOWN"), (self.version or "???"))
648 # class Distribution
651 class Command:
652 """Abstract base class for defining command classes, the "worker bees"
653 of the Distutils. A useful analogy for command classes is to
654 think of them as subroutines with local variables called
655 "options". The options are "declared" in 'initialize_options()'
656 and "defined" (given their final values, aka "finalized") in
657 'finalize_options()', both of which must be defined by every
658 command class. The distinction between the two is necessary
659 because option values might come from the outside world (command
660 line, option file, ...), and any options dependent on other
661 options must be computed *after* these outside influences have
662 been processed -- hence 'finalize_options()'. The "body" of the
663 subroutine, where it does all its work based on the values of its
664 options, is the 'run()' method, which must also be implemented by
665 every command class."""
667 # -- Creation/initialization methods -------------------------------
669 def __init__ (self, dist):
670 """Create and initialize a new Command object. Most importantly,
671 invokes the 'initialize_options()' method, which is the
672 real initializer and depends on the actual command being
673 instantiated."""
675 if not isinstance (dist, Distribution):
676 raise TypeError, "dist must be a Distribution instance"
677 if self.__class__ is Command:
678 raise RuntimeError, "Command is an abstract class"
680 self.distribution = dist
681 self.initialize_options ()
683 # Per-command versions of the global flags, so that the user can
684 # customize Distutils' behaviour command-by-command and let some
685 # commands fallback on the Distribution's behaviour. None means
686 # "not defined, check self.distribution's copy", while 0 or 1 mean
687 # false and true (duh). Note that this means figuring out the real
688 # value of each flag is a touch complicatd -- hence "self.verbose"
689 # (etc.) will be handled by __getattr__, below.
690 self._verbose = None
691 self._dry_run = None
692 self._force = None
694 # The 'help' flag is just used for command-line parsing, so
695 # none of that complicated bureaucracy is needed.
696 self.help = 0
698 # 'ready' records whether or not 'finalize_options()' has been
699 # called. 'finalize_options()' itself should not pay attention to
700 # this flag: it is the business of 'ensure_ready()', which always
701 # calls 'finalize_options()', to respect/update it.
702 self.ready = 0
704 # end __init__ ()
707 def __getattr__ (self, attr):
708 if attr in ('verbose', 'dry_run', 'force'):
709 myval = getattr (self, "_" + attr)
710 if myval is None:
711 return getattr (self.distribution, attr)
712 else:
713 return myval
714 else:
715 raise AttributeError, attr
718 def ensure_ready (self):
719 if not self.ready:
720 self.finalize_options ()
721 self.ready = 1
724 # Subclasses must define:
725 # initialize_options()
726 # provide default values for all options; may be overridden
727 # by Distutils client, by command-line options, or by options
728 # from option file
729 # finalize_options()
730 # decide on the final values for all options; this is called
731 # after all possible intervention from the outside world
732 # (command-line, option file, etc.) has been processed
733 # run()
734 # run the command: do whatever it is we're here to do,
735 # controlled by the command's various option values
737 def initialize_options (self):
738 """Set default values for all the options that this command
739 supports. Note that these defaults may be overridden
740 by the command-line supplied by the user; thus, this is
741 not the place to code dependencies between options; generally,
742 'initialize_options()' implementations are just a bunch
743 of "self.foo = None" assignments.
745 This method must be implemented by all command classes."""
747 raise RuntimeError, \
748 "abstract method -- subclass %s must override" % self.__class__
750 def finalize_options (self):
751 """Set final values for all the options that this command
752 supports. This is always called as late as possible, ie.
753 after any option assignments from the command-line or from
754 other commands have been done. Thus, this is the place to to
755 code option dependencies: if 'foo' depends on 'bar', then it
756 is safe to set 'foo' from 'bar' as long as 'foo' still has
757 the same value it was assigned in 'initialize_options()'.
759 This method must be implemented by all command classes."""
761 raise RuntimeError, \
762 "abstract method -- subclass %s must override" % self.__class__
764 def run (self):
765 """A command's raison d'etre: carry out the action it exists
766 to perform, controlled by the options initialized in
767 'initialize_options()', customized by the user and other
768 commands, and finalized in 'finalize_options()'. All
769 terminal output and filesystem interaction should be done by
770 'run()'.
772 This method must be implemented by all command classes."""
774 raise RuntimeError, \
775 "abstract method -- subclass %s must override" % self.__class__
777 def announce (self, msg, level=1):
778 """If the Distribution instance to which this command belongs
779 has a verbosity level of greater than or equal to 'level'
780 print 'msg' to stdout."""
782 if self.verbose >= level:
783 print msg
786 # -- Option query/set methods --------------------------------------
788 def get_option (self, option):
789 """Return the value of a single option for this command. Raise
790 DistutilsOptionError if 'option' is not known."""
791 try:
792 return getattr (self, option)
793 except AttributeError:
794 raise DistutilsOptionError, \
795 "command %s: no such option %s" % \
796 (self.get_command_name(), option)
799 def get_options (self, *options):
800 """Return (as a tuple) the values of several options for this
801 command. Raise DistutilsOptionError if any of the options in
802 'options' are not known."""
804 values = []
805 try:
806 for opt in options:
807 values.append (getattr (self, opt))
808 except AttributeError, name:
809 raise DistutilsOptionError, \
810 "command %s: no such option %s" % \
811 (self.get_command_name(), name)
813 return tuple (values)
816 def set_option (self, option, value):
817 """Set the value of a single option for this command. Raise
818 DistutilsOptionError if 'option' is not known."""
820 if not hasattr (self, option):
821 raise DistutilsOptionError, \
822 "command '%s': no such option '%s'" % \
823 (self.get_command_name(), option)
824 if value is not None:
825 setattr (self, option, value)
827 def set_options (self, **optval):
828 """Set the values of several options for this command. Raise
829 DistutilsOptionError if any of the options specified as
830 keyword arguments are not known."""
832 for k in optval.keys():
833 if optval[k] is not None:
834 self.set_option (k, optval[k])
837 # -- Convenience methods for commands ------------------------------
839 def get_command_name (self):
840 if hasattr (self, 'command_name'):
841 return self.command_name
842 else:
843 class_name = self.__class__.__name__
845 # The re.split here returs empty strings delimited by the
846 # words we're actually interested in -- e.g. "FooBarBaz"
847 # splits to ['', 'Foo', '', 'Bar', '', 'Baz', '']. Hence
848 # the 'filter' to strip out the empties.
849 words = filter (None, re.split (r'([A-Z][a-z]+)', class_name))
850 self.command_name = string.join (map (string.lower, words), "_")
851 return self.command_name
854 def set_undefined_options (self, src_cmd, *option_pairs):
855 """Set the values of any "undefined" options from corresponding
856 option values in some other command object. "Undefined" here
857 means "is None", which is the convention used to indicate
858 that an option has not been changed between
859 'set_initial_values()' and 'set_final_values()'. Usually
860 called from 'set_final_values()' for options that depend on
861 some other command rather than another option of the same
862 command. 'src_cmd' is the other command from which option
863 values will be taken (a command object will be created for it
864 if necessary); the remaining arguments are
865 '(src_option,dst_option)' tuples which mean "take the value
866 of 'src_option' in the 'src_cmd' command object, and copy it
867 to 'dst_option' in the current command object"."""
869 # Option_pairs: list of (src_option, dst_option) tuples
871 src_cmd_obj = self.distribution.find_command_obj (src_cmd)
872 src_cmd_obj.ensure_ready ()
873 try:
874 for (src_option, dst_option) in option_pairs:
875 if getattr (self, dst_option) is None:
876 self.set_option (dst_option,
877 src_cmd_obj.get_option (src_option))
878 except AttributeError, name:
879 # duh, which command?
880 raise DistutilsOptionError, "unknown option %s" % name
883 def find_peer (self, command, create=1):
884 """Wrapper around Distribution's 'find_command_obj()' method:
885 find (create if necessary and 'create' is true) the command
886 object for 'command'.."""
888 cmd_obj = self.distribution.find_command_obj (command, create)
889 cmd_obj.ensure_ready ()
890 return cmd_obj
893 def get_peer_option (self, command, option):
894 """Find or create the command object for 'command', and return
895 its 'option' option."""
897 cmd_obj = self.find_peer (command)
898 return cmd_obj.get_option (option)
901 def run_peer (self, command):
902 """Run some other command: uses the 'run_command()' method of
903 Distribution, which creates the command object if necessary
904 and then invokes its 'run()' method."""
906 self.distribution.run_command (command)
909 # -- External world manipulation -----------------------------------
911 def warn (self, msg):
912 sys.stderr.write ("warning: %s: %s\n" %
913 (self.get_command_name(), msg))
916 def execute (self, func, args, msg=None, level=1):
917 """Perform some action that affects the outside world (eg.
918 by writing to the filesystem). Such actions are special because
919 they should be disabled by the "dry run" flag, and should
920 announce themselves if the current verbosity level is high
921 enough. This method takes care of all that bureaucracy for you;
922 all you have to do is supply the funtion to call and an argument
923 tuple for it (to embody the "external action" being performed),
924 a message to print if the verbosity level is high enough, and an
925 optional verbosity threshold."""
927 # Generate a message if we weren't passed one
928 if msg is None:
929 msg = "%s %s" % (func.__name__, `args`)
930 if msg[-2:] == ',)': # correct for singleton tuple
931 msg = msg[0:-2] + ')'
933 # Print it if verbosity level is high enough
934 self.announce (msg, level)
936 # And do it, as long as we're not in dry-run mode
937 if not self.dry_run:
938 apply (func, args)
940 # execute()
943 def mkpath (self, name, mode=0777):
944 util.mkpath (name, mode,
945 self.verbose, self.dry_run)
948 def copy_file (self, infile, outfile,
949 preserve_mode=1, preserve_times=1, link=None, level=1):
950 """Copy a file respecting verbose, dry-run and force flags."""
952 return util.copy_file (infile, outfile,
953 preserve_mode, preserve_times,
954 not self.force,
955 link,
956 self.verbose >= level,
957 self.dry_run)
960 def copy_tree (self, infile, outfile,
961 preserve_mode=1, preserve_times=1, preserve_symlinks=0,
962 level=1):
963 """Copy an entire directory tree respecting verbose, dry-run,
964 and force flags."""
966 return util.copy_tree (infile, outfile,
967 preserve_mode,preserve_times,preserve_symlinks,
968 not self.force,
969 self.verbose >= level,
970 self.dry_run)
973 def move_file (self, src, dst, level=1):
974 """Move a file respecting verbose and dry-run flags."""
975 return util.move_file (src, dst,
976 self.verbose >= level,
977 self.dry_run)
980 def spawn (self, cmd, search_path=1, level=1):
981 from distutils.spawn import spawn
982 spawn (cmd, search_path,
983 self.verbose >= level,
984 self.dry_run)
987 def make_archive (self, base_name, format,
988 root_dir=None, base_dir=None):
989 util.make_archive (base_name, format, root_dir, base_dir,
990 self.verbose, self.dry_run)
993 def make_file (self, infiles, outfile, func, args,
994 exec_msg=None, skip_msg=None, level=1):
996 """Special case of 'execute()' for operations that process one or
997 more input files and generate one output file. Works just like
998 'execute()', except the operation is skipped and a different
999 message printed if 'outfile' already exists and is newer than
1000 all files listed in 'infiles'."""
1003 if exec_msg is None:
1004 exec_msg = "generating %s from %s" % \
1005 (outfile, string.join (infiles, ', '))
1006 if skip_msg is None:
1007 skip_msg = "skipping %s (inputs unchanged)" % outfile
1010 # Allow 'infiles' to be a single string
1011 if type (infiles) is StringType:
1012 infiles = (infiles,)
1013 elif type (infiles) not in (ListType, TupleType):
1014 raise TypeError, \
1015 "'infiles' must be a string, or a list or tuple of strings"
1017 # If 'outfile' must be regenerated (either because it doesn't
1018 # exist, is out-of-date, or the 'force' flag is true) then
1019 # perform the action that presumably regenerates it
1020 if self.force or util.newer_group (infiles, outfile):
1021 self.execute (func, args, exec_msg, level)
1023 # Otherwise, print the "skip" message
1024 else:
1025 self.announce (skip_msg, level)
1027 # make_file ()
1029 # class Command