Fix a bug in the ``compiler`` package that caused invalid code to be
[python/dscho.git] / Lib / distutils / dist.py
blobff49886d97fabdfa2afa67a023ddb6322af89fb9
1 """distutils.dist
3 Provides the Distribution class, which represents the module distribution
4 being built/installed/distributed.
5 """
7 # This module should be kept compatible with Python 2.1.
9 __revision__ = "$Id$"
11 import sys, os, string, re
12 from types import *
13 from copy import copy
15 try:
16 import warnings
17 except ImportError:
18 warnings = None
20 from distutils.errors import *
21 from distutils.fancy_getopt import FancyGetopt, translate_longopt
22 from distutils.util import check_environ, strtobool, rfc822_escape
23 from distutils import log
24 from distutils.debug import DEBUG
26 # Regex to define acceptable Distutils command names. This is not *quite*
27 # the same as a Python NAME -- I don't allow leading underscores. The fact
28 # that they're very similar is no coincidence; the default naming scheme is
29 # to look for a Python module named after the command.
30 command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
33 class Distribution:
34 """The core of the Distutils. Most of the work hiding behind 'setup'
35 is really done within a Distribution instance, which farms the work out
36 to the Distutils commands specified on the command line.
38 Setup scripts will almost never instantiate Distribution directly,
39 unless the 'setup()' function is totally inadequate to their needs.
40 However, it is conceivable that a setup script might wish to subclass
41 Distribution for some specialized purpose, and then pass the subclass
42 to 'setup()' as the 'distclass' keyword argument. If so, it is
43 necessary to respect the expectations that 'setup' has of Distribution.
44 See the code for 'setup()', in core.py, for details.
45 """
48 # 'global_options' describes the command-line options that may be
49 # supplied to the setup script prior to any actual commands.
50 # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
51 # these global options. This list should be kept to a bare minimum,
52 # since every global option is also valid as a command option -- and we
53 # don't want to pollute the commands with too many options that they
54 # have minimal control over.
55 # The fourth entry for verbose means that it can be repeated.
56 global_options = [('verbose', 'v', "run verbosely (default)", 1),
57 ('quiet', 'q', "run quietly (turns verbosity off)"),
58 ('dry-run', 'n', "don't actually do anything"),
59 ('help', 'h', "show detailed help message"),
62 # 'common_usage' is a short (2-3 line) string describing the common
63 # usage of the setup script.
64 common_usage = """\
65 Common commands: (see '--help-commands' for more)
67 setup.py build will build the package underneath 'build/'
68 setup.py install will install the package
69 """
71 # options that are not propagated to the commands
72 display_options = [
73 ('help-commands', None,
74 "list all available commands"),
75 ('name', None,
76 "print package name"),
77 ('version', 'V',
78 "print package version"),
79 ('fullname', None,
80 "print <package name>-<version>"),
81 ('author', None,
82 "print the author's name"),
83 ('author-email', None,
84 "print the author's email address"),
85 ('maintainer', None,
86 "print the maintainer's name"),
87 ('maintainer-email', None,
88 "print the maintainer's email address"),
89 ('contact', None,
90 "print the maintainer's name if known, else the author's"),
91 ('contact-email', None,
92 "print the maintainer's email address if known, else the author's"),
93 ('url', None,
94 "print the URL for this package"),
95 ('license', None,
96 "print the license of the package"),
97 ('licence', None,
98 "alias for --license"),
99 ('description', None,
100 "print the package description"),
101 ('long-description', None,
102 "print the long package description"),
103 ('platforms', None,
104 "print the list of platforms"),
105 ('classifiers', None,
106 "print the list of classifiers"),
107 ('keywords', None,
108 "print the list of keywords"),
109 ('provides', None,
110 "print the list of packages/modules provided"),
111 ('requires', None,
112 "print the list of packages/modules required"),
113 ('obsoletes', None,
114 "print the list of packages/modules made obsolete")
116 display_option_names = map(lambda x: translate_longopt(x[0]),
117 display_options)
119 # negative options are options that exclude other options
120 negative_opt = {'quiet': 'verbose'}
123 # -- Creation/initialization methods -------------------------------
125 def __init__ (self, attrs=None):
126 """Construct a new Distribution instance: initialize all the
127 attributes of a Distribution, and then use 'attrs' (a dictionary
128 mapping attribute names to values) to assign some of those
129 attributes their "real" values. (Any attributes not mentioned in
130 'attrs' will be assigned to some null value: 0, None, an empty list
131 or dictionary, etc.) Most importantly, initialize the
132 'command_obj' attribute to the empty dictionary; this will be
133 filled in with real command objects by 'parse_command_line()'.
136 # Default values for our command-line options
137 self.verbose = 1
138 self.dry_run = 0
139 self.help = 0
140 for attr in self.display_option_names:
141 setattr(self, attr, 0)
143 # Store the distribution meta-data (name, version, author, and so
144 # forth) in a separate object -- we're getting to have enough
145 # information here (and enough command-line options) that it's
146 # worth it. Also delegate 'get_XXX()' methods to the 'metadata'
147 # object in a sneaky and underhanded (but efficient!) way.
148 self.metadata = DistributionMetadata()
149 for basename in self.metadata._METHOD_BASENAMES:
150 method_name = "get_" + basename
151 setattr(self, method_name, getattr(self.metadata, method_name))
153 # 'cmdclass' maps command names to class objects, so we
154 # can 1) quickly figure out which class to instantiate when
155 # we need to create a new command object, and 2) have a way
156 # for the setup script to override command classes
157 self.cmdclass = {}
159 # 'command_packages' is a list of packages in which commands
160 # are searched for. The factory for command 'foo' is expected
161 # to be named 'foo' in the module 'foo' in one of the packages
162 # named here. This list is searched from the left; an error
163 # is raised if no named package provides the command being
164 # searched for. (Always access using get_command_packages().)
165 self.command_packages = None
167 # 'script_name' and 'script_args' are usually set to sys.argv[0]
168 # and sys.argv[1:], but they can be overridden when the caller is
169 # not necessarily a setup script run from the command-line.
170 self.script_name = None
171 self.script_args = None
173 # 'command_options' is where we store command options between
174 # parsing them (from config files, the command-line, etc.) and when
175 # they are actually needed -- ie. when the command in question is
176 # instantiated. It is a dictionary of dictionaries of 2-tuples:
177 # command_options = { command_name : { option : (source, value) } }
178 self.command_options = {}
180 # 'dist_files' is the list of (command, pyversion, file) that
181 # have been created by any dist commands run so far. This is
182 # filled regardless of whether the run is dry or not. pyversion
183 # gives sysconfig.get_python_version() if the dist file is
184 # specific to a Python version, 'any' if it is good for all
185 # Python versions on the target platform, and '' for a source
186 # file. pyversion should not be used to specify minimum or
187 # maximum required Python versions; use the metainfo for that
188 # instead.
189 self.dist_files = []
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 self.packages = None
195 self.package_data = {}
196 self.package_dir = None
197 self.py_modules = None
198 self.libraries = None
199 self.headers = None
200 self.ext_modules = None
201 self.ext_package = None
202 self.include_dirs = None
203 self.extra_path = None
204 self.scripts = None
205 self.data_files = None
207 # And now initialize bookkeeping stuff that can't be supplied by
208 # the caller at all. 'command_obj' maps command names to
209 # Command instances -- that's how we enforce that every command
210 # class is a singleton.
211 self.command_obj = {}
213 # 'have_run' maps command names to boolean values; it keeps track
214 # of whether we have actually run a particular command, to make it
215 # cheap to "run" a command whenever we think we might need to -- if
216 # it's already been done, no need for expensive filesystem
217 # operations, we just check the 'have_run' dictionary and carry on.
218 # It's only safe to query 'have_run' for a command class that has
219 # been instantiated -- a false value will be inserted when the
220 # command object is created, and replaced with a true value when
221 # the command is successfully run. Thus it's probably best to use
222 # '.get()' rather than a straight lookup.
223 self.have_run = {}
225 # Now we'll use the attrs dictionary (ultimately, keyword args from
226 # the setup script) to possibly override any or all of these
227 # distribution options.
229 if attrs:
230 # Pull out the set of command options and work on them
231 # specifically. Note that this order guarantees that aliased
232 # command options will override any supplied redundantly
233 # through the general options dictionary.
234 options = attrs.get('options')
235 if options:
236 del attrs['options']
237 for (command, cmd_options) in options.items():
238 opt_dict = self.get_option_dict(command)
239 for (opt, val) in cmd_options.items():
240 opt_dict[opt] = ("setup script", val)
242 if attrs.has_key('licence'):
243 attrs['license'] = attrs['licence']
244 del attrs['licence']
245 msg = "'licence' distribution option is deprecated; use 'license'"
246 if warnings is not None:
247 warnings.warn(msg)
248 else:
249 sys.stderr.write(msg + "\n")
251 # Now work on the rest of the attributes. Any attribute that's
252 # not already defined is invalid!
253 for (key,val) in attrs.items():
254 if hasattr(self.metadata, "set_" + key):
255 getattr(self.metadata, "set_" + key)(val)
256 elif hasattr(self.metadata, key):
257 setattr(self.metadata, key, val)
258 elif hasattr(self, key):
259 setattr(self, key, val)
260 else:
261 msg = "Unknown distribution option: %s" % repr(key)
262 if warnings is not None:
263 warnings.warn(msg)
264 else:
265 sys.stderr.write(msg + "\n")
267 self.finalize_options()
269 # __init__ ()
272 def get_option_dict (self, command):
273 """Get the option dictionary for a given command. If that
274 command's option dictionary hasn't been created yet, then create it
275 and return the new dictionary; otherwise, return the existing
276 option dictionary.
279 dict = self.command_options.get(command)
280 if dict is None:
281 dict = self.command_options[command] = {}
282 return dict
285 def dump_option_dicts (self, header=None, commands=None, indent=""):
286 from pprint import pformat
288 if commands is None: # dump all command option dicts
289 commands = self.command_options.keys()
290 commands.sort()
292 if header is not None:
293 print indent + header
294 indent = indent + " "
296 if not commands:
297 print indent + "no commands known yet"
298 return
300 for cmd_name in commands:
301 opt_dict = self.command_options.get(cmd_name)
302 if opt_dict is None:
303 print indent + "no option dict for '%s' command" % cmd_name
304 else:
305 print indent + "option dict for '%s' command:" % cmd_name
306 out = pformat(opt_dict)
307 for line in string.split(out, "\n"):
308 print indent + " " + line
310 # dump_option_dicts ()
314 # -- Config file finding/parsing methods ---------------------------
316 def find_config_files (self):
317 """Find as many configuration files as should be processed for this
318 platform, and return a list of filenames in the order in which they
319 should be parsed. The filenames returned are guaranteed to exist
320 (modulo nasty race conditions).
322 There are three possible config files: distutils.cfg in the
323 Distutils installation directory (ie. where the top-level
324 Distutils __inst__.py file lives), a file in the user's home
325 directory named .pydistutils.cfg on Unix and pydistutils.cfg
326 on Windows/Mac, and setup.cfg in the current directory.
328 files = []
329 check_environ()
331 # Where to look for the system-wide Distutils config file
332 sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
334 # Look for the system config file
335 sys_file = os.path.join(sys_dir, "distutils.cfg")
336 if os.path.isfile(sys_file):
337 files.append(sys_file)
339 # What to call the per-user config file
340 if os.name == 'posix':
341 user_filename = ".pydistutils.cfg"
342 else:
343 user_filename = "pydistutils.cfg"
345 # And look for the user config file
346 if os.environ.has_key('HOME'):
347 user_file = os.path.join(os.environ.get('HOME'), user_filename)
348 if os.path.isfile(user_file):
349 files.append(user_file)
351 # All platforms support local setup.cfg
352 local_file = "setup.cfg"
353 if os.path.isfile(local_file):
354 files.append(local_file)
356 return files
358 # find_config_files ()
361 def parse_config_files (self, filenames=None):
363 from ConfigParser import ConfigParser
365 if filenames is None:
366 filenames = self.find_config_files()
368 if DEBUG: print "Distribution.parse_config_files():"
370 parser = ConfigParser()
371 for filename in filenames:
372 if DEBUG: print " reading", filename
373 parser.read(filename)
374 for section in parser.sections():
375 options = parser.options(section)
376 opt_dict = self.get_option_dict(section)
378 for opt in options:
379 if opt != '__name__':
380 val = parser.get(section,opt)
381 opt = string.replace(opt, '-', '_')
382 opt_dict[opt] = (filename, val)
384 # Make the ConfigParser forget everything (so we retain
385 # the original filenames that options come from)
386 parser.__init__()
388 # If there was a "global" section in the config file, use it
389 # to set Distribution options.
391 if self.command_options.has_key('global'):
392 for (opt, (src, val)) in self.command_options['global'].items():
393 alias = self.negative_opt.get(opt)
394 try:
395 if alias:
396 setattr(self, alias, not strtobool(val))
397 elif opt in ('verbose', 'dry_run'): # ugh!
398 setattr(self, opt, strtobool(val))
399 else:
400 setattr(self, opt, val)
401 except ValueError, msg:
402 raise DistutilsOptionError, msg
404 # parse_config_files ()
407 # -- Command-line parsing methods ----------------------------------
409 def parse_command_line (self):
410 """Parse the setup script's command line, taken from the
411 'script_args' instance attribute (which defaults to 'sys.argv[1:]'
412 -- see 'setup()' in core.py). This list is first processed for
413 "global options" -- options that set attributes of the Distribution
414 instance. Then, it is alternately scanned for Distutils commands
415 and options for that command. Each new command terminates the
416 options for the previous command. The allowed options for a
417 command are determined by the 'user_options' attribute of the
418 command class -- thus, we have to be able to load command classes
419 in order to parse the command line. Any error in that 'options'
420 attribute raises DistutilsGetoptError; any error on the
421 command-line raises DistutilsArgError. If no Distutils commands
422 were found on the command line, raises DistutilsArgError. Return
423 true if command-line was successfully parsed and we should carry
424 on with executing commands; false if no errors but we shouldn't
425 execute commands (currently, this only happens if user asks for
426 help).
429 # We now have enough information to show the Macintosh dialog
430 # that allows the user to interactively specify the "command line".
432 toplevel_options = self._get_toplevel_options()
433 if sys.platform == 'mac':
434 import EasyDialogs
435 cmdlist = self.get_command_list()
436 self.script_args = EasyDialogs.GetArgv(
437 toplevel_options + self.display_options, cmdlist)
439 # We have to parse the command line a bit at a time -- global
440 # options, then the first command, then its options, and so on --
441 # because each command will be handled by a different class, and
442 # the options that are valid for a particular class aren't known
443 # until we have loaded the command class, which doesn't happen
444 # until we know what the command is.
446 self.commands = []
447 parser = FancyGetopt(toplevel_options + self.display_options)
448 parser.set_negative_aliases(self.negative_opt)
449 parser.set_aliases({'licence': 'license'})
450 args = parser.getopt(args=self.script_args, object=self)
451 option_order = parser.get_option_order()
452 log.set_verbosity(self.verbose)
454 # for display options we return immediately
455 if self.handle_display_options(option_order):
456 return
458 while args:
459 args = self._parse_command_opts(parser, args)
460 if args is None: # user asked for help (and got it)
461 return
463 # Handle the cases of --help as a "global" option, ie.
464 # "setup.py --help" and "setup.py --help command ...". For the
465 # former, we show global options (--verbose, --dry-run, etc.)
466 # and display-only options (--name, --version, etc.); for the
467 # latter, we omit the display-only options and show help for
468 # each command listed on the command line.
469 if self.help:
470 self._show_help(parser,
471 display_options=len(self.commands) == 0,
472 commands=self.commands)
473 return
475 # Oops, no commands found -- an end-user error
476 if not self.commands:
477 raise DistutilsArgError, "no commands supplied"
479 # All is well: return true
480 return 1
482 # parse_command_line()
484 def _get_toplevel_options (self):
485 """Return the non-display options recognized at the top level.
487 This includes options that are recognized *only* at the top
488 level as well as options recognized for commands.
490 return self.global_options + [
491 ("command-packages=", None,
492 "list of packages that provide distutils commands"),
495 def _parse_command_opts (self, parser, args):
496 """Parse the command-line options for a single command.
497 'parser' must be a FancyGetopt instance; 'args' must be the list
498 of arguments, starting with the current command (whose options
499 we are about to parse). Returns a new version of 'args' with
500 the next command at the front of the list; will be the empty
501 list if there are no more commands on the command line. Returns
502 None if the user asked for help on this command.
504 # late import because of mutual dependence between these modules
505 from distutils.cmd import Command
507 # Pull the current command from the head of the command line
508 command = args[0]
509 if not command_re.match(command):
510 raise SystemExit, "invalid command name '%s'" % command
511 self.commands.append(command)
513 # Dig up the command class that implements this command, so we
514 # 1) know that it's a valid command, and 2) know which options
515 # it takes.
516 try:
517 cmd_class = self.get_command_class(command)
518 except DistutilsModuleError, msg:
519 raise DistutilsArgError, msg
521 # Require that the command class be derived from Command -- want
522 # to be sure that the basic "command" interface is implemented.
523 if not issubclass(cmd_class, Command):
524 raise DistutilsClassError, \
525 "command class %s must subclass Command" % cmd_class
527 # Also make sure that the command object provides a list of its
528 # known options.
529 if not (hasattr(cmd_class, 'user_options') and
530 type(cmd_class.user_options) is ListType):
531 raise DistutilsClassError, \
532 ("command class %s must provide " +
533 "'user_options' attribute (a list of tuples)") % \
534 cmd_class
536 # If the command class has a list of negative alias options,
537 # merge it in with the global negative aliases.
538 negative_opt = self.negative_opt
539 if hasattr(cmd_class, 'negative_opt'):
540 negative_opt = copy(negative_opt)
541 negative_opt.update(cmd_class.negative_opt)
543 # Check for help_options in command class. They have a different
544 # format (tuple of four) so we need to preprocess them here.
545 if (hasattr(cmd_class, 'help_options') and
546 type(cmd_class.help_options) is ListType):
547 help_options = fix_help_options(cmd_class.help_options)
548 else:
549 help_options = []
552 # All commands support the global options too, just by adding
553 # in 'global_options'.
554 parser.set_option_table(self.global_options +
555 cmd_class.user_options +
556 help_options)
557 parser.set_negative_aliases(negative_opt)
558 (args, opts) = parser.getopt(args[1:])
559 if hasattr(opts, 'help') and opts.help:
560 self._show_help(parser, display_options=0, commands=[cmd_class])
561 return
563 if (hasattr(cmd_class, 'help_options') and
564 type(cmd_class.help_options) is ListType):
565 help_option_found=0
566 for (help_option, short, desc, func) in cmd_class.help_options:
567 if hasattr(opts, parser.get_attr_name(help_option)):
568 help_option_found=1
569 #print "showing help for option %s of command %s" % \
570 # (help_option[0],cmd_class)
572 if callable(func):
573 func()
574 else:
575 raise DistutilsClassError(
576 "invalid help function %r for help option '%s': "
577 "must be a callable object (function, etc.)"
578 % (func, help_option))
580 if help_option_found:
581 return
583 # Put the options from the command-line into their official
584 # holding pen, the 'command_options' dictionary.
585 opt_dict = self.get_option_dict(command)
586 for (name, value) in vars(opts).items():
587 opt_dict[name] = ("command line", value)
589 return args
591 # _parse_command_opts ()
593 def finalize_options (self):
594 """Set final values for all the options on the Distribution
595 instance, analogous to the .finalize_options() method of Command
596 objects.
599 keywords = self.metadata.keywords
600 if keywords is not None:
601 if type(keywords) is StringType:
602 keywordlist = string.split(keywords, ',')
603 self.metadata.keywords = map(string.strip, keywordlist)
605 platforms = self.metadata.platforms
606 if platforms is not None:
607 if type(platforms) is StringType:
608 platformlist = string.split(platforms, ',')
609 self.metadata.platforms = map(string.strip, platformlist)
611 def _show_help (self,
612 parser,
613 global_options=1,
614 display_options=1,
615 commands=[]):
616 """Show help for the setup script command-line in the form of
617 several lists of command-line options. 'parser' should be a
618 FancyGetopt instance; do not expect it to be returned in the
619 same state, as its option table will be reset to make it
620 generate the correct help text.
622 If 'global_options' is true, lists the global options:
623 --verbose, --dry-run, etc. If 'display_options' is true, lists
624 the "display-only" options: --name, --version, etc. Finally,
625 lists per-command help for every command name or command class
626 in 'commands'.
628 # late import because of mutual dependence between these modules
629 from distutils.core import gen_usage
630 from distutils.cmd import Command
632 if global_options:
633 if display_options:
634 options = self._get_toplevel_options()
635 else:
636 options = self.global_options
637 parser.set_option_table(options)
638 parser.print_help(self.common_usage + "\nGlobal options:")
639 print
641 if display_options:
642 parser.set_option_table(self.display_options)
643 parser.print_help(
644 "Information display options (just display " +
645 "information, ignore any commands)")
646 print
648 for command in self.commands:
649 if type(command) is ClassType and issubclass(command, Command):
650 klass = command
651 else:
652 klass = self.get_command_class(command)
653 if (hasattr(klass, 'help_options') and
654 type(klass.help_options) is ListType):
655 parser.set_option_table(klass.user_options +
656 fix_help_options(klass.help_options))
657 else:
658 parser.set_option_table(klass.user_options)
659 parser.print_help("Options for '%s' command:" % klass.__name__)
660 print
662 print gen_usage(self.script_name)
663 return
665 # _show_help ()
668 def handle_display_options (self, option_order):
669 """If there were any non-global "display-only" options
670 (--help-commands or the metadata display options) on the command
671 line, display the requested info and return true; else return
672 false.
674 from distutils.core import gen_usage
676 # User just wants a list of commands -- we'll print it out and stop
677 # processing now (ie. if they ran "setup --help-commands foo bar",
678 # we ignore "foo bar").
679 if self.help_commands:
680 self.print_commands()
681 print
682 print gen_usage(self.script_name)
683 return 1
685 # If user supplied any of the "display metadata" options, then
686 # display that metadata in the order in which the user supplied the
687 # metadata options.
688 any_display_options = 0
689 is_display_option = {}
690 for option in self.display_options:
691 is_display_option[option[0]] = 1
693 for (opt, val) in option_order:
694 if val and is_display_option.get(opt):
695 opt = translate_longopt(opt)
696 value = getattr(self.metadata, "get_"+opt)()
697 if opt in ['keywords', 'platforms']:
698 print string.join(value, ',')
699 elif opt in ('classifiers', 'provides', 'requires',
700 'obsoletes'):
701 print string.join(value, '\n')
702 else:
703 print value
704 any_display_options = 1
706 return any_display_options
708 # handle_display_options()
710 def print_command_list (self, commands, header, max_length):
711 """Print a subset of the list of all commands -- used by
712 'print_commands()'.
715 print header + ":"
717 for cmd in commands:
718 klass = self.cmdclass.get(cmd)
719 if not klass:
720 klass = self.get_command_class(cmd)
721 try:
722 description = klass.description
723 except AttributeError:
724 description = "(no description available)"
726 print " %-*s %s" % (max_length, cmd, description)
728 # print_command_list ()
731 def print_commands (self):
732 """Print out a help message listing all available commands with a
733 description of each. The list is divided into "standard commands"
734 (listed in distutils.command.__all__) and "extra commands"
735 (mentioned in self.cmdclass, but not a standard command). The
736 descriptions come from the command class attribute
737 'description'.
740 import distutils.command
741 std_commands = distutils.command.__all__
742 is_std = {}
743 for cmd in std_commands:
744 is_std[cmd] = 1
746 extra_commands = []
747 for cmd in self.cmdclass.keys():
748 if not is_std.get(cmd):
749 extra_commands.append(cmd)
751 max_length = 0
752 for cmd in (std_commands + extra_commands):
753 if len(cmd) > max_length:
754 max_length = len(cmd)
756 self.print_command_list(std_commands,
757 "Standard commands",
758 max_length)
759 if extra_commands:
760 print
761 self.print_command_list(extra_commands,
762 "Extra commands",
763 max_length)
765 # print_commands ()
767 def get_command_list (self):
768 """Get a list of (command, description) tuples.
769 The list is divided into "standard commands" (listed in
770 distutils.command.__all__) and "extra commands" (mentioned in
771 self.cmdclass, but not a standard command). The descriptions come
772 from the command class attribute 'description'.
774 # Currently this is only used on Mac OS, for the Mac-only GUI
775 # Distutils interface (by Jack Jansen)
777 import distutils.command
778 std_commands = distutils.command.__all__
779 is_std = {}
780 for cmd in std_commands:
781 is_std[cmd] = 1
783 extra_commands = []
784 for cmd in self.cmdclass.keys():
785 if not is_std.get(cmd):
786 extra_commands.append(cmd)
788 rv = []
789 for cmd in (std_commands + extra_commands):
790 klass = self.cmdclass.get(cmd)
791 if not klass:
792 klass = self.get_command_class(cmd)
793 try:
794 description = klass.description
795 except AttributeError:
796 description = "(no description available)"
797 rv.append((cmd, description))
798 return rv
800 # -- Command class/object methods ----------------------------------
802 def get_command_packages (self):
803 """Return a list of packages from which commands are loaded."""
804 pkgs = self.command_packages
805 if not isinstance(pkgs, type([])):
806 pkgs = string.split(pkgs or "", ",")
807 for i in range(len(pkgs)):
808 pkgs[i] = string.strip(pkgs[i])
809 pkgs = filter(None, pkgs)
810 if "distutils.command" not in pkgs:
811 pkgs.insert(0, "distutils.command")
812 self.command_packages = pkgs
813 return pkgs
815 def get_command_class (self, command):
816 """Return the class that implements the Distutils command named by
817 'command'. First we check the 'cmdclass' dictionary; if the
818 command is mentioned there, we fetch the class object from the
819 dictionary and return it. Otherwise we load the command module
820 ("distutils.command." + command) and fetch the command class from
821 the module. The loaded class is also stored in 'cmdclass'
822 to speed future calls to 'get_command_class()'.
824 Raises DistutilsModuleError if the expected module could not be
825 found, or if that module does not define the expected class.
827 klass = self.cmdclass.get(command)
828 if klass:
829 return klass
831 for pkgname in self.get_command_packages():
832 module_name = "%s.%s" % (pkgname, command)
833 klass_name = command
835 try:
836 __import__ (module_name)
837 module = sys.modules[module_name]
838 except ImportError:
839 continue
841 try:
842 klass = getattr(module, klass_name)
843 except AttributeError:
844 raise DistutilsModuleError, \
845 "invalid command '%s' (no class '%s' in module '%s')" \
846 % (command, klass_name, module_name)
848 self.cmdclass[command] = klass
849 return klass
851 raise DistutilsModuleError("invalid command '%s'" % command)
854 # get_command_class ()
856 def get_command_obj (self, command, create=1):
857 """Return the command object for 'command'. Normally this object
858 is cached on a previous call to 'get_command_obj()'; if no command
859 object for 'command' is in the cache, then we either create and
860 return it (if 'create' is true) or return None.
862 cmd_obj = self.command_obj.get(command)
863 if not cmd_obj and create:
864 if DEBUG:
865 print "Distribution.get_command_obj(): " \
866 "creating '%s' command object" % command
868 klass = self.get_command_class(command)
869 cmd_obj = self.command_obj[command] = klass(self)
870 self.have_run[command] = 0
872 # Set any options that were supplied in config files
873 # or on the command line. (NB. support for error
874 # reporting is lame here: any errors aren't reported
875 # until 'finalize_options()' is called, which means
876 # we won't report the source of the error.)
877 options = self.command_options.get(command)
878 if options:
879 self._set_command_options(cmd_obj, options)
881 return cmd_obj
883 def _set_command_options (self, command_obj, option_dict=None):
884 """Set the options for 'command_obj' from 'option_dict'. Basically
885 this means copying elements of a dictionary ('option_dict') to
886 attributes of an instance ('command').
888 'command_obj' must be a Command instance. If 'option_dict' is not
889 supplied, uses the standard option dictionary for this command
890 (from 'self.command_options').
892 command_name = command_obj.get_command_name()
893 if option_dict is None:
894 option_dict = self.get_option_dict(command_name)
896 if DEBUG: print " setting options for '%s' command:" % command_name
897 for (option, (source, value)) in option_dict.items():
898 if DEBUG: print " %s = %s (from %s)" % (option, value, source)
899 try:
900 bool_opts = map(translate_longopt, command_obj.boolean_options)
901 except AttributeError:
902 bool_opts = []
903 try:
904 neg_opt = command_obj.negative_opt
905 except AttributeError:
906 neg_opt = {}
908 try:
909 is_string = type(value) is StringType
910 if neg_opt.has_key(option) and is_string:
911 setattr(command_obj, neg_opt[option], not strtobool(value))
912 elif option in bool_opts and is_string:
913 setattr(command_obj, option, strtobool(value))
914 elif hasattr(command_obj, option):
915 setattr(command_obj, option, value)
916 else:
917 raise DistutilsOptionError, \
918 ("error in %s: command '%s' has no such option '%s'"
919 % (source, command_name, option))
920 except ValueError, msg:
921 raise DistutilsOptionError, msg
923 def reinitialize_command (self, command, reinit_subcommands=0):
924 """Reinitializes a command to the state it was in when first
925 returned by 'get_command_obj()': ie., initialized but not yet
926 finalized. This provides the opportunity to sneak option
927 values in programmatically, overriding or supplementing
928 user-supplied values from the config files and command line.
929 You'll have to re-finalize the command object (by calling
930 'finalize_options()' or 'ensure_finalized()') before using it for
931 real.
933 'command' should be a command name (string) or command object. If
934 'reinit_subcommands' is true, also reinitializes the command's
935 sub-commands, as declared by the 'sub_commands' class attribute (if
936 it has one). See the "install" command for an example. Only
937 reinitializes the sub-commands that actually matter, ie. those
938 whose test predicates return true.
940 Returns the reinitialized command object.
942 from distutils.cmd import Command
943 if not isinstance(command, Command):
944 command_name = command
945 command = self.get_command_obj(command_name)
946 else:
947 command_name = command.get_command_name()
949 if not command.finalized:
950 return command
951 command.initialize_options()
952 command.finalized = 0
953 self.have_run[command_name] = 0
954 self._set_command_options(command)
956 if reinit_subcommands:
957 for sub in command.get_sub_commands():
958 self.reinitialize_command(sub, reinit_subcommands)
960 return command
963 # -- Methods that operate on the Distribution ----------------------
965 def announce (self, msg, level=1):
966 log.debug(msg)
968 def run_commands (self):
969 """Run each command that was seen on the setup script command line.
970 Uses the list of commands found and cache of command objects
971 created by 'get_command_obj()'.
973 for cmd in self.commands:
974 self.run_command(cmd)
977 # -- Methods that operate on its Commands --------------------------
979 def run_command (self, command):
980 """Do whatever it takes to run a command (including nothing at all,
981 if the command has already been run). Specifically: if we have
982 already created and run the command named by 'command', return
983 silently without doing anything. If the command named by 'command'
984 doesn't even have a command object yet, create one. Then invoke
985 'run()' on that command object (or an existing one).
987 # Already been here, done that? then return silently.
988 if self.have_run.get(command):
989 return
991 log.info("running %s", command)
992 cmd_obj = self.get_command_obj(command)
993 cmd_obj.ensure_finalized()
994 cmd_obj.run()
995 self.have_run[command] = 1
998 # -- Distribution query methods ------------------------------------
1000 def has_pure_modules (self):
1001 return len(self.packages or self.py_modules or []) > 0
1003 def has_ext_modules (self):
1004 return self.ext_modules and len(self.ext_modules) > 0
1006 def has_c_libraries (self):
1007 return self.libraries and len(self.libraries) > 0
1009 def has_modules (self):
1010 return self.has_pure_modules() or self.has_ext_modules()
1012 def has_headers (self):
1013 return self.headers and len(self.headers) > 0
1015 def has_scripts (self):
1016 return self.scripts and len(self.scripts) > 0
1018 def has_data_files (self):
1019 return self.data_files and len(self.data_files) > 0
1021 def is_pure (self):
1022 return (self.has_pure_modules() and
1023 not self.has_ext_modules() and
1024 not self.has_c_libraries())
1026 # -- Metadata query methods ----------------------------------------
1028 # If you're looking for 'get_name()', 'get_version()', and so forth,
1029 # they are defined in a sneaky way: the constructor binds self.get_XXX
1030 # to self.metadata.get_XXX. The actual code is in the
1031 # DistributionMetadata class, below.
1033 # class Distribution
1036 class DistributionMetadata:
1037 """Dummy class to hold the distribution meta-data: name, version,
1038 author, and so forth.
1041 _METHOD_BASENAMES = ("name", "version", "author", "author_email",
1042 "maintainer", "maintainer_email", "url",
1043 "license", "description", "long_description",
1044 "keywords", "platforms", "fullname", "contact",
1045 "contact_email", "license", "classifiers",
1046 "download_url",
1047 # PEP 314
1048 "provides", "requires", "obsoletes",
1051 def __init__ (self):
1052 self.name = None
1053 self.version = None
1054 self.author = None
1055 self.author_email = None
1056 self.maintainer = None
1057 self.maintainer_email = None
1058 self.url = None
1059 self.license = None
1060 self.description = None
1061 self.long_description = None
1062 self.keywords = None
1063 self.platforms = None
1064 self.classifiers = None
1065 self.download_url = None
1066 # PEP 314
1067 self.provides = None
1068 self.requires = None
1069 self.obsoletes = None
1071 def write_pkg_info (self, base_dir):
1072 """Write the PKG-INFO file into the release tree.
1074 pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
1076 self.write_pkg_file(pkg_info)
1078 pkg_info.close()
1080 # write_pkg_info ()
1082 def write_pkg_file (self, file):
1083 """Write the PKG-INFO format data to a file object.
1085 version = '1.0'
1086 if self.provides or self.requires or self.obsoletes:
1087 version = '1.1'
1089 file.write('Metadata-Version: %s\n' % version)
1090 file.write('Name: %s\n' % self.get_name() )
1091 file.write('Version: %s\n' % self.get_version() )
1092 file.write('Summary: %s\n' % self.get_description() )
1093 file.write('Home-page: %s\n' % self.get_url() )
1094 file.write('Author: %s\n' % self.get_contact() )
1095 file.write('Author-email: %s\n' % self.get_contact_email() )
1096 file.write('License: %s\n' % self.get_license() )
1097 if self.download_url:
1098 file.write('Download-URL: %s\n' % self.download_url)
1100 long_desc = rfc822_escape( self.get_long_description() )
1101 file.write('Description: %s\n' % long_desc)
1103 keywords = string.join( self.get_keywords(), ',')
1104 if keywords:
1105 file.write('Keywords: %s\n' % keywords )
1107 self._write_list(file, 'Platform', self.get_platforms())
1108 self._write_list(file, 'Classifier', self.get_classifiers())
1110 # PEP 314
1111 self._write_list(file, 'Requires', self.get_requires())
1112 self._write_list(file, 'Provides', self.get_provides())
1113 self._write_list(file, 'Obsoletes', self.get_obsoletes())
1115 def _write_list (self, file, name, values):
1116 for value in values:
1117 file.write('%s: %s\n' % (name, value))
1119 # -- Metadata query methods ----------------------------------------
1121 def get_name (self):
1122 return self.name or "UNKNOWN"
1124 def get_version(self):
1125 return self.version or "0.0.0"
1127 def get_fullname (self):
1128 return "%s-%s" % (self.get_name(), self.get_version())
1130 def get_author(self):
1131 return self.author or "UNKNOWN"
1133 def get_author_email(self):
1134 return self.author_email or "UNKNOWN"
1136 def get_maintainer(self):
1137 return self.maintainer or "UNKNOWN"
1139 def get_maintainer_email(self):
1140 return self.maintainer_email or "UNKNOWN"
1142 def get_contact(self):
1143 return (self.maintainer or
1144 self.author or
1145 "UNKNOWN")
1147 def get_contact_email(self):
1148 return (self.maintainer_email or
1149 self.author_email or
1150 "UNKNOWN")
1152 def get_url(self):
1153 return self.url or "UNKNOWN"
1155 def get_license(self):
1156 return self.license or "UNKNOWN"
1157 get_licence = get_license
1159 def get_description(self):
1160 return self.description or "UNKNOWN"
1162 def get_long_description(self):
1163 return self.long_description or "UNKNOWN"
1165 def get_keywords(self):
1166 return self.keywords or []
1168 def get_platforms(self):
1169 return self.platforms or ["UNKNOWN"]
1171 def get_classifiers(self):
1172 return self.classifiers or []
1174 def get_download_url(self):
1175 return self.download_url or "UNKNOWN"
1177 # PEP 314
1179 def get_requires(self):
1180 return self.requires or []
1182 def set_requires(self, value):
1183 import distutils.versionpredicate
1184 for v in value:
1185 distutils.versionpredicate.VersionPredicate(v)
1186 self.requires = value
1188 def get_provides(self):
1189 return self.provides or []
1191 def set_provides(self, value):
1192 value = [v.strip() for v in value]
1193 for v in value:
1194 import distutils.versionpredicate
1195 distutils.versionpredicate.split_provision(v)
1196 self.provides = value
1198 def get_obsoletes(self):
1199 return self.obsoletes or []
1201 def set_obsoletes(self, value):
1202 import distutils.versionpredicate
1203 for v in value:
1204 distutils.versionpredicate.VersionPredicate(v)
1205 self.obsoletes = value
1207 # class DistributionMetadata
1210 def fix_help_options (options):
1211 """Convert a 4-tuple 'help_options' list as found in various command
1212 classes to the 3-tuple form required by FancyGetopt.
1214 new_options = []
1215 for help_tuple in options:
1216 new_options.append(help_tuple[0:3])
1217 return new_options
1220 if __name__ == "__main__":
1221 dist = Distribution()
1222 print "ok"