github.com/google/grumpy@v0.0.0-20171122020858-3ec87959189c/third_party/stdlib/optparse.py (about)

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