home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / DIST.PY < prev    next >
Encoding:
Python Source  |  2000-10-14  |  38.1 KB  |  969 lines

  1. """distutils.dist
  2.  
  3. Provides the Distribution class, which represents the module distribution
  4. being built/installed/distributed.
  5. """
  6.  
  7. # created 2000/04/03, Greg Ward
  8. # (extricated from core.py; actually dates back to the beginning)
  9.  
  10. __revision__ = "$Id: dist.py,v 1.41 2000/10/14 04:06:40 gward Exp $"
  11.  
  12. import sys, os, string, re
  13. from types import *
  14. from copy import copy
  15. from distutils.errors import *
  16. from distutils import sysconfig
  17. from distutils.fancy_getopt import FancyGetopt, translate_longopt
  18. from distutils.util import check_environ, strtobool
  19.  
  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.
  25. command_re = re.compile (r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
  26.  
  27.  
  28. class Distribution:
  29.     """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.
  32.  
  33.     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.     """
  41.  
  42.  
  43.     # 'global_options' describes the command-line options that may be
  44.     # supplied to the setup script prior to any actual commands.
  45.     # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of
  46.     # 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.
  50.     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"),
  54.                      ]
  55.  
  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,
  75.          "print the maintainer's name if known, else the author's"),
  76.         ('contact-email', None,
  77.          "print the maintainer's email address if known, else the author's"),
  78.         ('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"),
  86.         ('long-description', None,
  87.          "print the long package description"),
  88.         ]
  89.     display_option_names = map(lambda x: translate_longopt(x[0]),
  90.                                display_options)
  91.  
  92.     # negative options are options that exclude other options
  93.     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
  100.         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.         """
  108.  
  109.         # Default values for our command-line options
  110.         self.verbose = 1
  111.         self.dry_run = 0
  112.         self.help = 0
  113.         for attr in self.display_option_names:
  114.             setattr(self, attr, 0)
  115.  
  116.         # 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()
  122.         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))
  127.  
  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
  131.         # for the setup script to override command classes
  132.         self.cmdclass = {}
  133.  
  134.         # 'script_name' and 'script_args' are usually set to sys.argv[0]
  135.         # and sys.argv[1:], but they can be overridden when the caller is
  136.         # not necessarily a setup script run from the command-line.
  137.         self.script_name = None
  138.         self.script_args = None
  139.  
  140.         # 'command_options' is where we store command options between
  141.         # parsing them (from config files, the command-line, etc.) and when
  142.         # they are actually needed -- ie. when the command in question is
  143.         # instantiated.  It is a dictionary of dictionaries of 2-tuples:
  144.         #   command_options = { command_name : { option : (source, value) } }
  145.         self.command_options = {}
  146.  
  147.         # These options are really the business of various commands, rather
  148.         # than of the Distribution itself.  We provide aliases for them in
  149.         # Distribution as a convenience to the developer.
  150.         self.packages = None
  151.         self.package_dir = None
  152.         self.py_modules = None
  153.         self.libraries = None
  154.         self.headers = None
  155.         self.ext_modules = None
  156.         self.ext_package = None
  157.         self.include_dirs = None
  158.         self.extra_path = None
  159.         self.scripts = None
  160.         self.data_files = None
  161.  
  162.         # And now initialize bookkeeping stuff that can't be supplied by
  163.         # the caller at all.  'command_obj' maps command names to
  164.         # Command instances -- that's how we enforce that every command
  165.         # class is a singleton.
  166.         self.command_obj = {}
  167.  
  168.         # 'have_run' maps command names to boolean values; it keeps track
  169.         # of whether we have actually run a particular command, to make it
  170.         # cheap to "run" a command whenever we think we might need to -- if
  171.         # it's already been done, no need for expensive filesystem
  172.         # operations, we just check the 'have_run' dictionary and carry on.
  173.         # It's only safe to query 'have_run' for a command class that has
  174.         # been instantiated -- a false value will be inserted when the
  175.         # command object is created, and replaced with a true value when
  176.         # the command is successfully run.  Thus it's probably best to use
  177.         # '.get()' rather than a straight lookup.
  178.         self.have_run = {}
  179.  
  180.         # Now we'll use the attrs dictionary (ultimately, keyword args from
  181.         # the setup script) to possibly override any or all of these
  182.         # distribution options.
  183.  
  184.         if attrs:
  185.  
  186.             # Pull out the set of command options and work on them
  187.             # specifically.  Note that this order guarantees that aliased
  188.             # command options will override any supplied redundantly
  189.             # through the general options dictionary.
  190.             options = attrs.get('options')
  191.             if options:
  192.                 del attrs['options']
  193.                 for (command, cmd_options) in options.items():
  194.                     opt_dict = self.get_option_dict(command)
  195.                     for (opt, val) in cmd_options.items():
  196.                         opt_dict[opt] = ("setup script", val)
  197.  
  198.             # Now work on the rest of the attributes.  Any attribute that's
  199.             # not already defined is invalid!
  200.             for (key,val) in attrs.items():
  201.                 if hasattr(self.metadata, key):
  202.                     setattr(self.metadata, key, val)
  203.                 elif hasattr(self, key):
  204.                     setattr(self, key, val)
  205.                 else:
  206.                     raise DistutilsSetupError, \
  207.                           "invalid distribution option '%s'" % key
  208.  
  209.     # __init__ ()
  210.  
  211.  
  212.     def get_option_dict (self, command):
  213.         """Get the option dictionary for a given command.  If that
  214.         command's option dictionary hasn't been created yet, then create it
  215.         and return the new dictionary; otherwise, return the existing
  216.         option dictionary.
  217.         """
  218.  
  219.         dict = self.command_options.get(command)
  220.         if dict is None:
  221.             dict = self.command_options[command] = {}
  222.         return dict
  223.  
  224.  
  225.     def dump_option_dicts (self, header=None, commands=None, indent=""):
  226.         from pprint import pformat
  227.  
  228.         if commands is None:             # dump all command option dicts
  229.             commands = self.command_options.keys()
  230.             commands.sort()
  231.  
  232.         if header is not None:
  233.             print indent + header
  234.             indent = indent + "  "
  235.  
  236.         if not commands:
  237.             print indent + "no commands known yet"
  238.             return
  239.  
  240.         for cmd_name in commands:
  241.             opt_dict = self.command_options.get(cmd_name)
  242.             if opt_dict is None:
  243.                 print indent + "no option dict for '%s' command" % cmd_name
  244.             else:
  245.                 print indent + "option dict for '%s' command:" % cmd_name
  246.                 out = pformat(opt_dict)
  247.                 for line in string.split(out, "\n"):
  248.                     print indent + "  " + line
  249.  
  250.     # dump_option_dicts ()
  251.             
  252.  
  253.  
  254.     # -- Config file finding/parsing methods ---------------------------
  255.  
  256.     def find_config_files (self):
  257.         """Find as many configuration files as should be processed for this
  258.         platform, and return a list of filenames in the order in which they
  259.         should be parsed.  The filenames returned are guaranteed to exist
  260.         (modulo nasty race conditions).
  261.  
  262.         On Unix, there are three possible config files: pydistutils.cfg in
  263.         the Distutils installation directory (ie. where the top-level
  264.         Distutils __inst__.py file lives), .pydistutils.cfg in the user's
  265.         home directory, and setup.cfg in the current directory.
  266.  
  267.         On Windows and Mac OS, there are two possible config files:
  268.         pydistutils.cfg in the Python installation directory (sys.prefix)
  269.         and setup.cfg in the current directory.
  270.         """
  271.         files = []
  272.         check_environ()
  273.  
  274.         # Where to look for the system-wide Distutils config file
  275.         sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
  276.  
  277.         # Look for the system config file
  278.         sys_file = os.path.join(sys_dir, "distutils.cfg")
  279.         if os.path.isfile(sys_file):
  280.             files.append(sys_file)
  281.  
  282.         # What to call the per-user config file
  283.         if os.name == 'posix':
  284.             user_filename = ".pydistutils.cfg"
  285.         else:
  286.             user_filename = "pydistutils.cfg"
  287.  
  288.         # And look for the user config file
  289.         if os.environ.has_key('HOME'):
  290.             user_file = os.path.join(os.environ.get('HOME'), user_filename)
  291.             if os.path.isfile(user_file):
  292.                 files.append(user_file)
  293.  
  294.         # All platforms support local setup.cfg
  295.         local_file = "setup.cfg"
  296.         if os.path.isfile(local_file):
  297.             files.append(local_file)
  298.  
  299.         return files
  300.  
  301.     # find_config_files ()
  302.  
  303.  
  304.     def parse_config_files (self, filenames=None):
  305.  
  306.         from ConfigParser import ConfigParser
  307.         from distutils.core import DEBUG
  308.  
  309.         if filenames is None:
  310.             filenames = self.find_config_files()
  311.  
  312.         if DEBUG: print "Distribution.parse_config_files():"
  313.  
  314.         parser = ConfigParser()
  315.         for filename in filenames:
  316.             if DEBUG: print "  reading", filename
  317.             parser.read(filename)
  318.             for section in parser.sections():
  319.                 options = parser.options(section)
  320.                 opt_dict = self.get_option_dict(section)
  321.  
  322.                 for opt in options:
  323.                     if opt != '__name__':
  324.                         val = parser.get(section,opt)
  325.                         opt = string.replace(opt, '-', '_')
  326.                         opt_dict[opt] = (filename, val)
  327.  
  328.             # Make the ConfigParser forget everything (so we retain
  329.             # the original filenames that options come from) -- gag,
  330.             # retch, puke -- another good reason for a distutils-
  331.             # specific config parser (sigh...)
  332.             parser.__init__()
  333.  
  334.         # If there was a "global" section in the config file, use it
  335.         # to set Distribution options.
  336.  
  337.         if self.command_options.has_key('global'):
  338.             for (opt, (src, val)) in self.command_options['global'].items():
  339.                 alias = self.negative_opt.get(opt)
  340.                 try:
  341.                     if alias:
  342.                         setattr(self, alias, not strtobool(val))
  343.                     elif opt in ('verbose', 'dry_run'): # ugh!
  344.                         setattr(self, opt, strtobool(val))
  345.                 except ValueError, msg:
  346.                     raise DistutilsOptionError, msg
  347.  
  348.     # parse_config_files ()
  349.  
  350.  
  351.     # -- Command-line parsing methods ----------------------------------
  352.  
  353.     def parse_command_line (self):
  354.         """Parse the setup script's command line, taken from the
  355.         'script_args' instance attribute (which defaults to 'sys.argv[1:]'
  356.         -- see 'setup()' in core.py).  This list is first processed for
  357.         "global options" -- options that set attributes of the Distribution
  358.         instance.  Then, it is alternately scanned for Distutils commands
  359.         and options for that command.  Each new command terminates the
  360.         options for the previous command.  The allowed options for a
  361.         command are determined by the 'user_options' attribute of the
  362.         command class -- thus, we have to be able to load command classes
  363.         in order to parse the command line.  Any error in that 'options'
  364.         attribute raises DistutilsGetoptError; any error on the
  365.         command-line raises DistutilsArgError.  If no Distutils commands
  366.         were found on the command line, raises DistutilsArgError.  Return
  367.         true if command-line was successfully parsed and we should carry
  368.         on with executing commands; false if no errors but we shouldn't
  369.         execute commands (currently, this only happens if user asks for
  370.         help).
  371.         """
  372.         # We have to parse the command line a bit at a time -- global
  373.         # options, then the first command, then its options, and so on --
  374.         # because each command will be handled by a different class, and
  375.         # the options that are valid for a particular class aren't known
  376.         # until we have loaded the command class, which doesn't happen
  377.         # until we know what the command is.
  378.  
  379.         self.commands = []
  380.         parser = FancyGetopt(self.global_options + self.display_options)
  381.         parser.set_negative_aliases(self.negative_opt)
  382.         parser.set_aliases({'license': 'licence'})
  383.         args = parser.getopt(args=self.script_args, object=self)
  384.         option_order = parser.get_option_order()
  385.  
  386.         # for display options we return immediately
  387.         if self.handle_display_options(option_order):
  388.             return
  389.             
  390.         while args:
  391.             args = self._parse_command_opts(parser, args)
  392.             if args is None:            # user asked for help (and got it)
  393.                 return
  394.  
  395.         # Handle the cases of --help as a "global" option, ie.
  396.         # "setup.py --help" and "setup.py --help command ...".  For the
  397.         # former, we show global options (--verbose, --dry-run, etc.)
  398.         # and display-only options (--name, --version, etc.); for the
  399.         # latter, we omit the display-only options and show help for
  400.         # each command listed on the command line.
  401.         if self.help:
  402.             self._show_help(parser,
  403.                             display_options=len(self.commands) == 0,
  404.                             commands=self.commands)
  405.             return
  406.  
  407.         # Oops, no commands found -- an end-user error
  408.         if not self.commands:
  409.             raise DistutilsArgError, "no commands supplied"
  410.  
  411.         # All is well: return true
  412.         return 1
  413.  
  414.     # parse_command_line()
  415.  
  416.     def _parse_command_opts (self, parser, args):
  417.         """Parse the command-line options for a single command.
  418.         'parser' must be a FancyGetopt instance; 'args' must be the list
  419.         of arguments, starting with the current command (whose options
  420.         we are about to parse).  Returns a new version of 'args' with
  421.         the next command at the front of the list; will be the empty
  422.         list if there are no more commands on the command line.  Returns
  423.         None if the user asked for help on this command.
  424.         """
  425.         # late import because of mutual dependence between these modules
  426.         from distutils.cmd import Command
  427.  
  428.         # Pull the current command from the head of the command line
  429.         command = args[0]
  430.         if not command_re.match(command):
  431.             raise SystemExit, "invalid command name '%s'" % command
  432.         self.commands.append(command)
  433.  
  434.         # Dig up the command class that implements this command, so we
  435.         # 1) know that it's a valid command, and 2) know which options
  436.         # it takes.
  437.         try:
  438.             cmd_class = self.get_command_class(command)
  439.         except DistutilsModuleError, msg:
  440.             raise DistutilsArgError, msg
  441.  
  442.         # Require that the command class be derived from Command -- want
  443.         # to be sure that the basic "command" interface is implemented.
  444.         if not issubclass(cmd_class, Command):
  445.             raise DistutilsClassError, \
  446.                   "command class %s must subclass Command" % cmd_class
  447.  
  448.         # Also make sure that the command object provides a list of its
  449.         # known options.
  450.         if not (hasattr(cmd_class, 'user_options') and
  451.                 type(cmd_class.user_options) is ListType):
  452.             raise DistutilsClassError, \
  453.                   ("command class %s must provide " +
  454.                    "'user_options' attribute (a list of tuples)") % \
  455.                   cmd_class
  456.  
  457.         # If the command class has a list of negative alias options,
  458.         # merge it in with the global negative aliases.
  459.         negative_opt = self.negative_opt
  460.         if hasattr(cmd_class, 'negative_opt'):
  461.             negative_opt = copy(negative_opt)
  462.             negative_opt.update(cmd_class.negative_opt)
  463.  
  464.         # Check for help_options in command class.  They have a different
  465.         # format (tuple of four) so we need to preprocess them here.
  466.         if (hasattr(cmd_class, 'help_options') and
  467.             type(cmd_class.help_options) is ListType):
  468.             help_options = fix_help_options(cmd_class.help_options)
  469.         else:
  470.             help_options = []
  471.  
  472.  
  473.         # All commands support the global options too, just by adding
  474.         # in 'global_options'.
  475.         parser.set_option_table(self.global_options +
  476.                                 cmd_class.user_options +
  477.                                 help_options)
  478.         parser.set_negative_aliases(negative_opt)
  479.         (args, opts) = parser.getopt(args[1:])
  480.         if hasattr(opts, 'help') and opts.help:
  481.             self._show_help(parser, display_options=0, commands=[cmd_class])
  482.             return
  483.  
  484.         if (hasattr(cmd_class, 'help_options') and
  485.             type(cmd_class.help_options) is ListType):
  486.             help_option_found=0
  487.             for (help_option, short, desc, func) in cmd_class.help_options:
  488.                 if hasattr(opts, parser.get_attr_name(help_option)):
  489.                     help_option_found=1
  490.                     #print "showing help for option %s of command %s" % \
  491.                     #      (help_option[0],cmd_class)
  492.  
  493.                     if callable(func):
  494.                         func()
  495.                     else:
  496.                         raise DistutilsClassError, \
  497.                             ("invalid help function %s for help option '%s': "
  498.                              "must be a callable object (function, etc.)") % \
  499.                             (`func`, help_option)
  500.  
  501.             if help_option_found: 
  502.                 return
  503.  
  504.         # Put the options from the command-line into their official
  505.         # holding pen, the 'command_options' dictionary.
  506.         opt_dict = self.get_option_dict(command)
  507.         for (name, value) in vars(opts).items():
  508.             opt_dict[name] = ("command line", value)
  509.  
  510.         return args
  511.  
  512.     # _parse_command_opts ()
  513.  
  514.  
  515.     def _show_help (self,
  516.                     parser,
  517.                     global_options=1,
  518.                     display_options=1,
  519.                     commands=[]):
  520.         """Show help for the setup script command-line in the form of
  521.         several lists of command-line options.  'parser' should be a
  522.         FancyGetopt instance; do not expect it to be returned in the
  523.         same state, as its option table will be reset to make it
  524.         generate the correct help text.
  525.  
  526.         If 'global_options' is true, lists the global options:
  527.         --verbose, --dry-run, etc.  If 'display_options' is true, lists
  528.         the "display-only" options: --name, --version, etc.  Finally,
  529.         lists per-command help for every command name or command class
  530.         in 'commands'.
  531.         """
  532.         # late import because of mutual dependence between these modules
  533.         from distutils.core import gen_usage
  534.         from distutils.cmd import Command
  535.  
  536.         if global_options:
  537.             parser.set_option_table(self.global_options)
  538.             parser.print_help("Global options:")
  539.             print
  540.  
  541.         if display_options:
  542.             parser.set_option_table(self.display_options)
  543.             parser.print_help(
  544.                 "Information display options (just display " +
  545.                 "information, ignore any commands)")
  546.             print
  547.  
  548.         for command in self.commands:
  549.             if type(command) is ClassType and issubclass(klass, Command):
  550.                 klass = command
  551.             else:
  552.                 klass = self.get_command_class(command)
  553.             if (hasattr(klass, 'help_options') and
  554.                 type(klass.help_options) is ListType):
  555.                 parser.set_option_table(klass.user_options +
  556.                                         fix_help_options(klass.help_options))
  557.             else:
  558.                 parser.set_option_table(klass.user_options)
  559.             parser.print_help("Options for '%s' command:" % klass.__name__)
  560.             print
  561.  
  562.         print gen_usage(self.script_name)
  563.         return
  564.  
  565.     # _show_help ()
  566.  
  567.  
  568.     def handle_display_options (self, option_order):
  569.         """If there were any non-global "display-only" options
  570.         (--help-commands or the metadata display options) on the command
  571.         line, display the requested info and return true; else return
  572.         false.
  573.         """
  574.         from distutils.core import gen_usage
  575.  
  576.         # User just wants a list of commands -- we'll print it out and stop
  577.         # processing now (ie. if they ran "setup --help-commands foo bar",
  578.         # we ignore "foo bar").
  579.         if self.help_commands:
  580.             self.print_commands()
  581.             print
  582.             print gen_usage(self.script_name)
  583.             return 1
  584.  
  585.         # If user supplied any of the "display metadata" options, then
  586.         # display that metadata in the order in which the user supplied the
  587.         # metadata options.
  588.         any_display_options = 0
  589.         is_display_option = {}
  590.         for option in self.display_options:
  591.             is_display_option[option[0]] = 1
  592.  
  593.         for (opt, val) in option_order:
  594.             if val and is_display_option.get(opt):
  595.                 opt = translate_longopt(opt)
  596.                 print getattr(self.metadata, "get_"+opt)()
  597.                 any_display_options = 1
  598.  
  599.         return any_display_options
  600.  
  601.     # handle_display_options()
  602.  
  603.     def print_command_list (self, commands, header, max_length):
  604.         """Print a subset of the list of all commands -- used by
  605.         'print_commands()'.
  606.         """
  607.  
  608.         print header + ":"
  609.  
  610.         for cmd in commands:
  611.             klass = self.cmdclass.get(cmd)
  612.             if not klass:
  613.                 klass = self.get_command_class(cmd)
  614.             try:
  615.                 description = klass.description
  616.             except AttributeError:
  617.                 description = "(no description available)"
  618.  
  619.             print "  %-*s  %s" % (max_length, cmd, description)
  620.  
  621.     # print_command_list ()
  622.  
  623.  
  624.     def print_commands (self):
  625.         """Print out a help message listing all available commands with a
  626.         description of each.  The list is divided into "standard commands"
  627.         (listed in distutils.command.__all__) and "extra commands"
  628.         (mentioned in self.cmdclass, but not a standard command).  The
  629.         descriptions come from the command class attribute
  630.         'description'.
  631.         """
  632.  
  633.         import distutils.command
  634.         std_commands = distutils.command.__all__
  635.         is_std = {}
  636.         for cmd in std_commands:
  637.             is_std[cmd] = 1
  638.  
  639.         extra_commands = []
  640.         for cmd in self.cmdclass.keys():
  641.             if not is_std.get(cmd):
  642.                 extra_commands.append(cmd)
  643.  
  644.         max_length = 0
  645.         for cmd in (std_commands + extra_commands):
  646.             if len(cmd) > max_length:
  647.                 max_length = len(cmd)
  648.  
  649.         self.print_command_list(std_commands,
  650.                                 "Standard commands",
  651.                                 max_length)
  652.         if extra_commands:
  653.             print
  654.             self.print_command_list(extra_commands,
  655.                                     "Extra commands",
  656.                                     max_length)
  657.  
  658.     # print_commands ()
  659.  
  660.  
  661.     # -- Command class/object methods ----------------------------------
  662.  
  663.     def get_command_class (self, command):
  664.         """Return the class that implements the Distutils command named by
  665.         'command'.  First we check the 'cmdclass' dictionary; if the
  666.         command is mentioned there, we fetch the class object from the
  667.         dictionary and return it.  Otherwise we load the command module
  668.         ("distutils.command." + command) and fetch the command class from
  669.         the module.  The loaded class is also stored in 'cmdclass'
  670.         to speed future calls to 'get_command_class()'.
  671.  
  672.         Raises DistutilsModuleError if the expected module could not be
  673.         found, or if that module does not define the expected class.
  674.         """
  675.         klass = self.cmdclass.get(command)
  676.         if klass:
  677.             return klass
  678.  
  679.         module_name = 'distutils.command.' + command
  680.         klass_name = command
  681.  
  682.         try:
  683.             __import__ (module_name)
  684.             module = sys.modules[module_name]
  685.         except ImportError:
  686.             raise DistutilsModuleError, \
  687.                   "invalid command '%s' (no module named '%s')" % \
  688.                   (command, module_name)
  689.  
  690.         try:
  691.             klass = getattr(module, klass_name)
  692.         except AttributeError:
  693.             raise DistutilsModuleError, \
  694.                   "invalid command '%s' (no class '%s' in module '%s')" \
  695.                   % (command, klass_name, module_name)
  696.  
  697.         self.cmdclass[command] = klass
  698.         return klass
  699.  
  700.     # get_command_class ()
  701.  
  702.     def get_command_obj (self, command, create=1):
  703.         """Return the command object for 'command'.  Normally this object
  704.         is cached on a previous call to 'get_command_obj()'; if no command
  705.         object for 'command' is in the cache, then we either create and
  706.         return it (if 'create' is true) or return None.
  707.         """
  708.         from distutils.core import DEBUG
  709.         cmd_obj = self.command_obj.get(command)
  710.         if not cmd_obj and create:
  711.             if DEBUG:
  712.                 print "Distribution.get_command_obj(): " \
  713.                       "creating '%s' command object" % command
  714.  
  715.             klass = self.get_command_class(command)
  716.             cmd_obj = self.command_obj[command] = klass(self)
  717.             self.have_run[command] = 0
  718.  
  719.             # Set any options that were supplied in config files
  720.             # or on the command line.  (NB. support for error
  721.             # reporting is lame here: any errors aren't reported
  722.             # until 'finalize_options()' is called, which means
  723.             # we won't report the source of the error.)
  724.             options = self.command_options.get(command)
  725.             if options:
  726.                 self._set_command_options(cmd_obj, options)
  727.  
  728.         return cmd_obj
  729.  
  730.     def _set_command_options (self, command_obj, option_dict=None):
  731.         """Set the options for 'command_obj' from 'option_dict'.  Basically
  732.         this means copying elements of a dictionary ('option_dict') to
  733.         attributes of an instance ('command').
  734.  
  735.         'command_obj' must be a Command instance.  If 'option_dict' is not
  736.         supplied, uses the standard option dictionary for this command
  737.         (from 'self.command_options').
  738.         """
  739.         from distutils.core import DEBUG
  740.         
  741.         command_name = command_obj.get_command_name()
  742.         if option_dict is None:
  743.             option_dict = self.get_option_dict(command_name)
  744.  
  745.         if DEBUG: print "  setting options for '%s' command:" % command_name
  746.         for (option, (source, value)) in option_dict.items():
  747.             if DEBUG: print "    %s = %s (from %s)" % (option, value, source)
  748.             try:
  749.                 bool_opts = map(translate_longopt, command_obj.boolean_options)
  750.             except AttributeError:
  751.                 bool_opts = []
  752.             try:
  753.                 neg_opt = command_obj.negative_opt
  754.             except AttributeError:
  755.                 neg_opt = {}
  756.  
  757.             try:
  758.                 is_string = type(value) is StringType
  759.                 if neg_opt.has_key(option) and is_string:
  760.                     setattr(command_obj, neg_opt[option], not strtobool(value))
  761.                 elif option in bool_opts and is_string:
  762.                     setattr(command_obj, option, strtobool(value))
  763.                 elif hasattr(command_obj, option):
  764.                     setattr(command_obj, option, value)
  765.                 else:
  766.                     raise DistutilsOptionError, \
  767.                           ("error in %s: command '%s' has no such option '%s'"
  768.                            % (source, command_name, option))
  769.             except ValueError, msg:
  770.                 raise DistutilsOptionError, msg
  771.  
  772.     def reinitialize_command (self, command, reinit_subcommands=0):
  773.         """Reinitializes a command to the state it was in when first
  774.         returned by 'get_command_obj()': ie., initialized but not yet
  775.         finalized.  This provides the opportunity to sneak option
  776.         values in programmatically, overriding or supplementing
  777.         user-supplied values from the config files and command line.
  778.         You'll have to re-finalize the command object (by calling
  779.         'finalize_options()' or 'ensure_finalized()') before using it for
  780.         real.  
  781.  
  782.         'command' should be a command name (string) or command object.  If
  783.         'reinit_subcommands' is true, also reinitializes the command's
  784.         sub-commands, as declared by the 'sub_commands' class attribute (if
  785.         it has one).  See the "install" command for an example.  Only
  786.         reinitializes the sub-commands that actually matter, ie. those
  787.         whose test predicates return true.
  788.  
  789.         Returns the reinitialized command object.
  790.         """
  791.         from distutils.cmd import Command
  792.         if not isinstance(command, Command):
  793.             command_name = command
  794.             command = self.get_command_obj(command_name)
  795.         else:
  796.             command_name = command.get_command_name()
  797.  
  798.         if not command.finalized:
  799.             return command
  800.         command.initialize_options()
  801.         command.finalized = 0
  802.         self.have_run[command_name] = 0
  803.         self._set_command_options(command)
  804.  
  805.         if reinit_subcommands:
  806.             for sub in command.get_sub_commands():
  807.                 self.reinitialize_command(sub, reinit_subcommands)            
  808.  
  809.         return command
  810.  
  811.         
  812.     # -- Methods that operate on the Distribution ----------------------
  813.  
  814.     def announce (self, msg, level=1):
  815.         """Print 'msg' if 'level' is greater than or equal to the verbosity
  816.         level recorded in the 'verbose' attribute (which, currently, can be
  817.         only 0 or 1).
  818.         """
  819.         if self.verbose >= level:
  820.             print msg
  821.  
  822.  
  823.     def run_commands (self):
  824.         """Run each command that was seen on the setup script command line.
  825.         Uses the list of commands found and cache of command objects
  826.         created by 'get_command_obj()'.
  827.         """
  828.         for cmd in self.commands:
  829.             self.run_command(cmd)
  830.  
  831.  
  832.     # -- Methods that operate on its Commands --------------------------
  833.  
  834.     def run_command (self, command):
  835.         """Do whatever it takes to run a command (including nothing at all,
  836.         if the command has already been run).  Specifically: if we have
  837.         already created and run the command named by 'command', return
  838.         silently without doing anything.  If the command named by 'command'
  839.         doesn't even have a command object yet, create one.  Then invoke
  840.         'run()' on that command object (or an existing one).
  841.         """
  842.         # Already been here, done that? then return silently.
  843.         if self.have_run.get(command):
  844.             return
  845.  
  846.         self.announce("running " + command)
  847.         cmd_obj = self.get_command_obj(command)
  848.         cmd_obj.ensure_finalized()
  849.         cmd_obj.run()
  850.         self.have_run[command] = 1
  851.  
  852.  
  853.     # -- Distribution query methods ------------------------------------
  854.  
  855.     def has_pure_modules (self):
  856.         return len(self.packages or self.py_modules or []) > 0
  857.  
  858.     def has_ext_modules (self):
  859.         return self.ext_modules and len(self.ext_modules) > 0
  860.  
  861.     def has_c_libraries (self):
  862.         return self.libraries and len(self.libraries) > 0
  863.  
  864.     def has_modules (self):
  865.         return self.has_pure_modules() or self.has_ext_modules()
  866.  
  867.     def has_headers (self):
  868.         return self.headers and len(self.headers) > 0
  869.  
  870.     def has_scripts (self):
  871.         return self.scripts and len(self.scripts) > 0
  872.  
  873.     def has_data_files (self):
  874.         return self.data_files and len(self.data_files) > 0
  875.  
  876.     def is_pure (self):
  877.         return (self.has_pure_modules() and
  878.                 not self.has_ext_modules() and
  879.                 not self.has_c_libraries())
  880.  
  881.     # -- Metadata query methods ----------------------------------------
  882.  
  883.     # If you're looking for 'get_name()', 'get_version()', and so forth,
  884.     # they are defined in a sneaky way: the constructor binds self.get_XXX
  885.     # to self.metadata.get_XXX.  The actual code is in the
  886.     # DistributionMetadata class, below.
  887.  
  888. # class Distribution
  889.  
  890.  
  891. class DistributionMetadata:
  892.     """Dummy class to hold the distribution meta-data: name, version,
  893.     author, and so forth.
  894.     """
  895.  
  896.     def __init__ (self):
  897.         self.name = None
  898.         self.version = None
  899.         self.author = None
  900.         self.author_email = None
  901.         self.maintainer = None
  902.         self.maintainer_email = None
  903.         self.url = None
  904.         self.licence = None
  905.         self.description = None
  906.         self.long_description = None
  907.         
  908.     # -- Metadata query methods ----------------------------------------
  909.  
  910.     def get_name (self):
  911.         return self.name or "UNKNOWN"
  912.  
  913.     def get_version(self):
  914.         return self.version or "???"
  915.  
  916.     def get_fullname (self):
  917.         return "%s-%s" % (self.get_name(), self.get_version())
  918.  
  919.     def get_author(self):
  920.         return self.author or "UNKNOWN"
  921.  
  922.     def get_author_email(self):
  923.         return self.author_email or "UNKNOWN"
  924.  
  925.     def get_maintainer(self):
  926.         return self.maintainer or "UNKNOWN"
  927.  
  928.     def get_maintainer_email(self):
  929.         return self.maintainer_email or "UNKNOWN"
  930.  
  931.     def get_contact(self):
  932.         return (self.maintainer or
  933.                 self.author or
  934.                 "UNKNOWN")
  935.  
  936.     def get_contact_email(self):
  937.         return (self.maintainer_email or
  938.                 self.author_email or
  939.                 "UNKNOWN")
  940.  
  941.     def get_url(self):
  942.         return self.url or "UNKNOWN"
  943.  
  944.     def get_licence(self):
  945.         return self.licence or "UNKNOWN"
  946.  
  947.     def get_description(self):
  948.         return self.description or "UNKNOWN"
  949.  
  950.     def get_long_description(self):
  951.         return self.long_description or "UNKNOWN"
  952.  
  953. # class DistributionMetadata
  954.  
  955.  
  956. def fix_help_options (options):
  957.     """Convert a 4-tuple 'help_options' list as found in various command
  958.     classes to the 3-tuple form required by FancyGetopt.
  959.     """
  960.     new_options = []
  961.     for help_tuple in options:
  962.         new_options.append(help_tuple[0:3])
  963.     return new_options
  964.  
  965.  
  966. if __name__ == "__main__":
  967.     dist = Distribution()
  968.     print "ok"
  969.