blob: de4f7ef0a281b5dc26b93e749b4319272625da64 [file] [log] [blame]
Greg Wardfe6462c2000-04-04 01:40:52 +00001"""distutils.dist
2
3Provides the Distribution class, which represents the module distribution
4being built/installed/distributed."""
5
6# created 2000/04/03, Greg Ward
7# (extricated from core.py; actually dates back to the beginning)
8
9__revision__ = "$Id$"
10
Gregory P. Smith14263542000-05-12 00:41:33 +000011import sys, os, string, re
Greg Wardfe6462c2000-04-04 01:40:52 +000012from types import *
13from copy import copy
14from distutils.errors import *
Greg Ward36c36fe2000-05-20 14:07:59 +000015from distutils import sysconfig
Greg Ward82715e12000-04-21 02:28:14 +000016from distutils.fancy_getopt import FancyGetopt, longopt_xlate
Gregory P. Smith14263542000-05-12 00:41:33 +000017from distutils.util import check_environ
Greg Wardfe6462c2000-04-04 01:40:52 +000018
19
20# Regex to define acceptable Distutils command names. This is not *quite*
21# the same as a Python NAME -- I don't allow leading underscores. The fact
22# that they're very similar is no coincidence; the default naming scheme is
23# to look for a Python module named after the command.
24command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
25
26
27class Distribution:
28 """The core of the Distutils. Most of the work hiding behind
29 'setup' is really done within a Distribution instance, which
30 farms the work out to the Distutils commands specified on the
31 command line.
32
33 Clients will almost never instantiate Distribution directly,
34 unless the 'setup' function is totally inadequate to their needs.
35 However, it is conceivable that a client might wish to subclass
36 Distribution for some specialized purpose, and then pass the
37 subclass to 'setup' as the 'distclass' keyword argument. If so,
38 it is necessary to respect the expectations that 'setup' has of
39 Distribution: it must have a constructor and methods
40 'parse_command_line()' and 'run_commands()' with signatures like
41 those described below."""
42
43
44 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000045 # supplied to the setup script prior to any actual commands.
46 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000047 # these global options. This list should be kept to a bare minimum,
48 # since every global option is also valid as a command option -- and we
49 # don't want to pollute the commands with too many options that they
50 # have minimal control over.
Greg Wardd5d8a992000-05-23 01:42:17 +000051 global_options = [('verbose', 'v', "run verbosely (default)"),
52 ('quiet', 'q', "run quietly (turns verbosity off)"),
53 ('dry-run', 'n', "don't actually do anything"),
54 ('help', 'h', "show detailed help message"),
Greg Wardfe6462c2000-04-04 01:40:52 +000055 ]
Greg Ward82715e12000-04-21 02:28:14 +000056
57 # options that are not propagated to the commands
58 display_options = [
59 ('help-commands', None,
60 "list all available commands"),
61 ('name', None,
62 "print package name"),
63 ('version', 'V',
64 "print package version"),
65 ('fullname', None,
66 "print <package name>-<version>"),
67 ('author', None,
68 "print the author's name"),
69 ('author-email', None,
70 "print the author's email address"),
71 ('maintainer', None,
72 "print the maintainer's name"),
73 ('maintainer-email', None,
74 "print the maintainer's email address"),
75 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000076 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000077 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000078 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000079 ('url', None,
80 "print the URL for this package"),
81 ('licence', None,
82 "print the licence of the package"),
83 ('license', None,
84 "alias for --licence"),
85 ('description', None,
86 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +000087 ('long-description', None,
88 "print the long package description"),
Greg Ward82715e12000-04-21 02:28:14 +000089 ]
90 display_option_names = map(lambda x: string.translate(x[0], longopt_xlate),
91 display_options)
92
93 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +000094 negative_opt = {'quiet': 'verbose'}
95
96
97 # -- Creation/initialization methods -------------------------------
98
99 def __init__ (self, attrs=None):
100 """Construct a new Distribution instance: initialize all the
101 attributes of a Distribution, and then uses 'attrs' (a
102 dictionary mapping attribute names to values) to assign
103 some of those attributes their "real" values. (Any attributes
104 not mentioned in 'attrs' will be assigned to some null
105 value: 0, None, an empty list or dictionary, etc.) Most
106 importantly, initialize the 'command_obj' attribute
107 to the empty dictionary; this will be filled in with real
108 command objects by 'parse_command_line()'."""
109
110 # Default values for our command-line options
111 self.verbose = 1
112 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000113 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000114 for attr in self.display_option_names:
115 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000116
Greg Ward82715e12000-04-21 02:28:14 +0000117 # Store the distribution meta-data (name, version, author, and so
118 # forth) in a separate object -- we're getting to have enough
119 # information here (and enough command-line options) that it's
120 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
121 # object in a sneaky and underhanded (but efficient!) way.
122 self.metadata = DistributionMetadata ()
Greg Ward4982f982000-04-22 02:52:44 +0000123 method_basenames = dir(self.metadata) + \
124 ['fullname', 'contact', 'contact_email']
125 for basename in method_basenames:
126 method_name = "get_" + basename
127 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000128
129 # 'cmdclass' maps command names to class objects, so we
130 # can 1) quickly figure out which class to instantiate when
131 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000132 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000133 self.cmdclass = {}
134
Greg Wardd5d8a992000-05-23 01:42:17 +0000135 # 'command_options' is where we store command options between
136 # parsing them (from config files, the command-line, etc.) and when
137 # they are actually needed -- ie. when the command in question is
138 # instantiated. It is a dictionary of dictionaries of 2-tuples:
139 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000140 self.command_options = {}
141
Greg Wardfe6462c2000-04-04 01:40:52 +0000142 # These options are really the business of various commands, rather
143 # than of the Distribution itself. We provide aliases for them in
144 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000145 self.packages = None
146 self.package_dir = None
147 self.py_modules = None
148 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000149 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000150 self.ext_modules = None
151 self.ext_package = None
152 self.include_dirs = None
153 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000154 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000155 self.data_files = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000156
157 # And now initialize bookkeeping stuff that can't be supplied by
158 # the caller at all. 'command_obj' maps command names to
159 # Command instances -- that's how we enforce that every command
160 # class is a singleton.
161 self.command_obj = {}
162
163 # 'have_run' maps command names to boolean values; it keeps track
164 # of whether we have actually run a particular command, to make it
165 # cheap to "run" a command whenever we think we might need to -- if
166 # it's already been done, no need for expensive filesystem
167 # operations, we just check the 'have_run' dictionary and carry on.
168 # It's only safe to query 'have_run' for a command class that has
169 # been instantiated -- a false value will be inserted when the
170 # command object is created, and replaced with a true value when
171 # the command is succesfully run. Thus it's probably best to use
172 # '.get()' rather than a straight lookup.
173 self.have_run = {}
174
175 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000176 # the setup script) to possibly override any or all of these
177 # distribution options.
178
Greg Wardfe6462c2000-04-04 01:40:52 +0000179 if attrs:
180
181 # Pull out the set of command options and work on them
182 # specifically. Note that this order guarantees that aliased
183 # command options will override any supplied redundantly
184 # through the general options dictionary.
185 options = attrs.get ('options')
186 if options:
187 del attrs['options']
188 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000189 opt_dict = self.get_option_dict(command)
190 for (opt, val) in cmd_options.items():
191 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000192
193 # Now work on the rest of the attributes. Any attribute that's
194 # not already defined is invalid!
195 for (key,val) in attrs.items():
Greg Ward82715e12000-04-21 02:28:14 +0000196 if hasattr (self.metadata, key):
197 setattr (self.metadata, key, val)
198 elif hasattr (self, key):
Greg Wardfe6462c2000-04-04 01:40:52 +0000199 setattr (self, key, val)
200 else:
Greg Ward02a1a2b2000-04-15 22:15:07 +0000201 raise DistutilsSetupError, \
Greg Wardfe6462c2000-04-04 01:40:52 +0000202 "invalid distribution option '%s'" % key
203
204 # __init__ ()
205
206
Greg Ward0e48cfd2000-05-26 01:00:15 +0000207 def get_option_dict (self, command):
208 """Get the option dictionary for a given command. If that
209 command's option dictionary hasn't been created yet, then create it
210 and return the new dictionary; otherwise, return the existing
211 option dictionary.
212 """
213
214 dict = self.command_options.get(command)
215 if dict is None:
216 dict = self.command_options[command] = {}
217 return dict
218
219
Greg Wardc32d9a62000-05-28 23:53:06 +0000220 def dump_option_dicts (self, header=None, commands=None, indent=""):
221 from pprint import pformat
222
223 if commands is None: # dump all command option dicts
224 commands = self.command_options.keys()
225 commands.sort()
226
227 if header is not None:
228 print indent + header
229 indent = indent + " "
230
231 if not commands:
232 print indent + "no commands known yet"
233 return
234
235 for cmd_name in commands:
236 opt_dict = self.command_options.get(cmd_name)
237 if opt_dict is None:
238 print indent + "no option dict for '%s' command" % cmd_name
239 else:
240 print indent + "option dict for '%s' command:" % cmd_name
241 out = pformat(opt_dict)
242 for line in string.split(out, "\n"):
243 print indent + " " + line
244
245 # dump_option_dicts ()
246
247
248
Greg Wardd5d8a992000-05-23 01:42:17 +0000249 # -- Config file finding/parsing methods ---------------------------
250
Gregory P. Smith14263542000-05-12 00:41:33 +0000251 def find_config_files (self):
252 """Find as many configuration files as should be processed for this
253 platform, and return a list of filenames in the order in which they
254 should be parsed. The filenames returned are guaranteed to exist
255 (modulo nasty race conditions).
256
257 On Unix, there are three possible config files: pydistutils.cfg in
258 the Distutils installation directory (ie. where the top-level
259 Distutils __inst__.py file lives), .pydistutils.cfg in the user's
260 home directory, and setup.cfg in the current directory.
261
262 On Windows and Mac OS, there are two possible config files:
263 pydistutils.cfg in the Python installation directory (sys.prefix)
Greg Wardd5d8a992000-05-23 01:42:17 +0000264 and setup.cfg in the current directory.
265 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000266 files = []
267 if os.name == "posix":
268 check_environ()
269
270 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
271 sys_file = os.path.join(sys_dir, "pydistutils.cfg")
272 if os.path.isfile(sys_file):
273 files.append(sys_file)
274
275 user_file = os.path.join(os.environ.get('HOME'),
276 ".pydistutils.cfg")
277 if os.path.isfile(user_file):
278 files.append(user_file)
279
280 else:
281 sys_file = os.path.join (sysconfig.PREFIX, "pydistutils.cfg")
282 if os.path.isfile(sys_file):
283 files.append(sys_file)
284
285 # All platforms support local setup.cfg
286 local_file = "setup.cfg"
287 if os.path.isfile(local_file):
288 files.append(local_file)
289
290 return files
291
292 # find_config_files ()
293
294
295 def parse_config_files (self, filenames=None):
296
297 from ConfigParser import ConfigParser
298
299 if filenames is None:
300 filenames = self.find_config_files()
301
Greg Ward47460772000-05-23 03:47:35 +0000302 print "Distribution.parse_config_files():"
303
Gregory P. Smith14263542000-05-12 00:41:33 +0000304 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000305 for filename in filenames:
Greg Ward47460772000-05-23 03:47:35 +0000306 print " reading", filename
Greg Wardd5d8a992000-05-23 01:42:17 +0000307 parser.read(filename)
308 for section in parser.sections():
309 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000310 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000311
Greg Wardd5d8a992000-05-23 01:42:17 +0000312 for opt in options:
313 if opt != '__name__':
Greg Ward0e48cfd2000-05-26 01:00:15 +0000314 opt_dict[opt] = (filename, parser.get(section,opt))
Gregory P. Smith14263542000-05-12 00:41:33 +0000315
Greg Ward47460772000-05-23 03:47:35 +0000316 # Make the ConfigParser forget everything (so we retain
317 # the original filenames that options come from) -- gag,
318 # retch, puke -- another good reason for a distutils-
319 # specific config parser (sigh...)
320 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000321
322
Greg Wardd5d8a992000-05-23 01:42:17 +0000323 # -- Command-line parsing methods ----------------------------------
324
Greg Wardfe6462c2000-04-04 01:40:52 +0000325 def parse_command_line (self, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000326 """Parse the setup script's command line. 'args' must be a list
327 of command-line arguments, most likely 'sys.argv[1:]' (see the
328 'setup()' function). This list is first processed for "global
329 options" -- options that set attributes of the Distribution
330 instance. Then, it is alternately scanned for Distutils
331 commands and options for that command. Each new command
332 terminates the options for the previous command. The allowed
333 options for a command are determined by the 'user_options'
334 attribute of the command class -- thus, we have to be able to
335 load command classes in order to parse the command line. Any
336 error in that 'options' attribute raises DistutilsGetoptError;
337 any error on the command-line raises DistutilsArgError. If no
338 Distutils commands were found on the command line, raises
339 DistutilsArgError. Return true if command-line were
340 successfully parsed and we should carry on with executing
341 commands; false if no errors but we shouldn't execute commands
342 (currently, this only happens if user asks for help).
343 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000344 # We have to parse the command line a bit at a time -- global
345 # options, then the first command, then its options, and so on --
346 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000347 # the options that are valid for a particular class aren't known
348 # until we have loaded the command class, which doesn't happen
349 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000350
351 self.commands = []
Greg Ward82715e12000-04-21 02:28:14 +0000352 parser = FancyGetopt (self.global_options + self.display_options)
353 parser.set_negative_aliases (self.negative_opt)
Greg Ward58ec6ed2000-04-21 04:22:49 +0000354 parser.set_aliases ({'license': 'licence'})
Greg Ward82715e12000-04-21 02:28:14 +0000355 args = parser.getopt (object=self)
356 option_order = parser.get_option_order()
Greg Wardfe6462c2000-04-04 01:40:52 +0000357
Greg Ward82715e12000-04-21 02:28:14 +0000358 # for display options we return immediately
359 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000360 return
361
362 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000363 args = self._parse_command_opts(parser, args)
364 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000365 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000366
Greg Wardd5d8a992000-05-23 01:42:17 +0000367 # Handle the cases of --help as a "global" option, ie.
368 # "setup.py --help" and "setup.py --help command ...". For the
369 # former, we show global options (--verbose, --dry-run, etc.)
370 # and display-only options (--name, --version, etc.); for the
371 # latter, we omit the display-only options and show help for
372 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000373 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000374 print "showing 'global' help; commands=", self.commands
375 self._show_help(parser,
376 display_options=len(self.commands) == 0,
377 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000378 return
379
380 # Oops, no commands found -- an end-user error
381 if not self.commands:
382 raise DistutilsArgError, "no commands supplied"
383
384 # All is well: return true
385 return 1
386
387 # parse_command_line()
388
Greg Wardd5d8a992000-05-23 01:42:17 +0000389 def _parse_command_opts (self, parser, args):
390
391 """Parse the command-line options for a single command.
392 'parser' must be a FancyGetopt instance; 'args' must be the list
393 of arguments, starting with the current command (whose options
394 we are about to parse). Returns a new version of 'args' with
395 the next command at the front of the list; will be the empty
396 list if there are no more commands on the command line. Returns
397 None if the user asked for help on this command.
398 """
399 # late import because of mutual dependence between these modules
400 from distutils.cmd import Command
401
402 # Pull the current command from the head of the command line
403 command = args[0]
404 if not command_re.match (command):
405 raise SystemExit, "invalid command name '%s'" % command
406 self.commands.append (command)
407
408 # Dig up the command class that implements this command, so we
409 # 1) know that it's a valid command, and 2) know which options
410 # it takes.
411 try:
412 cmd_class = self.get_command_class (command)
413 except DistutilsModuleError, msg:
414 raise DistutilsArgError, msg
415
416 # Require that the command class be derived from Command -- want
417 # to be sure that the basic "command" interface is implemented.
418 if not issubclass (cmd_class, Command):
419 raise DistutilsClassError, \
420 "command class %s must subclass Command" % cmd_class
421
422 # Also make sure that the command object provides a list of its
423 # known options.
424 if not (hasattr (cmd_class, 'user_options') and
425 type (cmd_class.user_options) is ListType):
426 raise DistutilsClassError, \
427 ("command class %s must provide " +
428 "'user_options' attribute (a list of tuples)") % \
429 cmd_class
430
431 # If the command class has a list of negative alias options,
432 # merge it in with the global negative aliases.
433 negative_opt = self.negative_opt
434 if hasattr (cmd_class, 'negative_opt'):
435 negative_opt = copy (negative_opt)
436 negative_opt.update (cmd_class.negative_opt)
437
438 # All commands support the global options too, just by adding
439 # in 'global_options'.
440 parser.set_option_table (self.global_options +
441 cmd_class.user_options)
442 parser.set_negative_aliases (negative_opt)
443 (args, opts) = parser.getopt (args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000444 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000445 print "showing help for command", cmd_class
446 self._show_help(parser, display_options=0, commands=[cmd_class])
447 return
448
449 # Put the options from the command-line into their official
450 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000451 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000452 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000453 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000454
455 return args
456
457 # _parse_command_opts ()
458
459
460 def _show_help (self,
461 parser,
462 global_options=1,
463 display_options=1,
464 commands=[]):
465 """Show help for the setup script command-line in the form of
466 several lists of command-line options. 'parser' should be a
467 FancyGetopt instance; do not expect it to be returned in the
468 same state, as its option table will be reset to make it
469 generate the correct help text.
470
471 If 'global_options' is true, lists the global options:
472 --verbose, --dry-run, etc. If 'display_options' is true, lists
473 the "display-only" options: --name, --version, etc. Finally,
474 lists per-command help for every command name or command class
475 in 'commands'.
476 """
477 # late import because of mutual dependence between these modules
478 from distutils.core import usage
479 from distutils.cmd import Command
480
481 if global_options:
482 parser.set_option_table (self.global_options)
483 parser.print_help ("Global options:")
484 print
485
486 if display_options:
487 parser.set_option_table (self.display_options)
488 parser.print_help (
489 "Information display options (just display " +
490 "information, ignore any commands)")
491 print
492
493 for command in self.commands:
494 if type(command) is ClassType and issubclass(klass, Command):
495 klass = command
496 else:
497 klass = self.get_command_class (command)
498 parser.set_option_table (klass.user_options)
499 parser.print_help ("Options for '%s' command:" % klass.__name__)
500 print
501
502 print usage
503 return
504
505 # _show_help ()
506
507
Greg Ward82715e12000-04-21 02:28:14 +0000508 def handle_display_options (self, option_order):
509 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000510 (--help-commands or the metadata display options) on the command
511 line, display the requested info and return true; else return
512 false.
513 """
Greg Ward82715e12000-04-21 02:28:14 +0000514 from distutils.core import usage
515
516 # User just wants a list of commands -- we'll print it out and stop
517 # processing now (ie. if they ran "setup --help-commands foo bar",
518 # we ignore "foo bar").
519 if self.help_commands:
520 self.print_commands ()
521 print
522 print usage
523 return 1
524
525 # If user supplied any of the "display metadata" options, then
526 # display that metadata in the order in which the user supplied the
527 # metadata options.
528 any_display_options = 0
529 is_display_option = {}
530 for option in self.display_options:
531 is_display_option[option[0]] = 1
532
533 for (opt, val) in option_order:
534 if val and is_display_option.get(opt):
535 opt = string.translate (opt, longopt_xlate)
536 print getattr(self.metadata, "get_"+opt)()
537 any_display_options = 1
538
539 return any_display_options
540
541 # handle_display_options()
Greg Wardfe6462c2000-04-04 01:40:52 +0000542
543 def print_command_list (self, commands, header, max_length):
544 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000545 'print_commands()'.
546 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000547
548 print header + ":"
549
550 for cmd in commands:
551 klass = self.cmdclass.get (cmd)
552 if not klass:
Greg Wardd5d8a992000-05-23 01:42:17 +0000553 klass = self.get_command_class (cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000554 try:
555 description = klass.description
556 except AttributeError:
557 description = "(no description available)"
558
559 print " %-*s %s" % (max_length, cmd, description)
560
561 # print_command_list ()
562
563
564 def print_commands (self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000565 """Print out a help message listing all available commands with a
566 description of each. The list is divided into "standard commands"
567 (listed in distutils.command.__all__) and "extra commands"
568 (mentioned in self.cmdclass, but not a standard command). The
569 descriptions come from the command class attribute
570 'description'.
571 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000572
573 import distutils.command
574 std_commands = distutils.command.__all__
575 is_std = {}
576 for cmd in std_commands:
577 is_std[cmd] = 1
578
579 extra_commands = []
580 for cmd in self.cmdclass.keys():
581 if not is_std.get(cmd):
582 extra_commands.append (cmd)
583
584 max_length = 0
585 for cmd in (std_commands + extra_commands):
586 if len (cmd) > max_length:
587 max_length = len (cmd)
588
589 self.print_command_list (std_commands,
590 "Standard commands",
591 max_length)
592 if extra_commands:
593 print
594 self.print_command_list (extra_commands,
595 "Extra commands",
596 max_length)
597
598 # print_commands ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000599
600
601 # -- Command class/object methods ----------------------------------
602
Greg Wardd5d8a992000-05-23 01:42:17 +0000603 def get_command_class (self, command):
604 """Return the class that implements the Distutils command named by
605 'command'. First we check the 'cmdclass' dictionary; if the
606 command is mentioned there, we fetch the class object from the
607 dictionary and return it. Otherwise we load the command module
608 ("distutils.command." + command) and fetch the command class from
609 the module. The loaded class is also stored in 'cmdclass'
610 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000611
Gregory P. Smith14263542000-05-12 00:41:33 +0000612 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000613 found, or if that module does not define the expected class.
614 """
615 klass = self.cmdclass.get(command)
616 if klass:
617 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000618
619 module_name = 'distutils.command.' + command
620 klass_name = command
621
622 try:
623 __import__ (module_name)
624 module = sys.modules[module_name]
625 except ImportError:
626 raise DistutilsModuleError, \
627 "invalid command '%s' (no module named '%s')" % \
628 (command, module_name)
629
630 try:
Greg Wardd5d8a992000-05-23 01:42:17 +0000631 klass = getattr(module, klass_name)
632 except AttributeError:
Greg Wardfe6462c2000-04-04 01:40:52 +0000633 raise DistutilsModuleError, \
634 "invalid command '%s' (no class '%s' in module '%s')" \
635 % (command, klass_name, module_name)
636
Greg Wardd5d8a992000-05-23 01:42:17 +0000637 self.cmdclass[command] = klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000638 return klass
639
Greg Wardd5d8a992000-05-23 01:42:17 +0000640 # get_command_class ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000641
Greg Wardd5d8a992000-05-23 01:42:17 +0000642 def get_command_obj (self, command, create=1):
643 """Return the command object for 'command'. Normally this object
644 is cached on a previous call to 'get_command_obj()'; if no comand
645 object for 'command' is in the cache, then we either create and
646 return it (if 'create' is true) or return None.
647 """
648 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000649 if not cmd_obj and create:
Greg Ward47460772000-05-23 03:47:35 +0000650 print "Distribution.get_command_obj(): " \
651 "creating '%s' command object" % command
652
Greg Wardd5d8a992000-05-23 01:42:17 +0000653 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000654 cmd_obj = self.command_obj[command] = klass(self)
655 self.have_run[command] = 0
656
657 # Set any options that were supplied in config files
658 # or on the command line. (NB. support for error
659 # reporting is lame here: any errors aren't reported
660 # until 'finalize_options()' is called, which means
661 # we won't report the source of the error.)
662 options = self.command_options.get(command)
663 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000664 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000665
666 return cmd_obj
667
Greg Wardc32d9a62000-05-28 23:53:06 +0000668 def _set_command_options (self, command_obj, option_dict=None):
669
670 """Set the options for 'command_obj' from 'option_dict'. Basically
671 this means copying elements of a dictionary ('option_dict') to
672 attributes of an instance ('command').
673
674 'command_obj' must be a Commnd instance. If 'option_dict' is not
675 supplied, uses the standard option dictionary for this command
676 (from 'self.command_options').
677 """
678 from distutils.core import DEBUG
679
680 command_name = command_obj.get_command_name()
681 if option_dict is None:
682 option_dict = self.get_option_dict(command_name)
683
684 if DEBUG: print " setting options for '%s' command:" % command_name
685 for (option, (source, value)) in option_dict.items():
686 if DEBUG: print " %s = %s (from %s)" % (option, value, source)
687 if not hasattr(command_obj, option):
688 raise DistutilsOptionError, \
689 ("error in %s: command '%s' has no such option '%s'") % \
690 (source, command_name, option)
691 setattr(command_obj, option, value)
692
693 def reinitialize_command (self, command):
694 """Reinitializes a command to the state it was in when first
695 returned by 'get_command_obj()': ie., initialized but not yet
696 finalized. This gives provides the opportunity to sneak option
697 values in programmatically, overriding or supplementing
698 user-supplied values from the config files and command line.
699 You'll have to re-finalize the command object (by calling
700 'finalize_options()' or 'ensure_finalized()') before using it for
701 real.
702
703 'command' should be a command name (string) or command object.
704 Returns the reinitialized command object.
705 """
706 from distutils.cmd import Command
707 if not isinstance(command, Command):
708 command_name = command
709 command = self.get_command_obj(command_name)
710 else:
711 command_name = command.get_command_name()
712
713 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000714 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000715 command.initialize_options()
716 command.finalized = 0
717 self._set_command_options(command)
718 return command
719
Greg Wardfe6462c2000-04-04 01:40:52 +0000720
721 # -- Methods that operate on the Distribution ----------------------
722
723 def announce (self, msg, level=1):
724 """Print 'msg' if 'level' is greater than or equal to the verbosity
Greg Wardd5d8a992000-05-23 01:42:17 +0000725 level recorded in the 'verbose' attribute (which, currently, can be
726 only 0 or 1).
727 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000728 if self.verbose >= level:
729 print msg
730
731
732 def run_commands (self):
Greg Ward82715e12000-04-21 02:28:14 +0000733 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000734 Uses the list of commands found and cache of command objects
735 created by 'get_command_obj()'."""
Greg Wardfe6462c2000-04-04 01:40:52 +0000736
737 for cmd in self.commands:
738 self.run_command (cmd)
739
740
Greg Wardfe6462c2000-04-04 01:40:52 +0000741 # -- Methods that operate on its Commands --------------------------
742
743 def run_command (self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000744 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000745 if the command has already been run). Specifically: if we have
746 already created and run the command named by 'command', return
747 silently without doing anything. If the command named by 'command'
748 doesn't even have a command object yet, create one. Then invoke
749 'run()' on that command object (or an existing one).
750 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000751
752 # Already been here, done that? then return silently.
753 if self.have_run.get (command):
754 return
755
756 self.announce ("running " + command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000757 cmd_obj = self.get_command_obj (command)
Greg Ward4fb29e52000-05-27 17:27:23 +0000758 cmd_obj.ensure_finalized ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000759 cmd_obj.run ()
760 self.have_run[command] = 1
761
762
Greg Wardfe6462c2000-04-04 01:40:52 +0000763 # -- Distribution query methods ------------------------------------
764
765 def has_pure_modules (self):
766 return len (self.packages or self.py_modules or []) > 0
767
768 def has_ext_modules (self):
769 return self.ext_modules and len (self.ext_modules) > 0
770
771 def has_c_libraries (self):
772 return self.libraries and len (self.libraries) > 0
773
774 def has_modules (self):
775 return self.has_pure_modules() or self.has_ext_modules()
776
Greg Ward51def7d2000-05-27 01:36:14 +0000777 def has_headers (self):
778 return self.headers and len(self.headers) > 0
779
Greg Ward44a61bb2000-05-20 15:06:48 +0000780 def has_scripts (self):
781 return self.scripts and len(self.scripts) > 0
782
783 def has_data_files (self):
784 return self.data_files and len(self.data_files) > 0
785
Greg Wardfe6462c2000-04-04 01:40:52 +0000786 def is_pure (self):
787 return (self.has_pure_modules() and
788 not self.has_ext_modules() and
789 not self.has_c_libraries())
790
Greg Ward82715e12000-04-21 02:28:14 +0000791 # -- Metadata query methods ----------------------------------------
792
793 # If you're looking for 'get_name()', 'get_version()', and so forth,
794 # they are defined in a sneaky way: the constructor binds self.get_XXX
795 # to self.metadata.get_XXX. The actual code is in the
796 # DistributionMetadata class, below.
797
798# class Distribution
799
800
801class DistributionMetadata:
802 """Dummy class to hold the distribution meta-data: name, version,
803 author, and so forth."""
804
805 def __init__ (self):
806 self.name = None
807 self.version = None
808 self.author = None
809 self.author_email = None
810 self.maintainer = None
811 self.maintainer_email = None
812 self.url = None
813 self.licence = None
814 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +0000815 self.long_description = None
Greg Ward82715e12000-04-21 02:28:14 +0000816
817 # -- Metadata query methods ----------------------------------------
818
Greg Wardfe6462c2000-04-04 01:40:52 +0000819 def get_name (self):
820 return self.name or "UNKNOWN"
821
Greg Ward82715e12000-04-21 02:28:14 +0000822 def get_version(self):
823 return self.version or "???"
Greg Wardfe6462c2000-04-04 01:40:52 +0000824
Greg Ward82715e12000-04-21 02:28:14 +0000825 def get_fullname (self):
826 return "%s-%s" % (self.get_name(), self.get_version())
827
828 def get_author(self):
829 return self.author or "UNKNOWN"
830
831 def get_author_email(self):
832 return self.author_email or "UNKNOWN"
833
834 def get_maintainer(self):
835 return self.maintainer or "UNKNOWN"
836
837 def get_maintainer_email(self):
838 return self.maintainer_email or "UNKNOWN"
839
840 def get_contact(self):
841 return (self.maintainer or
842 self.author or
843 "UNKNOWN")
844
845 def get_contact_email(self):
846 return (self.maintainer_email or
847 self.author_email or
848 "UNKNOWN")
849
850 def get_url(self):
851 return self.url or "UNKNOWN"
852
853 def get_licence(self):
854 return self.licence or "UNKNOWN"
855
856 def get_description(self):
857 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +0000858
859 def get_long_description(self):
860 return self.long_description or "UNKNOWN"
861
Greg Ward82715e12000-04-21 02:28:14 +0000862# class DistributionMetadata
Greg Wardfe6462c2000-04-04 01:40:52 +0000863
864if __name__ == "__main__":
865 dist = Distribution ()
866 print "ok"