home *** CD-ROM | disk | FTP | other *** search
/ Freelog Special Freeware 31 / FreelogHS31.iso / Texte / scribus / scribus-1.3.3.9-win32-install.exe / lib / optparse.py < prev    next >
Text File  |  2004-11-03  |  58KB  |  1,568 lines

  1. """optparse - a powerful, extensible, and easy-to-use option parser.
  2.  
  3. By Greg Ward <gward@python.net>
  4.  
  5. Originally distributed as Optik; see http://optik.sourceforge.net/ .
  6.  
  7. If you have problems with this module, please do not file bugs,
  8. patches, or feature requests with Python; instead, use Optik's
  9. SourceForge project page:
  10.   http://sourceforge.net/projects/optik
  11.  
  12. For support, use the optik-users@lists.sourceforge.net mailing list
  13. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  14. """
  15.  
  16. # Python developers: please do not make changes to this file, since
  17. # it is automatically generated from the Optik source code.
  18.  
  19. __version__ = "1.5a2"
  20.  
  21. __all__ = ['Option',
  22.            'SUPPRESS_HELP',
  23.            'SUPPRESS_USAGE',
  24.            'Values',
  25.            'OptionContainer',
  26.            'OptionGroup',
  27.            'OptionParser',
  28.            'HelpFormatter',
  29.            'IndentedHelpFormatter',
  30.            'TitledHelpFormatter',
  31.            'OptParseError',
  32.            'OptionError',
  33.            'OptionConflictError',
  34.            'OptionValueError',
  35.            'BadOptionError']
  36.  
  37. __copyright__ = """
  38. Copyright (c) 2001-2004 Gregory P. Ward.  All rights reserved.
  39. Copyright (c) 2002-2004 Python Software Foundation.  All rights reserved.
  40.  
  41. Redistribution and use in source and binary forms, with or without
  42. modification, are permitted provided that the following conditions are
  43. met:
  44.  
  45.   * Redistributions of source code must retain the above copyright
  46.     notice, this list of conditions and the following disclaimer.
  47.  
  48.   * Redistributions in binary form must reproduce the above copyright
  49.     notice, this list of conditions and the following disclaimer in the
  50.     documentation and/or other materials provided with the distribution.
  51.  
  52.   * Neither the name of the author nor the names of its
  53.     contributors may be used to endorse or promote products derived from
  54.     this software without specific prior written permission.
  55.  
  56. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  57. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  58. TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  59. PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
  60. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  61. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  62. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  63. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  64. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  65. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  66. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  67. """
  68.  
  69. import sys, os
  70. import types
  71. import textwrap
  72. from gettext import gettext as _
  73.  
  74. def _repr(self):
  75.     return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
  76.  
  77.  
  78. # This file was generated from:
  79. #   Id: option_parser.py 421 2004-10-26 00:45:16Z greg
  80. #   Id: option.py 422 2004-10-26 00:53:47Z greg
  81. #   Id: help.py 367 2004-07-24 23:21:21Z gward
  82. #   Id: errors.py 367 2004-07-24 23:21:21Z gward
  83.  
  84. class OptParseError (Exception):
  85.     def __init__(self, msg):
  86.         self.msg = msg
  87.  
  88.     def __str__(self):
  89.         return self.msg
  90.  
  91.  
  92. class OptionError (OptParseError):
  93.     """
  94.     Raised if an Option instance is created with invalid or
  95.     inconsistent arguments.
  96.     """
  97.  
  98.     def __init__(self, msg, option):
  99.         self.msg = msg
  100.         self.option_id = str(option)
  101.  
  102.     def __str__(self):
  103.         if self.option_id:
  104.             return "option %s: %s" % (self.option_id, self.msg)
  105.         else:
  106.             return self.msg
  107.  
  108. class OptionConflictError (OptionError):
  109.     """
  110.     Raised if conflicting options are added to an OptionParser.
  111.     """
  112.  
  113. class OptionValueError (OptParseError):
  114.     """
  115.     Raised if an invalid option value is encountered on the command
  116.     line.
  117.     """
  118.  
  119. class BadOptionError (OptParseError):
  120.     """
  121.     Raised if an invalid or ambiguous option is seen on the command-line.
  122.     """
  123.  
  124.  
  125. class HelpFormatter:
  126.  
  127.     """
  128.     Abstract base class for formatting option help.  OptionParser
  129.     instances should use one of the HelpFormatter subclasses for
  130.     formatting help; by default IndentedHelpFormatter is used.
  131.  
  132.     Instance attributes:
  133.       parser : OptionParser
  134.         the controlling OptionParser instance
  135.       indent_increment : int
  136.         the number of columns to indent per nesting level
  137.       max_help_position : int
  138.         the maximum starting column for option help text
  139.       help_position : int
  140.         the calculated starting column for option help text;
  141.         initially the same as the maximum
  142.       width : int
  143.         total number of columns for output (pass None to constructor for
  144.         this value to be taken from the $COLUMNS environment variable)
  145.       level : int
  146.         current indentation level
  147.       current_indent : int
  148.         current indentation level (in columns)
  149.       help_width : int
  150.         number of columns available for option help text (calculated)
  151.       default_tag : str
  152.         text to replace with each option's default value, "%default"
  153.         by default.  Set to false value to disable default value expansion.
  154.       option_strings : { Option : str }
  155.         maps Option instances to the snippet of help text explaining
  156.         the syntax of that option, e.g. "-h, --help" or
  157.         "-fFILE, --file=FILE"
  158.       _short_opt_fmt : str
  159.         format string controlling how short options with values are
  160.         printed in help text.  Must be either "%s%s" ("-fFILE") or
  161.         "%s %s" ("-f FILE"), because those are the two syntaxes that
  162.         Optik supports.
  163.       _long_opt_fmt : str
  164.         similar but for long options; must be either "%s %s" ("--file FILE")
  165.         or "%s=%s" ("--file=FILE").
  166.     """
  167.  
  168.     NO_DEFAULT_VALUE = "none"
  169.  
  170.     def __init__(self,
  171.                  indent_increment,
  172.                  max_help_position,
  173.                  width,
  174.                  short_first):
  175.         self.parser = None
  176.         self.indent_increment = indent_increment
  177.         self.help_position = self.max_help_position = max_help_position
  178.         if width is None:
  179.             try:
  180.                 width = int(os.environ['COLUMNS'])
  181.             except (KeyError, ValueError):
  182.                 width = 80
  183.             width -= 2
  184.         self.width = width
  185.         self.current_indent = 0
  186.         self.level = 0
  187.         self.help_width = None          # computed later
  188.         self.short_first = short_first
  189.         self.default_tag = "%default"
  190.         self.option_strings = {}
  191.         self._short_opt_fmt = "%s %s"
  192.         self._long_opt_fmt = "%s=%s"
  193.  
  194.     def set_parser(self, parser):
  195.         self.parser = parser
  196.  
  197.     def set_short_opt_delimiter(self, delim):
  198.         if delim not in ("", " "):
  199.             raise ValueError(
  200.                 "invalid metavar delimiter for short options: %r" % delim)
  201.         self._short_opt_fmt = "%s" + delim + "%s"
  202.  
  203.     def set_long_opt_delimiter(self, delim):
  204.         if delim not in ("=", " "):
  205.             raise ValueError(
  206.                 "invalid metavar delimiter for long options: %r" % delim)
  207.         self._long_opt_fmt = "%s" + delim + "%s"
  208.  
  209.     def indent(self):
  210.         self.current_indent += self.indent_increment
  211.         self.level += 1
  212.  
  213.     def dedent(self):
  214.         self.current_indent -= self.indent_increment
  215.         assert self.current_indent >= 0, "Indent decreased below 0."
  216.         self.level -= 1
  217.  
  218.     def format_usage(self, usage):
  219.         raise NotImplementedError, "subclasses must implement"
  220.  
  221.     def format_heading(self, heading):
  222.         raise NotImplementedError, "subclasses must implement"
  223.  
  224.     def format_description(self, description):
  225.         if not description:
  226.             return ""
  227.         desc_width = self.width - self.current_indent
  228.         indent = " "*self.current_indent
  229.         return textwrap.fill(description,
  230.                              desc_width,
  231.                              initial_indent=indent,
  232.                              subsequent_indent=indent) + "\n"
  233.  
  234.     def expand_default(self, option):
  235.         if self.parser is None or not self.default_tag:
  236.             return option.help
  237.  
  238.         default_value = self.parser.defaults.get(option.dest)
  239.         if default_value is NO_DEFAULT or default_value is None:
  240.             default_value = self.NO_DEFAULT_VALUE
  241.  
  242.         return option.help.replace(self.default_tag, str(default_value))
  243.  
  244.     def format_option(self, option):
  245.         # The help for each option consists of two parts:
  246.         #   * the opt strings and metavars
  247.         #     eg. ("-x", or "-fFILENAME, --file=FILENAME")
  248.         #   * the user-supplied help string
  249.         #     eg. ("turn on expert mode", "read data from FILENAME")
  250.         #
  251.         # If possible, we write both of these on the same line:
  252.         #   -x      turn on expert mode
  253.         #
  254.         # But if the opt string list is too long, we put the help
  255.         # string on a second line, indented to the same column it would
  256.         # start in if it fit on the first line.
  257.         #   -fFILENAME, --file=FILENAME
  258.         #           read data from FILENAME
  259.         result = []
  260.         opts = self.option_strings[option]
  261.         opt_width = self.help_position - self.current_indent - 2
  262.         if len(opts) > opt_width:
  263.             opts = "%*s%s\n" % (self.current_indent, "", opts)
  264.             indent_first = self.help_position
  265.         else:                       # start help on same line as opts
  266.             opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
  267.             indent_first = 0
  268.         result.append(opts)
  269.         if option.help:
  270.             help_text = self.expand_default(option)
  271.             help_lines = textwrap.wrap(help_text, self.help_width)
  272.             result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
  273.             result.extend(["%*s%s\n" % (self.help_position, "", line)
  274.                            for line in help_lines[1:]])
  275.         elif opts[-1] != "\n":
  276.             result.append("\n")
  277.         return "".join(result)
  278.  
  279.     def store_option_strings(self, parser):
  280.         self.indent()
  281.         max_len = 0
  282.         for opt in parser.option_list:
  283.             strings = self.format_option_strings(opt)
  284.             self.option_strings[opt] = strings
  285.             max_len = max(max_len, len(strings) + self.current_indent)
  286.         self.indent()
  287.         for group in parser.option_groups:
  288.             for opt in group.option_list:
  289.                 strings = self.format_option_strings(opt)
  290.                 self.option_strings[opt] = strings
  291.                 max_len = max(max_len, len(strings) + self.current_indent)
  292.         self.dedent()
  293.         self.dedent()
  294.         self.help_position = min(max_len + 2, self.max_help_position)
  295.         self.help_width = self.width - self.help_position
  296.  
  297.     def format_option_strings(self, option):
  298.         """Return a comma-separated list of option strings & metavariables."""
  299.         if option.takes_value():
  300.             metavar = option.metavar or option.dest.upper()
  301.             short_opts = [self._short_opt_fmt % (sopt, metavar)
  302.                           for sopt in option._short_opts]
  303.             long_opts = [self._long_opt_fmt % (lopt, metavar)
  304.                          for lopt in option._long_opts]
  305.         else:
  306.             short_opts = option._short_opts
  307.             long_opts = option._long_opts
  308.  
  309.         if self.short_first:
  310.             opts = short_opts + long_opts
  311.         else:
  312.             opts = long_opts + short_opts
  313.  
  314.         return ", ".join(opts)
  315.  
  316. class IndentedHelpFormatter (HelpFormatter):
  317.     """Format help with indented section bodies.
  318.     """
  319.  
  320.     def __init__(self,
  321.                  indent_increment=2,
  322.                  max_help_position=24,
  323.                  width=None,
  324.                  short_first=1):
  325.         HelpFormatter.__init__(
  326.             self, indent_increment, max_help_position, width, short_first)
  327.  
  328.     def format_usage(self, usage):
  329.         return _("usage: %s\n") % usage
  330.  
  331.     def format_heading(self, heading):
  332.         return "%*s%s:\n" % (self.current_indent, "", heading)
  333.  
  334.  
  335. class TitledHelpFormatter (HelpFormatter):
  336.     """Format help with underlined section headers.
  337.     """
  338.  
  339.     def __init__(self,
  340.                  indent_increment=0,
  341.                  max_help_position=24,
  342.                  width=None,
  343.                  short_first=0):
  344.         HelpFormatter.__init__ (
  345.             self, indent_increment, max_help_position, width, short_first)
  346.  
  347.     def format_usage(self, usage):
  348.         return "%s  %s\n" % (self.format_heading(_("Usage")), usage)
  349.  
  350.     def format_heading(self, heading):
  351.         return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
  352.  
  353.  
  354. _builtin_cvt = { "int" : (int, _("integer")),
  355.                  "long" : (long, _("long integer")),
  356.                  "float" : (float, _("floating-point")),
  357.                  "complex" : (complex, _("complex")) }
  358.  
  359. def check_builtin(option, opt, value):
  360.     (cvt, what) = _builtin_cvt[option.type]
  361.     try:
  362.         return cvt(value)
  363.     except ValueError:
  364.         raise OptionValueError(
  365.             _("option %s: invalid %s value: %r") % (opt, what, value))
  366.  
  367. def check_choice(option, opt, value):
  368.     if value in option.choices:
  369.         return value
  370.     else:
  371.         choices = ", ".join(map(repr, option.choices))
  372.         raise OptionValueError(
  373.             _("option %s: invalid choice: %r (choose from %s)")
  374.             % (opt, value, choices))
  375.  
  376. # Not supplying a default is different from a default of None,
  377. # so we need an explicit "not supplied" value.
  378. NO_DEFAULT = ("NO", "DEFAULT")
  379.  
  380.  
  381. class Option:
  382.     """
  383.     Instance attributes:
  384.       _short_opts : [string]
  385.       _long_opts : [string]
  386.  
  387.       action : string
  388.       type : string
  389.       dest : string
  390.       default : any
  391.       nargs : int
  392.       const : any
  393.       choices : [string]
  394.       callback : function
  395.       callback_args : (any*)
  396.       callback_kwargs : { string : any }
  397.       help : string
  398.       metavar : string
  399.     """
  400.  
  401.     # The list of instance attributes that may be set through
  402.     # keyword args to the constructor.
  403.     ATTRS = ['action',
  404.              'type',
  405.              'dest',
  406.              'default',
  407.              'nargs',
  408.              'const',
  409.              'choices',
  410.              'callback',
  411.              'callback_args',
  412.              'callback_kwargs',
  413.              'help',
  414.              'metavar']
  415.  
  416.     # The set of actions allowed by option parsers.  Explicitly listed
  417.     # here so the constructor can validate its arguments.
  418.     ACTIONS = ("store",
  419.                "store_const",
  420.                "store_true",
  421.                "store_false",
  422.                "append",
  423.                "count",
  424.                "callback",
  425.                "help",
  426.                "version")
  427.  
  428.     # The set of actions that involve storing a value somewhere;
  429.     # also listed just for constructor argument validation.  (If
  430.     # the action is one of these, there must be a destination.)
  431.     STORE_ACTIONS = ("store",
  432.                      "store_const",
  433.                      "store_true",
  434.                      "store_false",
  435.                      "append",
  436.                      "count")
  437.  
  438.     # The set of actions for which it makes sense to supply a value
  439.     # type, ie. which may consume an argument from the command line.
  440.     TYPED_ACTIONS = ("store",
  441.                      "append",
  442.                      "callback")
  443.  
  444.     # The set of actions which *require* a value type, ie. that
  445.     # always consume an argument from the command line.
  446.     ALWAYS_TYPED_ACTIONS = ("store",
  447.                             "append")
  448.  
  449.     # The set of known types for option parsers.  Again, listed here for
  450.     # constructor argument validation.
  451.     TYPES = ("string", "int", "long", "float", "complex", "choice")
  452.  
  453.     # Dictionary of argument checking functions, which convert and
  454.     # validate option arguments according to the option type.
  455.     #
  456.     # Signature of checking functions is:
  457.     #   check(option : Option, opt : string, value : string) -> any
  458.     # where
  459.     #   option is the Option instance calling the checker
  460.     #   opt is the actual option seen on the command-line
  461.     #     (eg. "-a", "--file")
  462.     #   value is the option argument seen on the command-line
  463.     #
  464.     # The return value should be in the appropriate Python type
  465.     # for option.type -- eg. an integer if option.type == "int".
  466.     #
  467.     # If no checker is defined for a type, arguments will be
  468.     # unchecked and remain strings.
  469.     TYPE_CHECKER = { "int"    : check_builtin,
  470.                      "long"   : check_builtin,
  471.                      "float"  : check_builtin,
  472.                      "complex": check_builtin,
  473.                      "choice" : check_choice,
  474.                    }
  475.  
  476.  
  477.     # CHECK_METHODS is a list of unbound method objects; they are called
  478.     # by the constructor, in order, after all attributes are
  479.     # initialized.  The list is created and filled in later, after all
  480.     # the methods are actually defined.  (I just put it here because I
  481.     # like to define and document all class attributes in the same
  482.     # place.)  Subclasses that add another _check_*() method should
  483.     # define their own CHECK_METHODS list that adds their check method
  484.     # to those from this class.
  485.     CHECK_METHODS = None
  486.  
  487.  
  488.     # -- Constructor/initialization methods ----------------------------
  489.  
  490.     def __init__(self, *opts, **attrs):
  491.         # Set _short_opts, _long_opts attrs from 'opts' tuple.
  492.         # Have to be set now, in case no option strings are supplied.
  493.         self._short_opts = []
  494.         self._long_opts = []
  495.         opts = self._check_opt_strings(opts)
  496.         self._set_opt_strings(opts)
  497.  
  498.         # Set all other attrs (action, type, etc.) from 'attrs' dict
  499.         self._set_attrs(attrs)
  500.  
  501.         # Check all the attributes we just set.  There are lots of
  502.         # complicated interdependencies, but luckily they can be farmed
  503.         # out to the _check_*() methods listed in CHECK_METHODS -- which
  504.         # could be handy for subclasses!  The one thing these all share
  505.         # is that they raise OptionError if they discover a problem.
  506.         for checker in self.CHECK_METHODS:
  507.             checker(self)
  508.  
  509.     def _check_opt_strings(self, opts):
  510.         # Filter out None because early versions of Optik had exactly
  511.         # one short option and one long option, either of which
  512.         # could be None.
  513.         opts = filter(None, opts)
  514.         if not opts:
  515.             raise TypeError("at least one option string must be supplied")
  516.         return opts
  517.  
  518.     def _set_opt_strings(self, opts):
  519.         for opt in opts:
  520.             if len(opt) < 2:
  521.                 raise OptionError(
  522.                     "invalid option string %r: "
  523.                     "must be at least two characters long" % opt, self)
  524.             elif len(opt) == 2:
  525.                 if not (opt[0] == "-" and opt[1] != "-"):
  526.                     raise OptionError(
  527.                         "invalid short option string %r: "
  528.                         "must be of the form -x, (x any non-dash char)" % opt,
  529.                         self)
  530.                 self._short_opts.append(opt)
  531.             else:
  532.                 if not (opt[0:2] == "--" and opt[2] != "-"):
  533.                     raise OptionError(
  534.                         "invalid long option string %r: "
  535.                         "must start with --, followed by non-dash" % opt,
  536.                         self)
  537.                 self._long_opts.append(opt)
  538.  
  539.     def _set_attrs(self, attrs):
  540.         for attr in self.ATTRS:
  541.             if attrs.has_key(attr):
  542.                 setattr(self, attr, attrs[attr])
  543.                 del attrs[attr]
  544.             else:
  545.                 if attr == 'default':
  546.                     setattr(self, attr, NO_DEFAULT)
  547.                 else:
  548.                     setattr(self, attr, None)
  549.         if attrs:
  550.             raise OptionError(
  551.                 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
  552.                 self)
  553.  
  554.  
  555.     # -- Constructor validation methods --------------------------------
  556.  
  557.     def _check_action(self):
  558.         if self.action is None:
  559.             self.action = "store"
  560.         elif self.action not in self.ACTIONS:
  561.             raise OptionError("invalid action: %r" % self.action, self)
  562.  
  563.     def _check_type(self):
  564.         if self.type is None:
  565.             if self.action in self.ALWAYS_TYPED_ACTIONS:
  566.                 if self.choices is not None:
  567.                     # The "choices" attribute implies "choice" type.
  568.                     self.type = "choice"
  569.                 else:
  570.                     # No type given?  "string" is the most sensible default.
  571.                     self.type = "string"
  572.         else:
  573.             # Allow type objects as an alternative to their names.
  574.             if type(self.type) is type:
  575.                 self.type = self.type.__name__
  576.             if self.type == "str":
  577.                 self.type = "string"
  578.  
  579.             if self.type not in self.TYPES:
  580.                 raise OptionError("invalid option type: %r" % self.type, self)
  581.             if self.action not in self.TYPED_ACTIONS:
  582.                 raise OptionError(
  583.                     "must not supply a type for action %r" % self.action, self)
  584.  
  585.     def _check_choice(self):
  586.         if self.type == "choice":
  587.             if self.choices is None:
  588.                 raise OptionError(
  589.                     "must supply a list of choices for type 'choice'", self)
  590.             elif type(self.choices) not in (types.TupleType, types.ListType):
  591.                 raise OptionError(
  592.                     "choices must be a list of strings ('%s' supplied)"
  593.                     % str(type(self.choices)).split("'")[1], self)
  594.         elif self.choices is not None:
  595.             raise OptionError(
  596.                 "must not supply choices for type %r" % self.type, self)
  597.  
  598.     def _check_dest(self):
  599.         # No destination given, and we need one for this action.  The
  600.         # self.type check is for callbacks that take a value.
  601.         takes_value = (self.action in self.STORE_ACTIONS or
  602.                        self.type is not None)
  603.         if self.dest is None and takes_value:
  604.  
  605.             # Glean a destination from the first long option string,
  606.             # or from the first short option string if no long options.
  607.             if self._long_opts:
  608.                 # eg. "--foo-bar" -> "foo_bar"
  609.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  610.             else:
  611.                 self.dest = self._short_opts[0][1]
  612.  
  613.     def _check_const(self):
  614.         if self.action != "store_const" and self.const is not None:
  615.             raise OptionError(
  616.                 "'const' must not be supplied for action %r" % self.action,
  617.                 self)
  618.  
  619.     def _check_nargs(self):
  620.         if self.action in self.TYPED_ACTIONS:
  621.             if self.nargs is None:
  622.                 self.nargs = 1
  623.         elif self.nargs is not None:
  624.             raise OptionError(
  625.                 "'nargs' must not be supplied for action %r" % self.action,
  626.                 self)
  627.  
  628.     def _check_callback(self):
  629.         if self.action == "callback":
  630.             if not callable(self.callback):
  631.                 raise OptionError(
  632.                     "callback not callable: %r" % self.callback, self)
  633.             if (self.callback_args is not None and
  634.                 type(self.callback_args) is not types.TupleType):
  635.                 raise OptionError(
  636.                     "callback_args, if supplied, must be a tuple: not %r"
  637.                     % self.callback_args, self)
  638.             if (self.callback_kwargs is not None and
  639.                 type(self.callback_kwargs) is not types.DictType):
  640.                 raise OptionError(
  641.                     "callback_kwargs, if supplied, must be a dict: not %r"
  642.                     % self.callback_kwargs, self)
  643.         else:
  644.             if self.callback is not None:
  645.                 raise OptionError(
  646.                     "callback supplied (%r) for non-callback option"
  647.                     % self.callback, self)
  648.             if self.callback_args is not None:
  649.                 raise OptionError(
  650.                     "callback_args supplied for non-callback option", self)
  651.             if self.callback_kwargs is not None:
  652.                 raise OptionError(
  653.                     "callback_kwargs supplied for non-callback option", self)
  654.  
  655.  
  656.     CHECK_METHODS = [_check_action,
  657.                      _check_type,
  658.                      _check_choice,
  659.                      _check_dest,
  660.                      _check_const,
  661.                      _check_nargs,
  662.                      _check_callback]
  663.  
  664.  
  665.     # -- Miscellaneous methods -----------------------------------------
  666.  
  667.     def __str__(self):
  668.         return "/".join(self._short_opts + self._long_opts)
  669.  
  670.     __repr__ = _repr
  671.  
  672.     def takes_value(self):
  673.         return self.type is not None
  674.  
  675.     def get_opt_string(self):
  676.         if self._long_opts:
  677.             return self._long_opts[0]
  678.         else:
  679.             return self._short_opts[0]
  680.  
  681.  
  682.     # -- Processing methods --------------------------------------------
  683.  
  684.     def check_value(self, opt, value):
  685.         checker = self.TYPE_CHECKER.get(self.type)
  686.         if checker is None:
  687.             return value
  688.         else:
  689.             return checker(self, opt, value)
  690.  
  691.     def convert_value(self, opt, value):
  692.         if value is not None:
  693.             if self.nargs == 1:
  694.                 return self.check_value(opt, value)
  695.             else:
  696.                 return tuple([self.check_value(opt, v) for v in value])
  697.  
  698.     def process(self, opt, value, values, parser):
  699.  
  700.         # First, convert the value(s) to the right type.  Howl if any
  701.         # value(s) are bogus.
  702.         value = self.convert_value(opt, value)
  703.  
  704.         # And then take whatever action is expected of us.
  705.         # This is a separate method to make life easier for
  706.         # subclasses to add new actions.
  707.         return self.take_action(
  708.             self.action, self.dest, opt, value, values, parser)
  709.  
  710.     def take_action(self, action, dest, opt, value, values, parser):
  711.         if action == "store":
  712.             setattr(values, dest, value)
  713.         elif action == "store_const":
  714.             setattr(values, dest, self.const)
  715.         elif action == "store_true":
  716.             setattr(values, dest, True)
  717.         elif action == "store_false":
  718.             setattr(values, dest, False)
  719.         elif action == "append":
  720.             values.ensure_value(dest, []).append(value)
  721.         elif action == "count":
  722.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  723.         elif action == "callback":
  724.             args = self.callback_args or ()
  725.             kwargs = self.callback_kwargs or {}
  726.             self.callback(self, opt, value, parser, *args, **kwargs)
  727.         elif action == "help":
  728.             parser.print_help()
  729.             parser.exit()
  730.         elif action == "version":
  731.             parser.print_version()
  732.             parser.exit()
  733.         else:
  734.             raise RuntimeError, "unknown action %r" % self.action
  735.  
  736.         return 1
  737.  
  738. # class Option
  739.  
  740.  
  741. SUPPRESS_HELP = "SUPPRESS"+"HELP"
  742. SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
  743.  
  744. # For compatibility with Python 2.2
  745. try:
  746.     True, False
  747. except NameError:
  748.     (True, False) = (1, 0)
  749. try:
  750.     basestring
  751. except NameError:
  752.     basestring = (str, unicode)
  753.  
  754.  
  755. class Values:
  756.  
  757.     def __init__(self, defaults=None):
  758.         if defaults:
  759.             for (attr, val) in defaults.items():
  760.                 setattr(self, attr, val)
  761.  
  762.     def __str__(self):
  763.         return str(self.__dict__)
  764.  
  765.     __repr__ = _repr
  766.  
  767.     def __eq__(self, other):
  768.         if isinstance(other, Values):
  769.             return self.__dict__ == other.__dict__
  770.         elif isinstance(other, dict):
  771.             return self.__dict__ == other
  772.         else:
  773.             return False
  774.  
  775.     def __ne__(self, other):
  776.         return not (self == other)
  777.  
  778.     def _update_careful(self, dict):
  779.         """
  780.         Update the option values from an arbitrary dictionary, but only
  781.         use keys from dict that already have a corresponding attribute
  782.         in self.  Any keys in dict without a corresponding attribute
  783.         are silently ignored.
  784.         """
  785.         for attr in dir(self):
  786.             if dict.has_key(attr):
  787.                 dval = dict[attr]
  788.                 if dval is not None:
  789.                     setattr(self, attr, dval)
  790.  
  791.     def _update_loose(self, dict):
  792.         """
  793.         Update the option values from an arbitrary dictionary,
  794.         using all keys from the dictionary regardless of whether
  795.         they have a corresponding attribute in self or not.
  796.         """
  797.         self.__dict__.update(dict)
  798.  
  799.     def _update(self, dict, mode):
  800.         if mode == "careful":
  801.             self._update_careful(dict)
  802.         elif mode == "loose":
  803.             self._update_loose(dict)
  804.         else:
  805.             raise ValueError, "invalid update mode: %r" % mode
  806.  
  807.     def read_module(self, modname, mode="careful"):
  808.         __import__(modname)
  809.         mod = sys.modules[modname]
  810.         self._update(vars(mod), mode)
  811.  
  812.     def read_file(self, filename, mode="careful"):
  813.         vars = {}
  814.         execfile(filename, vars)
  815.         self._update(vars, mode)
  816.  
  817.     def ensure_value(self, attr, value):
  818.         if not hasattr(self, attr) or getattr(self, attr) is None:
  819.             setattr(self, attr, value)
  820.         return getattr(self, attr)
  821.  
  822.  
  823. class OptionContainer:
  824.  
  825.     """
  826.     Abstract base class.
  827.  
  828.     Class attributes:
  829.       standard_option_list : [Option]
  830.         list of standard options that will be accepted by all instances
  831.         of this parser class (intended to be overridden by subclasses).
  832.  
  833.     Instance attributes:
  834.       option_list : [Option]
  835.         the list of Option objects contained by this OptionContainer
  836.       _short_opt : { string : Option }
  837.         dictionary mapping short option strings, eg. "-f" or "-X",
  838.         to the Option instances that implement them.  If an Option
  839.         has multiple short option strings, it will appears in this
  840.         dictionary multiple times. [1]
  841.       _long_opt : { string : Option }
  842.         dictionary mapping long option strings, eg. "--file" or
  843.         "--exclude", to the Option instances that implement them.
  844.         Again, a given Option can occur multiple times in this
  845.         dictionary. [1]
  846.       defaults : { string : any }
  847.         dictionary mapping option destination names to default
  848.         values for each destination [1]
  849.  
  850.     [1] These mappings are common to (shared by) all components of the
  851.         controlling OptionParser, where they are initially created.
  852.  
  853.     """
  854.  
  855.     def __init__(self, option_class, conflict_handler, description):
  856.         # Initialize the option list and related data structures.
  857.         # This method must be provided by subclasses, and it must
  858.         # initialize at least the following instance attributes:
  859.         # option_list, _short_opt, _long_opt, defaults.
  860.         self._create_option_list()
  861.  
  862.         self.option_class = option_class
  863.         self.set_conflict_handler(conflict_handler)
  864.         self.set_description(description)
  865.  
  866.     def _create_option_mappings(self):
  867.         # For use by OptionParser constructor -- create the master
  868.         # option mappings used by this OptionParser and all
  869.         # OptionGroups that it owns.
  870.         self._short_opt = {}            # single letter -> Option instance
  871.         self._long_opt = {}             # long option -> Option instance
  872.         self.defaults = {}              # maps option dest -> default value
  873.  
  874.  
  875.     def _share_option_mappings(self, parser):
  876.         # For use by OptionGroup constructor -- use shared option
  877.         # mappings from the OptionParser that owns this OptionGroup.
  878.         self._short_opt = parser._short_opt
  879.         self._long_opt = parser._long_opt
  880.         self.defaults = parser.defaults
  881.  
  882.     def set_conflict_handler(self, handler):
  883.         if handler not in ("error", "resolve"):
  884.             raise ValueError, "invalid conflict_resolution value %r" % handler
  885.         self.conflict_handler = handler
  886.  
  887.     def set_description(self, description):
  888.         self.description = description
  889.  
  890.     def get_description(self):
  891.         return self.description
  892.  
  893.  
  894.     # -- Option-adding methods -----------------------------------------
  895.  
  896.     def _check_conflict(self, option):
  897.         conflict_opts = []
  898.         for opt in option._short_opts:
  899.             if self._short_opt.has_key(opt):
  900.                 conflict_opts.append((opt, self._short_opt[opt]))
  901.         for opt in option._long_opts:
  902.             if self._long_opt.has_key(opt):
  903.                 conflict_opts.append((opt, self._long_opt[opt]))
  904.  
  905.         if conflict_opts:
  906.             handler = self.conflict_handler
  907.             if handler == "error":
  908.                 raise OptionConflictError(
  909.                     "conflicting option string(s): %s"
  910.                     % ", ".join([co[0] for co in conflict_opts]),
  911.                     option)
  912.             elif handler == "resolve":
  913.                 for (opt, c_option) in conflict_opts:
  914.                     if opt.startswith("--"):
  915.                         c_option._long_opts.remove(opt)
  916.                         del self._long_opt[opt]
  917.                     else:
  918.                         c_option._short_opts.remove(opt)
  919.                         del self._short_opt[opt]
  920.                     if not (c_option._short_opts or c_option._long_opts):
  921.                         c_option.container.option_list.remove(c_option)
  922.  
  923.     def add_option(self, *args, **kwargs):
  924.         """add_option(Option)
  925.            add_option(opt_str, ..., kwarg=val, ...)
  926.         """
  927.         if type(args[0]) is types.StringType:
  928.             option = self.option_class(*args, **kwargs)
  929.         elif len(args) == 1 and not kwargs:
  930.             option = args[0]
  931.             if not isinstance(option, Option):
  932.                 raise TypeError, "not an Option instance: %r" % option
  933.         else:
  934.             raise TypeError, "invalid arguments"
  935.  
  936.         self._check_conflict(option)
  937.  
  938.         self.option_list.append(option)
  939.         option.container = self
  940.         for opt in option._short_opts:
  941.             self._short_opt[opt] = option
  942.         for opt in option._long_opts:
  943.             self._long_opt[opt] = option
  944.  
  945.         if option.dest is not None:     # option has a dest, we need a default
  946.             if option.default is not NO_DEFAULT:
  947.                 self.defaults[option.dest] = option.default
  948.             elif not self.defaults.has_key(option.dest):
  949.                 self.defaults[option.dest] = None
  950.  
  951.         return option
  952.  
  953.     def add_options(self, option_list):
  954.         for option in option_list:
  955.             self.add_option(option)
  956.  
  957.     # -- Option query/removal methods ----------------------------------
  958.  
  959.     def get_option(self, opt_str):
  960.         return (self._short_opt.get(opt_str) or
  961.                 self._long_opt.get(opt_str))
  962.  
  963.     def has_option(self, opt_str):
  964.         return (self._short_opt.has_key(opt_str) or
  965.                 self._long_opt.has_key(opt_str))
  966.  
  967.     def remove_option(self, opt_str):
  968.         option = self._short_opt.get(opt_str)
  969.         if option is None:
  970.             option = self._long_opt.get(opt_str)
  971.         if option is None:
  972.             raise ValueError("no such option %r" % opt_str)
  973.  
  974.         for opt in option._short_opts:
  975.             del self._short_opt[opt]
  976.         for opt in option._long_opts:
  977.             del self._long_opt[opt]
  978.         option.container.option_list.remove(option)
  979.  
  980.  
  981.     # -- Help-formatting methods ---------------------------------------
  982.  
  983.     def format_option_help(self, formatter):
  984.         if not self.option_list:
  985.             return ""
  986.         result = []
  987.         for option in self.option_list:
  988.             if not option.help is SUPPRESS_HELP:
  989.                 result.append(formatter.format_option(option))
  990.         return "".join(result)
  991.  
  992.     def format_description(self, formatter):
  993.         return formatter.format_description(self.get_description())
  994.  
  995.     def format_help(self, formatter):
  996.         result = []
  997.         if self.description:
  998.             result.append(self.format_description(formatter))
  999.         if self.option_list:
  1000.             result.append(self.format_option_help(formatter))
  1001.         return "\n".join(result)
  1002.  
  1003.  
  1004. class OptionGroup (OptionContainer):
  1005.  
  1006.     def __init__(self, parser, title, description=None):
  1007.         self.parser = parser
  1008.         OptionContainer.__init__(
  1009.             self, parser.option_class, parser.conflict_handler, description)
  1010.         self.title = title
  1011.  
  1012.     def _create_option_list(self):
  1013.         self.option_list = []
  1014.         self._share_option_mappings(self.parser)
  1015.  
  1016.     def set_title(self, title):
  1017.         self.title = title
  1018.  
  1019.     # -- Help-formatting methods ---------------------------------------
  1020.  
  1021.     def format_help(self, formatter):
  1022.         result = formatter.format_heading(self.title)
  1023.         formatter.indent()
  1024.         result += OptionContainer.format_help(self, formatter)
  1025.         formatter.dedent()
  1026.         return result
  1027.  
  1028.  
  1029. class OptionParser (OptionContainer):
  1030.  
  1031.     """
  1032.     Class attributes:
  1033.       standard_option_list : [Option]
  1034.         list of standard options that will be accepted by all instances
  1035.         of this parser class (intended to be overridden by subclasses).
  1036.  
  1037.     Instance attributes:
  1038.       usage : string
  1039.         a usage string for your program.  Before it is displayed
  1040.         to the user, "%prog" will be expanded to the name of
  1041.         your program (self.prog or os.path.basename(sys.argv[0])).
  1042.       prog : string
  1043.         the name of the current program (to override
  1044.         os.path.basename(sys.argv[0])).
  1045.  
  1046.       option_groups : [OptionGroup]
  1047.         list of option groups in this parser (option groups are
  1048.         irrelevant for parsing the command-line, but very useful
  1049.         for generating help)
  1050.  
  1051.       allow_interspersed_args : bool = true
  1052.         if true, positional arguments may be interspersed with options.
  1053.         Assuming -a and -b each take a single argument, the command-line
  1054.           -ablah foo bar -bboo baz
  1055.         will be interpreted the same as
  1056.           -ablah -bboo -- foo bar baz
  1057.         If this flag were false, that command line would be interpreted as
  1058.           -ablah -- foo bar -bboo baz
  1059.         -- ie. we stop processing options as soon as we see the first
  1060.         non-option argument.  (This is the tradition followed by
  1061.         Python's getopt module, Perl's Getopt::Std, and other argument-
  1062.         parsing libraries, but it is generally annoying to users.)
  1063.  
  1064.       process_default_values : bool = true
  1065.         if true, option default values are processed similarly to option
  1066.         values from the command line: that is, they are passed to the
  1067.         type-checking function for the option's type (as long as the
  1068.         default value is a string).  (This really only matters if you
  1069.         have defined custom types; see SF bug #955889.)  Set it to false
  1070.         to restore the behaviour of Optik 1.4.1 and earlier.
  1071.  
  1072.       rargs : [string]
  1073.         the argument list currently being parsed.  Only set when
  1074.         parse_args() is active, and continually trimmed down as
  1075.         we consume arguments.  Mainly there for the benefit of
  1076.         callback options.
  1077.       largs : [string]
  1078.         the list of leftover arguments that we have skipped while
  1079.         parsing options.  If allow_interspersed_args is false, this
  1080.         list is always empty.
  1081.       values : Values
  1082.         the set of option values currently being accumulated.  Only
  1083.         set when parse_args() is active.  Also mainly for callbacks.
  1084.  
  1085.     Because of the 'rargs', 'largs', and 'values' attributes,
  1086.     OptionParser is not thread-safe.  If, for some perverse reason, you
  1087.     need to parse command-line arguments simultaneously in different
  1088.     threads, use different OptionParser instances.
  1089.  
  1090.     """
  1091.  
  1092.     standard_option_list = []
  1093.  
  1094.     def __init__(self,
  1095.                  usage=None,
  1096.                  option_list=None,
  1097.                  option_class=Option,
  1098.                  version=None,
  1099.                  conflict_handler="error",
  1100.                  description=None,
  1101.                  formatter=None,
  1102.                  add_help_option=True,
  1103.                  prog=None):
  1104.         OptionContainer.__init__(
  1105.             self, option_class, conflict_handler, description)
  1106.         self.set_usage(usage)
  1107.         self.prog = prog
  1108.         self.version = version
  1109.         self.allow_interspersed_args = True
  1110.         self.process_default_values = True
  1111.         if formatter is None:
  1112.             formatter = IndentedHelpFormatter()
  1113.         self.formatter = formatter
  1114.         self.formatter.set_parser(self)
  1115.  
  1116.         # Populate the option list; initial sources are the
  1117.         # standard_option_list class attribute, the 'option_list'
  1118.         # argument, and (if applicable) the _add_version_option() and
  1119.         # _add_help_option() methods.
  1120.         self._populate_option_list(option_list,
  1121.                                    add_help=add_help_option)
  1122.  
  1123.         self._init_parsing_state()
  1124.  
  1125.     # -- Private methods -----------------------------------------------
  1126.     # (used by our or OptionContainer's constructor)
  1127.  
  1128.     def _create_option_list(self):
  1129.         self.option_list = []
  1130.         self.option_groups = []
  1131.         self._create_option_mappings()
  1132.  
  1133.     def _add_help_option(self):
  1134.         self.add_option("-h", "--help",
  1135.                         action="help",
  1136.                         help=_("show this help message and exit"))
  1137.  
  1138.     def _add_version_option(self):
  1139.         self.add_option("--version",
  1140.                         action="version",
  1141.                         help=_("show program's version number and exit"))
  1142.  
  1143.     def _populate_option_list(self, option_list, add_help=True):
  1144.         if self.standard_option_list:
  1145.             self.add_options(self.standard_option_list)
  1146.         if option_list:
  1147.             self.add_options(option_list)
  1148.         if self.version:
  1149.             self._add_version_option()
  1150.         if add_help:
  1151.             self._add_help_option()
  1152.  
  1153.     def _init_parsing_state(self):
  1154.         # These are set in parse_args() for the convenience of callbacks.
  1155.         self.rargs = None
  1156.         self.largs = None
  1157.         self.values = None
  1158.  
  1159.  
  1160.     # -- Simple modifier methods ---------------------------------------
  1161.  
  1162.     def set_usage(self, usage):
  1163.         if usage is None:
  1164.             self.usage = _("%prog [options]")
  1165.         elif usage is SUPPRESS_USAGE:
  1166.             self.usage = None
  1167.         # For backwards compatibility with Optik 1.3 and earlier.
  1168.         elif usage.startswith("usage:" + " "):
  1169.             self.usage = usage[7:]
  1170.         else:
  1171.             self.usage = usage
  1172.  
  1173.     def enable_interspersed_args(self):
  1174.         self.allow_interspersed_args = True
  1175.  
  1176.     def disable_interspersed_args(self):
  1177.         self.allow_interspersed_args = False
  1178.  
  1179.     def set_process_default_values(self, process):
  1180.         self.process_default_values = process
  1181.  
  1182.     def set_default(self, dest, value):
  1183.         self.defaults[dest] = value
  1184.  
  1185.     def set_defaults(self, **kwargs):
  1186.         self.defaults.update(kwargs)
  1187.  
  1188.     def _get_all_options(self):
  1189.         options = self.option_list[:]
  1190.         for group in self.option_groups:
  1191.             options.extend(group.option_list)
  1192.         return options
  1193.  
  1194.     def get_default_values(self):
  1195.         if not self.process_default_values:
  1196.             # Old, pre-Optik 1.5 behaviour.
  1197.             return Values(self.defaults)
  1198.  
  1199.         defaults = self.defaults.copy()
  1200.         for option in self._get_all_options():
  1201.             default = defaults.get(option.dest)
  1202.             if isinstance(default, basestring):
  1203.                 opt_str = option.get_opt_string()
  1204.                 defaults[option.dest] = option.check_value(opt_str, default)
  1205.  
  1206.         return Values(defaults)
  1207.  
  1208.  
  1209.     # -- OptionGroup methods -------------------------------------------
  1210.  
  1211.     def add_option_group(self, *args, **kwargs):
  1212.         # XXX lots of overlap with OptionContainer.add_option()
  1213.         if type(args[0]) is types.StringType:
  1214.             group = OptionGroup(self, *args, **kwargs)
  1215.         elif len(args) == 1 and not kwargs:
  1216.             group = args[0]
  1217.             if not isinstance(group, OptionGroup):
  1218.                 raise TypeError, "not an OptionGroup instance: %r" % group
  1219.             if group.parser is not self:
  1220.                 raise ValueError, "invalid OptionGroup (wrong parser)"
  1221.         else:
  1222.             raise TypeError, "invalid arguments"
  1223.  
  1224.         self.option_groups.append(group)
  1225.         return group
  1226.  
  1227.     def get_option_group(self, opt_str):
  1228.         option = (self._short_opt.get(opt_str) or
  1229.                   self._long_opt.get(opt_str))
  1230.         if option and option.container is not self:
  1231.             return option.container
  1232.         return None
  1233.  
  1234.  
  1235.     # -- Option-parsing methods ----------------------------------------
  1236.  
  1237.     def _get_args(self, args):
  1238.         if args is None:
  1239.             return sys.argv[1:]
  1240.         else:
  1241.             return args[:]              # don't modify caller's list
  1242.  
  1243.     def parse_args(self, args=None, values=None):
  1244.         """
  1245.         parse_args(args : [string] = sys.argv[1:],
  1246.                    values : Values = None)
  1247.         -> (values : Values, args : [string])
  1248.  
  1249.         Parse the command-line options found in 'args' (default:
  1250.         sys.argv[1:]).  Any errors result in a call to 'error()', which
  1251.         by default prints the usage message to stderr and calls
  1252.         sys.exit() with an error message.  On success returns a pair
  1253.         (values, args) where 'values' is an Values instance (with all
  1254.         your option values) and 'args' is the list of arguments left
  1255.         over after parsing options.
  1256.         """
  1257.         rargs = self._get_args(args)
  1258.         if values is None:
  1259.             values = self.get_default_values()
  1260.  
  1261.         # Store the halves of the argument list as attributes for the
  1262.         # convenience of callbacks:
  1263.         #   rargs
  1264.         #     the rest of the command-line (the "r" stands for
  1265.         #     "remaining" or "right-hand")
  1266.         #   largs
  1267.         #     the leftover arguments -- ie. what's left after removing
  1268.         #     options and their arguments (the "l" stands for "leftover"
  1269.         #     or "left-hand")
  1270.         self.rargs = rargs
  1271.         self.largs = largs = []
  1272.         self.values = values
  1273.  
  1274.         try:
  1275.             stop = self._process_args(largs, rargs, values)
  1276.         except (BadOptionError, OptionValueError), err:
  1277.             self.error(err.msg)
  1278.  
  1279.         args = largs + rargs
  1280.         return self.check_values(values, args)
  1281.  
  1282.     def check_values(self, values, args):
  1283.         """
  1284.         check_values(values : Values, args : [string])
  1285.         -> (values : Values, args : [string])
  1286.  
  1287.         Check that the supplied option values and leftover arguments are
  1288.         valid.  Returns the option values and leftover arguments
  1289.         (possibly adjusted, possibly completely new -- whatever you
  1290.         like).  Default implementation just returns the passed-in
  1291.         values; subclasses may override as desired.
  1292.         """
  1293.         return (values, args)
  1294.  
  1295.     def _process_args(self, largs, rargs, values):
  1296.         """_process_args(largs : [string],
  1297.                          rargs : [string],
  1298.                          values : Values)
  1299.  
  1300.         Process command-line arguments and populate 'values', consuming
  1301.         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
  1302.         false, stop at the first non-option argument.  If true, accumulate any
  1303.         interspersed non-option arguments in 'largs'.
  1304.         """
  1305.         while rargs:
  1306.             arg = rargs[0]
  1307.             # We handle bare "--" explicitly, and bare "-" is handled by the
  1308.             # standard arg handler since the short arg case ensures that the
  1309.             # len of the opt string is greater than 1.
  1310.             if arg == "--":
  1311.                 del rargs[0]
  1312.                 return
  1313.             elif arg[0:2] == "--":
  1314.                 # process a single long option (possibly with value(s))
  1315.                 self._process_long_opt(rargs, values)
  1316.             elif arg[:1] == "-" and len(arg) > 1:
  1317.                 # process a cluster of short options (possibly with
  1318.                 # value(s) for the last one only)
  1319.                 self._process_short_opts(rargs, values)
  1320.             elif self.allow_interspersed_args:
  1321.                 largs.append(arg)
  1322.                 del rargs[0]
  1323.             else:
  1324.                 return                  # stop now, leave this arg in rargs
  1325.  
  1326.         # Say this is the original argument list:
  1327.         # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
  1328.         #                            ^
  1329.         # (we are about to process arg(i)).
  1330.         #
  1331.         # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
  1332.         # [arg0, ..., arg(i-1)] (any options and their arguments will have
  1333.         # been removed from largs).
  1334.         #
  1335.         # The while loop will usually consume 1 or more arguments per pass.
  1336.         # If it consumes 1 (eg. arg is an option that takes no arguments),
  1337.         # then after _process_arg() is done the situation is:
  1338.         #
  1339.         #   largs = subset of [arg0, ..., arg(i)]
  1340.         #   rargs = [arg(i+1), ..., arg(N-1)]
  1341.         #
  1342.         # If allow_interspersed_args is false, largs will always be
  1343.         # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
  1344.         # not a very interesting subset!
  1345.  
  1346.     def _match_long_opt(self, opt):
  1347.         """_match_long_opt(opt : string) -> string
  1348.  
  1349.         Determine which long option string 'opt' matches, ie. which one
  1350.         it is an unambiguous abbrevation for.  Raises BadOptionError if
  1351.         'opt' doesn't unambiguously match any long option string.
  1352.         """
  1353.         return _match_abbrev(opt, self._long_opt)
  1354.  
  1355.     def _process_long_opt(self, rargs, values):
  1356.         arg = rargs.pop(0)
  1357.  
  1358.         # Value explicitly attached to arg?  Pretend it's the next
  1359.         # argument.
  1360.         if "=" in arg:
  1361.             (opt, next_arg) = arg.split("=", 1)
  1362.             rargs.insert(0, next_arg)
  1363.             had_explicit_value = True
  1364.         else:
  1365.             opt = arg
  1366.             had_explicit_value = False
  1367.  
  1368.         opt = self._match_long_opt(opt)
  1369.         option = self._long_opt[opt]
  1370.         if option.takes_value():
  1371.             nargs = option.nargs
  1372.             if len(rargs) < nargs:
  1373.                 if nargs == 1:
  1374.                     self.error(_("%s option requires an argument") % opt)
  1375.                 else:
  1376.                     self.error(_("%s option requires %d arguments")
  1377.                                % (opt, nargs))
  1378.             elif nargs == 1:
  1379.                 value = rargs.pop(0)
  1380.             else:
  1381.                 value = tuple(rargs[0:nargs])
  1382.                 del rargs[0:nargs]
  1383.  
  1384.         elif had_explicit_value:
  1385.             self.error(_("%s option does not take a value") % opt)
  1386.  
  1387.         else:
  1388.             value = None
  1389.  
  1390.         option.process(opt, value, values, self)
  1391.  
  1392.     def _process_short_opts(self, rargs, values):
  1393.         arg = rargs.pop(0)
  1394.         stop = False
  1395.         i = 1
  1396.         for ch in arg[1:]:
  1397.             opt = "-" + ch
  1398.             option = self._short_opt.get(opt)
  1399.             i += 1                      # we have consumed a character
  1400.  
  1401.             if not option:
  1402.                 self.error(_("no such option: %s") % opt)
  1403.             if option.takes_value():
  1404.                 # Any characters left in arg?  Pretend they're the
  1405.                 # next arg, and stop consuming characters of arg.
  1406.                 if i < len(arg):
  1407.                     rargs.insert(0, arg[i:])
  1408.                     stop = True
  1409.  
  1410.                 nargs = option.nargs
  1411.                 if len(rargs) < nargs:
  1412.                     if nargs == 1:
  1413.                         self.error(_("%s option requires an argument") % opt)
  1414.                     else:
  1415.                         self.error(_("%s option requires %d arguments")
  1416.                                    % (opt, nargs))
  1417.                 elif nargs == 1:
  1418.                     value = rargs.pop(0)
  1419.                 else:
  1420.                     value = tuple(rargs[0:nargs])
  1421.                     del rargs[0:nargs]
  1422.  
  1423.             else:                       # option doesn't take a value
  1424.                 value = None
  1425.  
  1426.             option.process(opt, value, values, self)
  1427.  
  1428.             if stop:
  1429.                 break
  1430.  
  1431.  
  1432.     # -- Feedback methods ----------------------------------------------
  1433.  
  1434.     def get_prog_name(self):
  1435.         if self.prog is None:
  1436.             return os.path.basename(sys.argv[0])
  1437.         else:
  1438.             return self.prog
  1439.  
  1440.     def expand_prog_name(self, s):
  1441.         return s.replace("%prog", self.get_prog_name())
  1442.  
  1443.     def get_description(self):
  1444.         return self.expand_prog_name(self.description)
  1445.  
  1446.     def exit(self, status=0, msg=None):
  1447.         if msg:
  1448.             sys.stderr.write(msg)
  1449.         sys.exit(status)
  1450.  
  1451.     def error(self, msg):
  1452.         """error(msg : string)
  1453.  
  1454.         Print a usage message incorporating 'msg' to stderr and exit.
  1455.         If you override this in a subclass, it should not return -- it
  1456.         should either exit or raise an exception.
  1457.         """
  1458.         self.print_usage(sys.stderr)
  1459.         self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
  1460.  
  1461.     def get_usage(self):
  1462.         if self.usage:
  1463.             return self.formatter.format_usage(
  1464.                 self.expand_prog_name(self.usage))
  1465.         else:
  1466.             return ""
  1467.  
  1468.     def print_usage(self, file=None):
  1469.         """print_usage(file : file = stdout)
  1470.  
  1471.         Print the usage message for the current program (self.usage) to
  1472.         'file' (default stdout).  Any occurence of the string "%prog" in
  1473.         self.usage is replaced with the name of the current program
  1474.         (basename of sys.argv[0]).  Does nothing if self.usage is empty
  1475.         or not defined.
  1476.         """
  1477.         if self.usage:
  1478.             print >>file, self.get_usage()
  1479.  
  1480.     def get_version(self):
  1481.         if self.version:
  1482.             return self.expand_prog_name(self.version)
  1483.         else:
  1484.             return ""
  1485.  
  1486.     def print_version(self, file=None):
  1487.         """print_version(file : file = stdout)
  1488.  
  1489.         Print the version message for this program (self.version) to
  1490.         'file' (default stdout).  As with print_usage(), any occurence
  1491.         of "%prog" in self.version is replaced by the current program's
  1492.         name.  Does nothing if self.version is empty or undefined.
  1493.         """
  1494.         if self.version:
  1495.             print >>file, self.get_version()
  1496.  
  1497.     def format_option_help(self, formatter=None):
  1498.         if formatter is None:
  1499.             formatter = self.formatter
  1500.         formatter.store_option_strings(self)
  1501.         result = []
  1502.         result.append(formatter.format_heading(_("options")))
  1503.         formatter.indent()
  1504.         if self.option_list:
  1505.             result.append(OptionContainer.format_option_help(self, formatter))
  1506.             result.append("\n")
  1507.         for group in self.option_groups:
  1508.             result.append(group.format_help(formatter))
  1509.             result.append("\n")
  1510.         formatter.dedent()
  1511.         # Drop the last "\n", or the header if no options or option groups:
  1512.         return "".join(result[:-1])
  1513.  
  1514.     def format_help(self, formatter=None):
  1515.         if formatter is None:
  1516.             formatter = self.formatter
  1517.         result = []
  1518.         if self.usage:
  1519.             result.append(self.get_usage() + "\n")
  1520.         if self.description:
  1521.             result.append(self.format_description(formatter) + "\n")
  1522.         result.append(self.format_option_help(formatter))
  1523.         return "".join(result)
  1524.  
  1525.     def print_help(self, file=None):
  1526.         """print_help(file : file = stdout)
  1527.  
  1528.         Print an extended help message, listing all options and any
  1529.         help text provided with them, to 'file' (default stdout).
  1530.         """
  1531.         if file is None:
  1532.             file = sys.stdout
  1533.         file.write(self.format_help())
  1534.  
  1535. # class OptionParser
  1536.  
  1537.  
  1538. def _match_abbrev(s, wordmap):
  1539.     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1540.  
  1541.     Return the string key in 'wordmap' for which 's' is an unambiguous
  1542.     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
  1543.     'words', raise BadOptionError.
  1544.     """
  1545.     # Is there an exact match?
  1546.     if wordmap.has_key(s):
  1547.         return s
  1548.     else:
  1549.         # Isolate all words with s as a prefix.
  1550.         possibilities = [word for word in wordmap.keys()
  1551.                          if word.startswith(s)]
  1552.         # No exact match, so there had better be just one possibility.
  1553.         if len(possibilities) == 1:
  1554.             return possibilities[0]
  1555.         elif not possibilities:
  1556.             raise BadOptionError(_("no such option: %s") % s)
  1557.         else:
  1558.             # More than one possible completion: ambiguous prefix.
  1559.             raise BadOptionError(_("ambiguous option: %s (%s?)")
  1560.                                  % (s, ", ".join(possibilities)))
  1561.  
  1562.  
  1563. # Some day, there might be many Option classes.  As of Optik 1.3, the
  1564. # preferred way to instantiate Options is indirectly, via make_option(),
  1565. # which will become a factory function when there are many Option
  1566. # classes.
  1567. make_option = Option
  1568.