blob: 88bd94a470054b96d5b09c8eb0b4f4fcd1a9fb8c [file] [log] [blame]
Greg Wardfe6462c2000-04-04 01:40:52 +00001"""distutils.dist
2
3Provides the Distribution class, which represents the module distribution
Greg Ward8ff5a3f2000-06-02 00:44:53 +00004being built/installed/distributed.
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
Gregory P. Smith14263542000-05-12 00:41:33 +000012import sys, os, string, re
Greg Wardfe6462c2000-04-04 01:40:52 +000013from types import *
14from copy import copy
15from distutils.errors import *
Greg Ward36c36fe2000-05-20 14:07:59 +000016from distutils import sysconfig
Greg Ward82715e12000-04-21 02:28:14 +000017from distutils.fancy_getopt import FancyGetopt, longopt_xlate
Gregory P. Smith14263542000-05-12 00:41:33 +000018from distutils.util import check_environ
Greg Wardfe6462c2000-04-04 01:40:52 +000019
20
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.
25command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
26
27
28class Distribution:
Greg Ward8ff5a3f2000-06-02 00:44:53 +000029 """The core of the Distutils. Most of the work hiding behind 'setup'
30 is really done within a Distribution instance, which farms the work out
31 to the Distutils commands specified on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +000032
Greg Ward8ff5a3f2000-06-02 00:44:53 +000033 Setup scripts will almost never instantiate Distribution directly,
34 unless the 'setup()' function is totally inadequate to their needs.
35 However, it is conceivable that a setup script might wish to subclass
36 Distribution for some specialized purpose, and then pass the subclass
37 to 'setup()' as the 'distclass' keyword argument. If so, it is
38 necessary to respect the expectations that 'setup' has of Distribution.
39 See the code for 'setup()', in core.py, for details.
40 """
Greg Wardfe6462c2000-04-04 01:40:52 +000041
42
43 # 'global_options' describes the command-line options that may be
Greg Ward82715e12000-04-21 02:28:14 +000044 # supplied to the setup script prior to any actual commands.
45 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
Greg Wardfe6462c2000-04-04 01:40:52 +000046 # these global options. This list should be kept to a bare minimum,
47 # since every global option is also valid as a command option -- and we
48 # don't want to pollute the commands with too many options that they
49 # have minimal control over.
Greg Wardd5d8a992000-05-23 01:42:17 +000050 global_options = [('verbose', 'v', "run verbosely (default)"),
51 ('quiet', 'q', "run quietly (turns verbosity off)"),
52 ('dry-run', 'n', "don't actually do anything"),
53 ('help', 'h', "show detailed help message"),
Greg Wardfe6462c2000-04-04 01:40:52 +000054 ]
Greg Ward82715e12000-04-21 02:28:14 +000055
56 # options that are not propagated to the commands
57 display_options = [
58 ('help-commands', None,
59 "list all available commands"),
60 ('name', None,
61 "print package name"),
62 ('version', 'V',
63 "print package version"),
64 ('fullname', None,
65 "print <package name>-<version>"),
66 ('author', None,
67 "print the author's name"),
68 ('author-email', None,
69 "print the author's email address"),
70 ('maintainer', None,
71 "print the maintainer's name"),
72 ('maintainer-email', None,
73 "print the maintainer's email address"),
74 ('contact', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000075 "print the maintainer's name if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000076 ('contact-email', None,
Greg Wardd5d8a992000-05-23 01:42:17 +000077 "print the maintainer's email address if known, else the author's"),
Greg Ward82715e12000-04-21 02:28:14 +000078 ('url', None,
79 "print the URL for this package"),
80 ('licence', None,
81 "print the licence of the package"),
82 ('license', None,
83 "alias for --licence"),
84 ('description', None,
85 "print the package description"),
Greg Warde5a584e2000-04-26 02:26:55 +000086 ('long-description', None,
87 "print the long package description"),
Greg Ward82715e12000-04-21 02:28:14 +000088 ]
89 display_option_names = map(lambda x: string.translate(x[0], longopt_xlate),
90 display_options)
91
92 # negative options are options that exclude other options
Greg Wardfe6462c2000-04-04 01:40:52 +000093 negative_opt = {'quiet': 'verbose'}
94
95
96 # -- Creation/initialization methods -------------------------------
97
98 def __init__ (self, attrs=None):
99 """Construct a new Distribution instance: initialize all the
Greg Ward8ff5a3f2000-06-02 00:44:53 +0000100 attributes of a Distribution, and then use 'attrs' (a dictionary
101 mapping attribute names to values) to assign some of those
102 attributes their "real" values. (Any attributes not mentioned in
103 'attrs' will be assigned to some null value: 0, None, an empty list
104 or dictionary, etc.) Most importantly, initialize the
105 'command_obj' attribute to the empty dictionary; this will be
106 filled in with real command objects by 'parse_command_line()'.
107 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000108
109 # Default values for our command-line options
110 self.verbose = 1
111 self.dry_run = 0
Greg Wardfe6462c2000-04-04 01:40:52 +0000112 self.help = 0
Greg Ward82715e12000-04-21 02:28:14 +0000113 for attr in self.display_option_names:
114 setattr(self, attr, 0)
Greg Wardfe6462c2000-04-04 01:40:52 +0000115
Greg Ward82715e12000-04-21 02:28:14 +0000116 # Store the distribution meta-data (name, version, author, and so
117 # forth) in a separate object -- we're getting to have enough
118 # information here (and enough command-line options) that it's
119 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
120 # object in a sneaky and underhanded (but efficient!) way.
121 self.metadata = DistributionMetadata ()
Greg Ward4982f982000-04-22 02:52:44 +0000122 method_basenames = dir(self.metadata) + \
123 ['fullname', 'contact', 'contact_email']
124 for basename in method_basenames:
125 method_name = "get_" + basename
126 setattr(self, method_name, getattr(self.metadata, method_name))
Greg Wardfe6462c2000-04-04 01:40:52 +0000127
128 # 'cmdclass' maps command names to class objects, so we
129 # can 1) quickly figure out which class to instantiate when
130 # we need to create a new command object, and 2) have a way
Greg Ward82715e12000-04-21 02:28:14 +0000131 # for the setup script to override command classes
Greg Wardfe6462c2000-04-04 01:40:52 +0000132 self.cmdclass = {}
133
Greg Wardd5d8a992000-05-23 01:42:17 +0000134 # 'command_options' is where we store command options between
135 # parsing them (from config files, the command-line, etc.) and when
136 # they are actually needed -- ie. when the command in question is
137 # instantiated. It is a dictionary of dictionaries of 2-tuples:
138 # command_options = { command_name : { option : (source, value) } }
Gregory P. Smith14263542000-05-12 00:41:33 +0000139 self.command_options = {}
140
Greg Wardfe6462c2000-04-04 01:40:52 +0000141 # These options are really the business of various commands, rather
142 # than of the Distribution itself. We provide aliases for them in
143 # Distribution as a convenience to the developer.
Greg Wardfe6462c2000-04-04 01:40:52 +0000144 self.packages = None
145 self.package_dir = None
146 self.py_modules = None
147 self.libraries = None
Greg Ward51def7d2000-05-27 01:36:14 +0000148 self.headers = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000149 self.ext_modules = None
150 self.ext_package = None
151 self.include_dirs = None
152 self.extra_path = None
Gregory P. Smithb2e3bb32000-05-12 00:52:23 +0000153 self.scripts = None
Gregory P. Smith6a901dd2000-05-13 03:09:50 +0000154 self.data_files = None
Greg Wardfe6462c2000-04-04 01:40:52 +0000155
156 # And now initialize bookkeeping stuff that can't be supplied by
157 # the caller at all. 'command_obj' maps command names to
158 # Command instances -- that's how we enforce that every command
159 # class is a singleton.
160 self.command_obj = {}
161
162 # 'have_run' maps command names to boolean values; it keeps track
163 # of whether we have actually run a particular command, to make it
164 # cheap to "run" a command whenever we think we might need to -- if
165 # it's already been done, no need for expensive filesystem
166 # operations, we just check the 'have_run' dictionary and carry on.
167 # It's only safe to query 'have_run' for a command class that has
168 # been instantiated -- a false value will be inserted when the
169 # command object is created, and replaced with a true value when
170 # the command is succesfully run. Thus it's probably best to use
171 # '.get()' rather than a straight lookup.
172 self.have_run = {}
173
174 # Now we'll use the attrs dictionary (ultimately, keyword args from
Greg Ward82715e12000-04-21 02:28:14 +0000175 # the setup script) to possibly override any or all of these
176 # distribution options.
177
Greg Wardfe6462c2000-04-04 01:40:52 +0000178 if attrs:
179
180 # Pull out the set of command options and work on them
181 # specifically. Note that this order guarantees that aliased
182 # command options will override any supplied redundantly
183 # through the general options dictionary.
184 options = attrs.get ('options')
185 if options:
186 del attrs['options']
187 for (command, cmd_options) in options.items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000188 opt_dict = self.get_option_dict(command)
189 for (opt, val) in cmd_options.items():
190 opt_dict[opt] = ("setup script", val)
Greg Wardfe6462c2000-04-04 01:40:52 +0000191
192 # Now work on the rest of the attributes. Any attribute that's
193 # not already defined is invalid!
194 for (key,val) in attrs.items():
Greg Ward82715e12000-04-21 02:28:14 +0000195 if hasattr (self.metadata, key):
196 setattr (self.metadata, key, val)
197 elif hasattr (self, key):
Greg Wardfe6462c2000-04-04 01:40:52 +0000198 setattr (self, key, val)
199 else:
Greg Ward02a1a2b2000-04-15 22:15:07 +0000200 raise DistutilsSetupError, \
Greg Wardfe6462c2000-04-04 01:40:52 +0000201 "invalid distribution option '%s'" % key
202
203 # __init__ ()
204
205
Greg Ward0e48cfd2000-05-26 01:00:15 +0000206 def get_option_dict (self, command):
207 """Get the option dictionary for a given command. If that
208 command's option dictionary hasn't been created yet, then create it
209 and return the new dictionary; otherwise, return the existing
210 option dictionary.
211 """
212
213 dict = self.command_options.get(command)
214 if dict is None:
215 dict = self.command_options[command] = {}
216 return dict
217
218
Greg Wardc32d9a62000-05-28 23:53:06 +0000219 def dump_option_dicts (self, header=None, commands=None, indent=""):
220 from pprint import pformat
221
222 if commands is None: # dump all command option dicts
223 commands = self.command_options.keys()
224 commands.sort()
225
226 if header is not None:
227 print indent + header
228 indent = indent + " "
229
230 if not commands:
231 print indent + "no commands known yet"
232 return
233
234 for cmd_name in commands:
235 opt_dict = self.command_options.get(cmd_name)
236 if opt_dict is None:
237 print indent + "no option dict for '%s' command" % cmd_name
238 else:
239 print indent + "option dict for '%s' command:" % cmd_name
240 out = pformat(opt_dict)
241 for line in string.split(out, "\n"):
242 print indent + " " + line
243
244 # dump_option_dicts ()
245
246
247
Greg Wardd5d8a992000-05-23 01:42:17 +0000248 # -- Config file finding/parsing methods ---------------------------
249
Gregory P. Smith14263542000-05-12 00:41:33 +0000250 def find_config_files (self):
251 """Find as many configuration files as should be processed for this
252 platform, and return a list of filenames in the order in which they
253 should be parsed. The filenames returned are guaranteed to exist
254 (modulo nasty race conditions).
255
256 On Unix, there are three possible config files: pydistutils.cfg in
257 the Distutils installation directory (ie. where the top-level
258 Distutils __inst__.py file lives), .pydistutils.cfg in the user's
259 home directory, and setup.cfg in the current directory.
260
261 On Windows and Mac OS, there are two possible config files:
262 pydistutils.cfg in the Python installation directory (sys.prefix)
Greg Wardd5d8a992000-05-23 01:42:17 +0000263 and setup.cfg in the current directory.
264 """
Gregory P. Smith14263542000-05-12 00:41:33 +0000265 files = []
Greg Wardacf3f6a2000-06-07 02:26:19 +0000266 check_environ()
Gregory P. Smith14263542000-05-12 00:41:33 +0000267
Greg Ward11696872000-06-07 02:29:03 +0000268 # Where to look for the system-wide Distutils config file
269 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
270
271 # Look for the system config file
272 sys_file = os.path.join(sys_dir, "distutils.cfg")
Greg Wardacf3f6a2000-06-07 02:26:19 +0000273 if os.path.isfile(sys_file):
274 files.append(sys_file)
Gregory P. Smith14263542000-05-12 00:41:33 +0000275
Greg Ward11696872000-06-07 02:29:03 +0000276 # What to call the per-user config file
277 if os.name == 'posix':
278 user_filename = ".pydistutils.cfg"
279 else:
280 user_filename = "pydistutils.cfg"
281
282 # And look for the user config file
Greg Wardacf3f6a2000-06-07 02:26:19 +0000283 if os.environ.has_key('HOME'):
Greg Ward11696872000-06-07 02:29:03 +0000284 user_file = os.path.join(os.environ.get('HOME'), user_filename)
Gregory P. Smith14263542000-05-12 00:41:33 +0000285 if os.path.isfile(user_file):
286 files.append(user_file)
287
Gregory P. Smith14263542000-05-12 00:41:33 +0000288 # All platforms support local setup.cfg
289 local_file = "setup.cfg"
290 if os.path.isfile(local_file):
291 files.append(local_file)
292
293 return files
294
295 # find_config_files ()
296
297
298 def parse_config_files (self, filenames=None):
299
300 from ConfigParser import ConfigParser
Greg Ward2bd3f422000-06-02 01:59:33 +0000301 from distutils.core import DEBUG
Gregory P. Smith14263542000-05-12 00:41:33 +0000302
303 if filenames is None:
304 filenames = self.find_config_files()
305
Greg Ward2bd3f422000-06-02 01:59:33 +0000306 if DEBUG: print "Distribution.parse_config_files():"
Greg Ward47460772000-05-23 03:47:35 +0000307
Gregory P. Smith14263542000-05-12 00:41:33 +0000308 parser = ConfigParser()
Greg Wardd5d8a992000-05-23 01:42:17 +0000309 for filename in filenames:
Greg Ward2bd3f422000-06-02 01:59:33 +0000310 if DEBUG: print " reading", filename
Greg Wardd5d8a992000-05-23 01:42:17 +0000311 parser.read(filename)
312 for section in parser.sections():
313 options = parser.options(section)
Greg Ward0e48cfd2000-05-26 01:00:15 +0000314 opt_dict = self.get_option_dict(section)
Gregory P. Smith14263542000-05-12 00:41:33 +0000315
Greg Wardd5d8a992000-05-23 01:42:17 +0000316 for opt in options:
317 if opt != '__name__':
Greg Ward0e48cfd2000-05-26 01:00:15 +0000318 opt_dict[opt] = (filename, parser.get(section,opt))
Gregory P. Smith14263542000-05-12 00:41:33 +0000319
Greg Ward47460772000-05-23 03:47:35 +0000320 # Make the ConfigParser forget everything (so we retain
321 # the original filenames that options come from) -- gag,
322 # retch, puke -- another good reason for a distutils-
323 # specific config parser (sigh...)
324 parser.__init__()
Gregory P. Smith14263542000-05-12 00:41:33 +0000325
326
Greg Wardd5d8a992000-05-23 01:42:17 +0000327 # -- Command-line parsing methods ----------------------------------
328
Greg Wardfe6462c2000-04-04 01:40:52 +0000329 def parse_command_line (self, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000330 """Parse the setup script's command line. 'args' must be a list
331 of command-line arguments, most likely 'sys.argv[1:]' (see the
332 'setup()' function). This list is first processed for "global
333 options" -- options that set attributes of the Distribution
334 instance. Then, it is alternately scanned for Distutils
335 commands and options for that command. Each new command
336 terminates the options for the previous command. The allowed
337 options for a command are determined by the 'user_options'
338 attribute of the command class -- thus, we have to be able to
339 load command classes in order to parse the command line. Any
340 error in that 'options' attribute raises DistutilsGetoptError;
341 any error on the command-line raises DistutilsArgError. If no
342 Distutils commands were found on the command line, raises
343 DistutilsArgError. Return true if command-line were
344 successfully parsed and we should carry on with executing
345 commands; false if no errors but we shouldn't execute commands
346 (currently, this only happens if user asks for help).
347 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000348 # We have to parse the command line a bit at a time -- global
349 # options, then the first command, then its options, and so on --
350 # because each command will be handled by a different class, and
Greg Wardd5d8a992000-05-23 01:42:17 +0000351 # the options that are valid for a particular class aren't known
352 # until we have loaded the command class, which doesn't happen
353 # until we know what the command is.
Greg Wardfe6462c2000-04-04 01:40:52 +0000354
355 self.commands = []
Greg Ward82715e12000-04-21 02:28:14 +0000356 parser = FancyGetopt (self.global_options + self.display_options)
357 parser.set_negative_aliases (self.negative_opt)
Greg Ward58ec6ed2000-04-21 04:22:49 +0000358 parser.set_aliases ({'license': 'licence'})
Greg Ward82715e12000-04-21 02:28:14 +0000359 args = parser.getopt (object=self)
360 option_order = parser.get_option_order()
Greg Wardfe6462c2000-04-04 01:40:52 +0000361
Greg Ward82715e12000-04-21 02:28:14 +0000362 # for display options we return immediately
363 if self.handle_display_options(option_order):
Greg Wardfe6462c2000-04-04 01:40:52 +0000364 return
365
366 while args:
Greg Wardd5d8a992000-05-23 01:42:17 +0000367 args = self._parse_command_opts(parser, args)
368 if args is None: # user asked for help (and got it)
Greg Wardfe6462c2000-04-04 01:40:52 +0000369 return
Greg Wardfe6462c2000-04-04 01:40:52 +0000370
Greg Wardd5d8a992000-05-23 01:42:17 +0000371 # Handle the cases of --help as a "global" option, ie.
372 # "setup.py --help" and "setup.py --help command ...". For the
373 # former, we show global options (--verbose, --dry-run, etc.)
374 # and display-only options (--name, --version, etc.); for the
375 # latter, we omit the display-only options and show help for
376 # each command listed on the command line.
Greg Wardfe6462c2000-04-04 01:40:52 +0000377 if self.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000378 self._show_help(parser,
379 display_options=len(self.commands) == 0,
380 commands=self.commands)
Greg Wardfe6462c2000-04-04 01:40:52 +0000381 return
382
383 # Oops, no commands found -- an end-user error
384 if not self.commands:
385 raise DistutilsArgError, "no commands supplied"
386
387 # All is well: return true
388 return 1
389
390 # parse_command_line()
391
Greg Wardd5d8a992000-05-23 01:42:17 +0000392 def _parse_command_opts (self, parser, args):
Greg Wardd5d8a992000-05-23 01:42:17 +0000393 """Parse the command-line options for a single command.
394 'parser' must be a FancyGetopt instance; 'args' must be the list
395 of arguments, starting with the current command (whose options
396 we are about to parse). Returns a new version of 'args' with
397 the next command at the front of the list; will be the empty
398 list if there are no more commands on the command line. Returns
399 None if the user asked for help on this command.
400 """
401 # late import because of mutual dependence between these modules
402 from distutils.cmd import Command
403
404 # Pull the current command from the head of the command line
405 command = args[0]
406 if not command_re.match (command):
407 raise SystemExit, "invalid command name '%s'" % command
408 self.commands.append (command)
409
410 # Dig up the command class that implements this command, so we
411 # 1) know that it's a valid command, and 2) know which options
412 # it takes.
413 try:
414 cmd_class = self.get_command_class (command)
415 except DistutilsModuleError, msg:
416 raise DistutilsArgError, msg
417
418 # Require that the command class be derived from Command -- want
419 # to be sure that the basic "command" interface is implemented.
420 if not issubclass (cmd_class, Command):
421 raise DistutilsClassError, \
422 "command class %s must subclass Command" % cmd_class
423
424 # Also make sure that the command object provides a list of its
425 # known options.
426 if not (hasattr (cmd_class, 'user_options') and
427 type (cmd_class.user_options) is ListType):
428 raise DistutilsClassError, \
429 ("command class %s must provide " +
430 "'user_options' attribute (a list of tuples)") % \
431 cmd_class
432
433 # If the command class has a list of negative alias options,
434 # merge it in with the global negative aliases.
435 negative_opt = self.negative_opt
436 if hasattr (cmd_class, 'negative_opt'):
437 negative_opt = copy (negative_opt)
438 negative_opt.update (cmd_class.negative_opt)
439
Greg Ward9d17a7a2000-06-07 03:00:06 +0000440 # Check for help_options in command class
441 # They have a different format (tuple of four) so we need to preprocess them here
442 help_options = []
443 if hasattr(cmd_class,"help_options") and type (cmd_class.help_options) is ListType:
444 help_options = map(lambda x:(x[0],x[1],x[2]),cmd_class.help_options)
445
Greg Wardd5d8a992000-05-23 01:42:17 +0000446 # All commands support the global options too, just by adding
447 # in 'global_options'.
448 parser.set_option_table (self.global_options +
Greg Ward9d17a7a2000-06-07 03:00:06 +0000449 cmd_class.user_options + help_options)
Greg Wardd5d8a992000-05-23 01:42:17 +0000450 parser.set_negative_aliases (negative_opt)
451 (args, opts) = parser.getopt (args[1:])
Greg Ward47460772000-05-23 03:47:35 +0000452 if hasattr(opts, 'help') and opts.help:
Greg Wardd5d8a992000-05-23 01:42:17 +0000453 self._show_help(parser, display_options=0, commands=[cmd_class])
454 return
455
Greg Ward9d17a7a2000-06-07 03:00:06 +0000456 if hasattr(cmd_class,"help_options") and type (cmd_class.help_options) is ListType:
457 help_option_found=0
458 for help_option in cmd_class.help_options:
459 if hasattr(opts, parser.get_attr_name(help_option[0])):
460 help_option_found=1
461 #print "showing help for option %s of command %s" % (help_option[0],cmd_class)
462 if callable(help_option[3]):
463 help_option[3]()
464 else:
465 raise DistutilsClassError, \
466 ("command class %s must provide " +
467 "a callable object for help_option '%s'") % \
468 (cmd_class,help_option[0])
469 if help_option_found:
470 return
471
Greg Wardd5d8a992000-05-23 01:42:17 +0000472 # Put the options from the command-line into their official
473 # holding pen, the 'command_options' dictionary.
Greg Ward0e48cfd2000-05-26 01:00:15 +0000474 opt_dict = self.get_option_dict(command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000475 for (name, value) in vars(opts).items():
Greg Ward0e48cfd2000-05-26 01:00:15 +0000476 opt_dict[name] = ("command line", value)
Greg Wardd5d8a992000-05-23 01:42:17 +0000477
478 return args
479
480 # _parse_command_opts ()
481
482
483 def _show_help (self,
484 parser,
485 global_options=1,
486 display_options=1,
487 commands=[]):
488 """Show help for the setup script command-line in the form of
489 several lists of command-line options. 'parser' should be a
490 FancyGetopt instance; do not expect it to be returned in the
491 same state, as its option table will be reset to make it
492 generate the correct help text.
493
494 If 'global_options' is true, lists the global options:
495 --verbose, --dry-run, etc. If 'display_options' is true, lists
496 the "display-only" options: --name, --version, etc. Finally,
497 lists per-command help for every command name or command class
498 in 'commands'.
499 """
500 # late import because of mutual dependence between these modules
501 from distutils.core import usage
502 from distutils.cmd import Command
503
504 if global_options:
505 parser.set_option_table (self.global_options)
506 parser.print_help ("Global options:")
507 print
508
509 if display_options:
510 parser.set_option_table (self.display_options)
511 parser.print_help (
512 "Information display options (just display " +
513 "information, ignore any commands)")
514 print
515
516 for command in self.commands:
517 if type(command) is ClassType and issubclass(klass, Command):
518 klass = command
519 else:
520 klass = self.get_command_class (command)
Greg Ward9d17a7a2000-06-07 03:00:06 +0000521 if hasattr(klass,"help_options") and type (klass.help_options) is ListType:
522 parser.set_option_table (klass.user_options+
523 map(lambda x:(x[0],x[1],x[2]),klass.help_options))
524 else:
525 parser.set_option_table (klass.user_options)
Greg Wardd5d8a992000-05-23 01:42:17 +0000526 parser.print_help ("Options for '%s' command:" % klass.__name__)
527 print
528
529 print usage
530 return
531
532 # _show_help ()
Greg Ward9d17a7a2000-06-07 03:00:06 +0000533
Greg Wardd5d8a992000-05-23 01:42:17 +0000534
Greg Ward82715e12000-04-21 02:28:14 +0000535 def handle_display_options (self, option_order):
536 """If there were any non-global "display-only" options
Greg Wardd5d8a992000-05-23 01:42:17 +0000537 (--help-commands or the metadata display options) on the command
538 line, display the requested info and return true; else return
539 false.
540 """
Greg Ward82715e12000-04-21 02:28:14 +0000541 from distutils.core import usage
542
543 # User just wants a list of commands -- we'll print it out and stop
544 # processing now (ie. if they ran "setup --help-commands foo bar",
545 # we ignore "foo bar").
546 if self.help_commands:
547 self.print_commands ()
548 print
549 print usage
550 return 1
551
552 # If user supplied any of the "display metadata" options, then
553 # display that metadata in the order in which the user supplied the
554 # metadata options.
555 any_display_options = 0
556 is_display_option = {}
557 for option in self.display_options:
558 is_display_option[option[0]] = 1
559
560 for (opt, val) in option_order:
561 if val and is_display_option.get(opt):
562 opt = string.translate (opt, longopt_xlate)
563 print getattr(self.metadata, "get_"+opt)()
564 any_display_options = 1
565
566 return any_display_options
567
568 # handle_display_options()
Greg Wardfe6462c2000-04-04 01:40:52 +0000569
570 def print_command_list (self, commands, header, max_length):
571 """Print a subset of the list of all commands -- used by
Greg Wardd5d8a992000-05-23 01:42:17 +0000572 'print_commands()'.
573 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000574
575 print header + ":"
576
577 for cmd in commands:
578 klass = self.cmdclass.get (cmd)
579 if not klass:
Greg Wardd5d8a992000-05-23 01:42:17 +0000580 klass = self.get_command_class (cmd)
Greg Wardfe6462c2000-04-04 01:40:52 +0000581 try:
582 description = klass.description
583 except AttributeError:
584 description = "(no description available)"
585
586 print " %-*s %s" % (max_length, cmd, description)
587
588 # print_command_list ()
589
590
591 def print_commands (self):
Greg Wardd5d8a992000-05-23 01:42:17 +0000592 """Print out a help message listing all available commands with a
593 description of each. The list is divided into "standard commands"
594 (listed in distutils.command.__all__) and "extra commands"
595 (mentioned in self.cmdclass, but not a standard command). The
596 descriptions come from the command class attribute
597 'description'.
598 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000599
600 import distutils.command
601 std_commands = distutils.command.__all__
602 is_std = {}
603 for cmd in std_commands:
604 is_std[cmd] = 1
605
606 extra_commands = []
607 for cmd in self.cmdclass.keys():
608 if not is_std.get(cmd):
609 extra_commands.append (cmd)
610
611 max_length = 0
612 for cmd in (std_commands + extra_commands):
613 if len (cmd) > max_length:
614 max_length = len (cmd)
615
616 self.print_command_list (std_commands,
617 "Standard commands",
618 max_length)
619 if extra_commands:
620 print
621 self.print_command_list (extra_commands,
622 "Extra commands",
623 max_length)
624
625 # print_commands ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000626
627
628 # -- Command class/object methods ----------------------------------
629
Greg Wardd5d8a992000-05-23 01:42:17 +0000630 def get_command_class (self, command):
631 """Return the class that implements the Distutils command named by
632 'command'. First we check the 'cmdclass' dictionary; if the
633 command is mentioned there, we fetch the class object from the
634 dictionary and return it. Otherwise we load the command module
635 ("distutils.command." + command) and fetch the command class from
636 the module. The loaded class is also stored in 'cmdclass'
637 to speed future calls to 'get_command_class()'.
Greg Wardfe6462c2000-04-04 01:40:52 +0000638
Gregory P. Smith14263542000-05-12 00:41:33 +0000639 Raises DistutilsModuleError if the expected module could not be
Greg Wardd5d8a992000-05-23 01:42:17 +0000640 found, or if that module does not define the expected class.
641 """
642 klass = self.cmdclass.get(command)
643 if klass:
644 return klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000645
646 module_name = 'distutils.command.' + command
647 klass_name = command
648
649 try:
650 __import__ (module_name)
651 module = sys.modules[module_name]
652 except ImportError:
653 raise DistutilsModuleError, \
654 "invalid command '%s' (no module named '%s')" % \
655 (command, module_name)
656
657 try:
Greg Wardd5d8a992000-05-23 01:42:17 +0000658 klass = getattr(module, klass_name)
659 except AttributeError:
Greg Wardfe6462c2000-04-04 01:40:52 +0000660 raise DistutilsModuleError, \
661 "invalid command '%s' (no class '%s' in module '%s')" \
662 % (command, klass_name, module_name)
663
Greg Wardd5d8a992000-05-23 01:42:17 +0000664 self.cmdclass[command] = klass
Greg Wardfe6462c2000-04-04 01:40:52 +0000665 return klass
666
Greg Wardd5d8a992000-05-23 01:42:17 +0000667 # get_command_class ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000668
Greg Wardd5d8a992000-05-23 01:42:17 +0000669 def get_command_obj (self, command, create=1):
670 """Return the command object for 'command'. Normally this object
671 is cached on a previous call to 'get_command_obj()'; if no comand
672 object for 'command' is in the cache, then we either create and
673 return it (if 'create' is true) or return None.
674 """
Greg Ward2bd3f422000-06-02 01:59:33 +0000675 from distutils.core import DEBUG
Greg Wardd5d8a992000-05-23 01:42:17 +0000676 cmd_obj = self.command_obj.get(command)
Greg Wardfe6462c2000-04-04 01:40:52 +0000677 if not cmd_obj and create:
Greg Ward2bd3f422000-06-02 01:59:33 +0000678 if DEBUG:
679 print "Distribution.get_command_obj(): " \
680 "creating '%s' command object" % command
Greg Ward47460772000-05-23 03:47:35 +0000681
Greg Wardd5d8a992000-05-23 01:42:17 +0000682 klass = self.get_command_class(command)
Greg Ward47460772000-05-23 03:47:35 +0000683 cmd_obj = self.command_obj[command] = klass(self)
684 self.have_run[command] = 0
685
686 # Set any options that were supplied in config files
687 # or on the command line. (NB. support for error
688 # reporting is lame here: any errors aren't reported
689 # until 'finalize_options()' is called, which means
690 # we won't report the source of the error.)
691 options = self.command_options.get(command)
692 if options:
Greg Wardc32d9a62000-05-28 23:53:06 +0000693 self._set_command_options(cmd_obj, options)
Greg Wardfe6462c2000-04-04 01:40:52 +0000694
695 return cmd_obj
696
Greg Wardc32d9a62000-05-28 23:53:06 +0000697 def _set_command_options (self, command_obj, option_dict=None):
Greg Wardc32d9a62000-05-28 23:53:06 +0000698 """Set the options for 'command_obj' from 'option_dict'. Basically
699 this means copying elements of a dictionary ('option_dict') to
700 attributes of an instance ('command').
701
702 'command_obj' must be a Commnd instance. If 'option_dict' is not
703 supplied, uses the standard option dictionary for this command
704 (from 'self.command_options').
705 """
706 from distutils.core import DEBUG
707
708 command_name = command_obj.get_command_name()
709 if option_dict is None:
710 option_dict = self.get_option_dict(command_name)
711
712 if DEBUG: print " setting options for '%s' command:" % command_name
713 for (option, (source, value)) in option_dict.items():
714 if DEBUG: print " %s = %s (from %s)" % (option, value, source)
715 if not hasattr(command_obj, option):
716 raise DistutilsOptionError, \
717 ("error in %s: command '%s' has no such option '%s'") % \
718 (source, command_name, option)
719 setattr(command_obj, option, value)
720
721 def reinitialize_command (self, command):
722 """Reinitializes a command to the state it was in when first
723 returned by 'get_command_obj()': ie., initialized but not yet
724 finalized. This gives provides the opportunity to sneak option
725 values in programmatically, overriding or supplementing
726 user-supplied values from the config files and command line.
727 You'll have to re-finalize the command object (by calling
728 'finalize_options()' or 'ensure_finalized()') before using it for
729 real.
730
731 'command' should be a command name (string) or command object.
732 Returns the reinitialized command object.
733 """
734 from distutils.cmd import Command
735 if not isinstance(command, Command):
736 command_name = command
737 command = self.get_command_obj(command_name)
738 else:
739 command_name = command.get_command_name()
740
741 if not command.finalized:
Greg Ward282c7a02000-06-01 01:09:47 +0000742 return command
Greg Wardc32d9a62000-05-28 23:53:06 +0000743 command.initialize_options()
744 command.finalized = 0
Greg Ward43955c92000-06-06 02:52:36 +0000745 self.have_run[command_name] = 0
Greg Wardc32d9a62000-05-28 23:53:06 +0000746 self._set_command_options(command)
747 return command
748
Greg Wardfe6462c2000-04-04 01:40:52 +0000749
750 # -- Methods that operate on the Distribution ----------------------
751
752 def announce (self, msg, level=1):
753 """Print 'msg' if 'level' is greater than or equal to the verbosity
Greg Wardd5d8a992000-05-23 01:42:17 +0000754 level recorded in the 'verbose' attribute (which, currently, can be
755 only 0 or 1).
756 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000757 if self.verbose >= level:
758 print msg
759
760
761 def run_commands (self):
Greg Ward82715e12000-04-21 02:28:14 +0000762 """Run each command that was seen on the setup script command line.
Greg Wardd5d8a992000-05-23 01:42:17 +0000763 Uses the list of commands found and cache of command objects
764 created by 'get_command_obj()'."""
Greg Wardfe6462c2000-04-04 01:40:52 +0000765
766 for cmd in self.commands:
767 self.run_command (cmd)
768
769
Greg Wardfe6462c2000-04-04 01:40:52 +0000770 # -- Methods that operate on its Commands --------------------------
771
772 def run_command (self, command):
Greg Wardfe6462c2000-04-04 01:40:52 +0000773 """Do whatever it takes to run a command (including nothing at all,
Greg Wardd5d8a992000-05-23 01:42:17 +0000774 if the command has already been run). Specifically: if we have
775 already created and run the command named by 'command', return
776 silently without doing anything. If the command named by 'command'
777 doesn't even have a command object yet, create one. Then invoke
778 'run()' on that command object (or an existing one).
779 """
Greg Wardfe6462c2000-04-04 01:40:52 +0000780
781 # Already been here, done that? then return silently.
782 if self.have_run.get (command):
783 return
784
785 self.announce ("running " + command)
Greg Wardd5d8a992000-05-23 01:42:17 +0000786 cmd_obj = self.get_command_obj (command)
Greg Ward4fb29e52000-05-27 17:27:23 +0000787 cmd_obj.ensure_finalized ()
Greg Wardfe6462c2000-04-04 01:40:52 +0000788 cmd_obj.run ()
789 self.have_run[command] = 1
790
791
Greg Wardfe6462c2000-04-04 01:40:52 +0000792 # -- Distribution query methods ------------------------------------
793
794 def has_pure_modules (self):
795 return len (self.packages or self.py_modules or []) > 0
796
797 def has_ext_modules (self):
798 return self.ext_modules and len (self.ext_modules) > 0
799
800 def has_c_libraries (self):
801 return self.libraries and len (self.libraries) > 0
802
803 def has_modules (self):
804 return self.has_pure_modules() or self.has_ext_modules()
805
Greg Ward51def7d2000-05-27 01:36:14 +0000806 def has_headers (self):
807 return self.headers and len(self.headers) > 0
808
Greg Ward44a61bb2000-05-20 15:06:48 +0000809 def has_scripts (self):
810 return self.scripts and len(self.scripts) > 0
811
812 def has_data_files (self):
813 return self.data_files and len(self.data_files) > 0
814
Greg Wardfe6462c2000-04-04 01:40:52 +0000815 def is_pure (self):
816 return (self.has_pure_modules() and
817 not self.has_ext_modules() and
818 not self.has_c_libraries())
819
Greg Ward82715e12000-04-21 02:28:14 +0000820 # -- Metadata query methods ----------------------------------------
821
822 # If you're looking for 'get_name()', 'get_version()', and so forth,
823 # they are defined in a sneaky way: the constructor binds self.get_XXX
824 # to self.metadata.get_XXX. The actual code is in the
825 # DistributionMetadata class, below.
826
827# class Distribution
828
829
830class DistributionMetadata:
831 """Dummy class to hold the distribution meta-data: name, version,
832 author, and so forth."""
833
834 def __init__ (self):
835 self.name = None
836 self.version = None
837 self.author = None
838 self.author_email = None
839 self.maintainer = None
840 self.maintainer_email = None
841 self.url = None
842 self.licence = None
843 self.description = None
Greg Warde5a584e2000-04-26 02:26:55 +0000844 self.long_description = None
Greg Ward82715e12000-04-21 02:28:14 +0000845
846 # -- Metadata query methods ----------------------------------------
847
Greg Wardfe6462c2000-04-04 01:40:52 +0000848 def get_name (self):
849 return self.name or "UNKNOWN"
850
Greg Ward82715e12000-04-21 02:28:14 +0000851 def get_version(self):
852 return self.version or "???"
Greg Wardfe6462c2000-04-04 01:40:52 +0000853
Greg Ward82715e12000-04-21 02:28:14 +0000854 def get_fullname (self):
855 return "%s-%s" % (self.get_name(), self.get_version())
856
857 def get_author(self):
858 return self.author or "UNKNOWN"
859
860 def get_author_email(self):
861 return self.author_email or "UNKNOWN"
862
863 def get_maintainer(self):
864 return self.maintainer or "UNKNOWN"
865
866 def get_maintainer_email(self):
867 return self.maintainer_email or "UNKNOWN"
868
869 def get_contact(self):
870 return (self.maintainer or
871 self.author or
872 "UNKNOWN")
873
874 def get_contact_email(self):
875 return (self.maintainer_email or
876 self.author_email or
877 "UNKNOWN")
878
879 def get_url(self):
880 return self.url or "UNKNOWN"
881
882 def get_licence(self):
883 return self.licence or "UNKNOWN"
884
885 def get_description(self):
886 return self.description or "UNKNOWN"
Greg Warde5a584e2000-04-26 02:26:55 +0000887
888 def get_long_description(self):
889 return self.long_description or "UNKNOWN"
890
Greg Ward82715e12000-04-21 02:28:14 +0000891# class DistributionMetadata
Greg Wardfe6462c2000-04-04 01:40:52 +0000892
893if __name__ == "__main__":
894 dist = Distribution ()
895 print "ok"