home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / optparse.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  37.7 KB  |  1,173 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.7)
  3.  
  4. __version__ = '1.5.3'
  5. __all__ = [
  6.     'Option',
  7.     'make_option',
  8.     'SUPPRESS_HELP',
  9.     'SUPPRESS_USAGE',
  10.     'Values',
  11.     'OptionContainer',
  12.     'OptionGroup',
  13.     'OptionParser',
  14.     'HelpFormatter',
  15.     'IndentedHelpFormatter',
  16.     'TitledHelpFormatter',
  17.     'OptParseError',
  18.     'OptionError',
  19.     'OptionConflictError',
  20.     'OptionValueError',
  21.     'BadOptionError']
  22. __copyright__ = '\nCopyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.\nCopyright (c) 2002-2006 Python Software Foundation.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the author nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\nIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'
  23. import sys
  24. import os
  25. import types
  26. import textwrap
  27.  
  28. def _repr(self):
  29.     return '<%s at 0x%x: %s>' % (self.__class__.__name__, id(self), self)
  30.  
  31.  
  32. try:
  33.     from gettext import gettext
  34. except ImportError:
  35.     
  36.     def gettext(message):
  37.         return message
  38.  
  39.  
  40. _ = gettext
  41.  
  42. class OptParseError(Exception):
  43.     
  44.     def __init__(self, msg):
  45.         self.msg = msg
  46.  
  47.     
  48.     def __str__(self):
  49.         return self.msg
  50.  
  51.  
  52.  
  53. class OptionError(OptParseError):
  54.     
  55.     def __init__(self, msg, option):
  56.         self.msg = msg
  57.         self.option_id = str(option)
  58.  
  59.     
  60.     def __str__(self):
  61.         if self.option_id:
  62.             return 'option %s: %s' % (self.option_id, self.msg)
  63.         return None.msg
  64.  
  65.  
  66.  
  67. class OptionConflictError(OptionError):
  68.     pass
  69.  
  70.  
  71. class OptionValueError(OptParseError):
  72.     pass
  73.  
  74.  
  75. class BadOptionError(OptParseError):
  76.     
  77.     def __init__(self, opt_str):
  78.         self.opt_str = opt_str
  79.  
  80.     
  81.     def __str__(self):
  82.         return _('no such option: %s') % self.opt_str
  83.  
  84.  
  85.  
  86. class AmbiguousOptionError(BadOptionError):
  87.     
  88.     def __init__(self, opt_str, possibilities):
  89.         BadOptionError.__init__(self, opt_str)
  90.         self.possibilities = possibilities
  91.  
  92.     
  93.     def __str__(self):
  94.         return _('ambiguous option: %s (%s?)') % (self.opt_str, ', '.join(self.possibilities))
  95.  
  96.  
  97.  
  98. class HelpFormatter:
  99.     NO_DEFAULT_VALUE = 'none'
  100.     
  101.     def __init__(self, indent_increment, max_help_position, width, short_first):
  102.         self.parser = None
  103.         self.indent_increment = indent_increment
  104.         self.help_position = self.max_help_position = max_help_position
  105.         if width is None:
  106.             
  107.             try:
  108.                 width = int(os.environ['COLUMNS'])
  109.             except (KeyError, ValueError):
  110.                 width = 80
  111.  
  112.             width -= 2
  113.         self.width = width
  114.         self.current_indent = 0
  115.         self.level = 0
  116.         self.help_width = None
  117.         self.short_first = short_first
  118.         self.default_tag = '%default'
  119.         self.option_strings = { }
  120.         self._short_opt_fmt = '%s %s'
  121.         self._long_opt_fmt = '%s=%s'
  122.  
  123.     
  124.     def set_parser(self, parser):
  125.         self.parser = parser
  126.  
  127.     
  128.     def set_short_opt_delimiter(self, delim):
  129.         if delim not in ('', ' '):
  130.             raise ValueError('invalid metavar delimiter for short options: %r' % delim)
  131.         self._short_opt_fmt = '%s' + delim + '%s'
  132.  
  133.     
  134.     def set_long_opt_delimiter(self, delim):
  135.         if delim not in ('=', ' '):
  136.             raise ValueError('invalid metavar delimiter for long options: %r' % delim)
  137.         self._long_opt_fmt = '%s' + delim + '%s'
  138.  
  139.     
  140.     def indent(self):
  141.         self.current_indent += self.indent_increment
  142.         self.level += 1
  143.  
  144.     
  145.     def dedent(self):
  146.         self.current_indent -= self.indent_increment
  147.         self.level -= 1
  148.  
  149.     
  150.     def format_usage(self, usage):
  151.         raise NotImplementedError, 'subclasses must implement'
  152.  
  153.     
  154.     def format_heading(self, heading):
  155.         raise NotImplementedError, 'subclasses must implement'
  156.  
  157.     
  158.     def _format_text(self, text):
  159.         text_width = self.width - self.current_indent
  160.         indent = ' ' * self.current_indent
  161.         return textwrap.fill(text, text_width, initial_indent = indent, subsequent_indent = indent)
  162.  
  163.     
  164.     def format_description(self, description):
  165.         if description:
  166.             return self._format_text(description) + '\n'
  167.         return None
  168.  
  169.     
  170.     def format_epilog(self, epilog):
  171.         if epilog:
  172.             return '\n' + self._format_text(epilog) + '\n'
  173.         return None
  174.  
  175.     
  176.     def expand_default(self, option):
  177.         if self.parser is None or not (self.default_tag):
  178.             return option.help
  179.         default_value = None.parser.defaults.get(option.dest)
  180.         if default_value is NO_DEFAULT or default_value is None:
  181.             default_value = self.NO_DEFAULT_VALUE
  182.         return option.help.replace(self.default_tag, str(default_value))
  183.  
  184.     
  185.     def format_option(self, option):
  186.         result = []
  187.         opts = self.option_strings[option]
  188.         opt_width = self.help_position - self.current_indent - 2
  189.         if len(opts) > opt_width:
  190.             opts = '%*s%s\n' % (self.current_indent, '', opts)
  191.             indent_first = self.help_position
  192.         else:
  193.             opts = '%*s%-*s  ' % (self.current_indent, '', opt_width, opts)
  194.             indent_first = 0
  195.         result.append(opts)
  196.         if option.help:
  197.             help_text = self.expand_default(option)
  198.             help_lines = textwrap.wrap(help_text, self.help_width)
  199.             result.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  200.             result.extend([ '%*s%s\n' % (self.help_position, '', line) for line in help_lines[1:] ])
  201.         elif opts[-1] != '\n':
  202.             result.append('\n')
  203.         return ''.join(result)
  204.  
  205.     
  206.     def store_option_strings(self, parser):
  207.         self.indent()
  208.         max_len = 0
  209.         for opt in parser.option_list:
  210.             strings = self.format_option_strings(opt)
  211.             self.option_strings[opt] = strings
  212.             max_len = max(max_len, len(strings) + self.current_indent)
  213.         
  214.         self.indent()
  215.         for group in parser.option_groups:
  216.             for opt in group.option_list:
  217.                 strings = self.format_option_strings(opt)
  218.                 self.option_strings[opt] = strings
  219.                 max_len = max(max_len, len(strings) + self.current_indent)
  220.             
  221.         
  222.         self.dedent()
  223.         self.dedent()
  224.         self.help_position = min(max_len + 2, self.max_help_position)
  225.         self.help_width = self.width - self.help_position
  226.  
  227.     
  228.     def format_option_strings(self, option):
  229.         if option.takes_value():
  230.             if not option.metavar:
  231.                 pass
  232.             metavar = option.dest.upper()
  233.             short_opts = [ self._short_opt_fmt % (sopt, metavar) for sopt in option._short_opts ]
  234.             long_opts = [ self._long_opt_fmt % (lopt, metavar) for lopt in option._long_opts ]
  235.         else:
  236.             short_opts = option._short_opts
  237.             long_opts = option._long_opts
  238.         if self.short_first:
  239.             opts = short_opts + long_opts
  240.         else:
  241.             opts = long_opts + short_opts
  242.         return ', '.join(opts)
  243.  
  244.  
  245.  
  246. class IndentedHelpFormatter(HelpFormatter):
  247.     
  248.     def __init__(self, indent_increment = 2, max_help_position = 24, width = None, short_first = 1):
  249.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  250.  
  251.     
  252.     def format_usage(self, usage):
  253.         return _('Usage: %s\n') % usage
  254.  
  255.     
  256.     def format_heading(self, heading):
  257.         return '%*s%s:\n' % (self.current_indent, '', heading)
  258.  
  259.  
  260.  
  261. class TitledHelpFormatter(HelpFormatter):
  262.     
  263.     def __init__(self, indent_increment = 0, max_help_position = 24, width = None, short_first = 0):
  264.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  265.  
  266.     
  267.     def format_usage(self, usage):
  268.         return '%s  %s\n' % (self.format_heading(_('Usage')), usage)
  269.  
  270.     
  271.     def format_heading(self, heading):
  272.         return '%s\n%s\n' % (heading, '=-'[self.level] * len(heading))
  273.  
  274.  
  275.  
  276. def _parse_num(val, type):
  277.     if val[:2].lower() == '0x':
  278.         radix = 16
  279.     elif val[:2].lower() == '0b':
  280.         radix = 2
  281.         if not val[2:]:
  282.             pass
  283.         val = '0'
  284.     elif val[:1] == '0':
  285.         radix = 8
  286.     else:
  287.         radix = 10
  288.     return type(val, radix)
  289.  
  290.  
  291. def _parse_int(val):
  292.     return _parse_num(val, int)
  293.  
  294.  
  295. def _parse_long(val):
  296.     return _parse_num(val, long)
  297.  
  298. _builtin_cvt = {
  299.     'int': (_parse_int, _('integer')),
  300.     'long': (_parse_long, _('long integer')),
  301.     'float': (float, _('floating-point')),
  302.     'complex': (complex, _('complex')) }
  303.  
  304. def check_builtin(option, opt, value):
  305.     (cvt, what) = _builtin_cvt[option.type]
  306.     
  307.     try:
  308.         return cvt(value)
  309.     except ValueError:
  310.         raise OptionValueError(_('option %s: invalid %s value: %r') % (opt, what, value))
  311.  
  312.  
  313.  
  314. def check_choice(option, opt, value):
  315.     if value in option.choices:
  316.         return value
  317.     choices = None.join(map(repr, option.choices))
  318.     raise OptionValueError(_('option %s: invalid choice: %r (choose from %s)') % (opt, value, choices))
  319.  
  320. NO_DEFAULT = ('NO', 'DEFAULT')
  321.  
  322. class Option:
  323.     ATTRS = [
  324.         'action',
  325.         'type',
  326.         'dest',
  327.         'default',
  328.         'nargs',
  329.         'const',
  330.         'choices',
  331.         'callback',
  332.         'callback_args',
  333.         'callback_kwargs',
  334.         'help',
  335.         'metavar']
  336.     ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count', 'callback', 'help', 'version')
  337.     STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count')
  338.     TYPED_ACTIONS = ('store', 'append', 'callback')
  339.     ALWAYS_TYPED_ACTIONS = ('store', 'append')
  340.     CONST_ACTIONS = ('store_const', 'append_const')
  341.     TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
  342.     TYPE_CHECKER = {
  343.         'int': check_builtin,
  344.         'long': check_builtin,
  345.         'float': check_builtin,
  346.         'complex': check_builtin,
  347.         'choice': check_choice }
  348.     CHECK_METHODS = None
  349.     
  350.     def __init__(self, *opts, **attrs):
  351.         self._short_opts = []
  352.         self._long_opts = []
  353.         opts = self._check_opt_strings(opts)
  354.         self._set_opt_strings(opts)
  355.         self._set_attrs(attrs)
  356.         for checker in self.CHECK_METHODS:
  357.             checker(self)
  358.         
  359.  
  360.     
  361.     def _check_opt_strings(self, opts):
  362.         opts = filter(None, opts)
  363.         if not opts:
  364.             raise TypeError('at least one option string must be supplied')
  365.         return opts
  366.  
  367.     
  368.     def _set_opt_strings(self, opts):
  369.         for opt in opts:
  370.             if len(opt) < 2:
  371.                 raise OptionError('invalid option string %r: must be at least two characters long' % opt, self)
  372.             if len(opt) == 2:
  373.                 if not opt[0] == '-' and opt[1] != '-':
  374.                     raise OptionError('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt, self)
  375.                 self._short_opts.append(opt)
  376.                 continue
  377.             if not opt[0:2] == '--' and opt[2] != '-':
  378.                 raise OptionError('invalid long option string %r: must start with --, followed by non-dash' % opt, self)
  379.             self._long_opts.append(opt)
  380.         
  381.  
  382.     
  383.     def _set_attrs(self, attrs):
  384.         for attr in self.ATTRS:
  385.             if attr in attrs:
  386.                 setattr(self, attr, attrs[attr])
  387.                 del attrs[attr]
  388.                 continue
  389.             if attr == 'default':
  390.                 setattr(self, attr, NO_DEFAULT)
  391.                 continue
  392.             setattr(self, attr, None)
  393.         
  394.         if attrs:
  395.             attrs = attrs.keys()
  396.             attrs.sort()
  397.             raise OptionError('invalid keyword arguments: %s' % ', '.join(attrs), self)
  398.  
  399.     
  400.     def _check_action(self):
  401.         if self.action is None:
  402.             self.action = 'store'
  403.         elif self.action not in self.ACTIONS:
  404.             raise OptionError('invalid action: %r' % self.action, self)
  405.  
  406.     
  407.     def _check_type(self):
  408.         if self.type is None or self.action in self.ALWAYS_TYPED_ACTIONS:
  409.             if self.choices is not None:
  410.                 self.type = 'choice'
  411.             else:
  412.                 self.type = 'string'
  413.         
  414.         import __builtin__
  415.         if (type(self.type) is types.TypeType or hasattr(self.type, '__name__')) and getattr(__builtin__, self.type.__name__, None) is self.type:
  416.             self.type = self.type.__name__
  417.         if self.type == 'str':
  418.             self.type = 'string'
  419.         if self.type not in self.TYPES:
  420.             raise OptionError('invalid option type: %r' % self.type, self)
  421.         if self.action not in self.TYPED_ACTIONS:
  422.             raise OptionError('must not supply a type for action %r' % self.action, self)
  423.  
  424.     
  425.     def _check_choice(self):
  426.         if self.type == 'choice':
  427.             if self.choices is None:
  428.                 raise OptionError("must supply a list of choices for type 'choice'", self)
  429.             if type(self.choices) not in (types.TupleType, types.ListType):
  430.                 raise OptionError("choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self)
  431.         elif self.choices is not None:
  432.             raise OptionError('must not supply choices for type %r' % self.type, self)
  433.  
  434.     
  435.     def _check_dest(self):
  436.         if not self.action in self.STORE_ACTIONS:
  437.             pass
  438.         takes_value = self.type is not None
  439.         if self.dest is None and takes_value:
  440.             if self._long_opts:
  441.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  442.             else:
  443.                 self.dest = self._short_opts[0][1]
  444.  
  445.     
  446.     def _check_const(self):
  447.         if self.action not in self.CONST_ACTIONS and self.const is not None:
  448.             raise OptionError("'const' must not be supplied for action %r" % self.action, self)
  449.  
  450.     
  451.     def _check_nargs(self):
  452.         if self.action in self.TYPED_ACTIONS or self.nargs is None:
  453.             self.nargs = 1
  454.         
  455.         if self.nargs is not None:
  456.             raise OptionError("'nargs' must not be supplied for action %r" % self.action, self)
  457.  
  458.     
  459.     def _check_callback(self):
  460.         if self.action == 'callback':
  461.             if not hasattr(self.callback, '__call__'):
  462.                 raise OptionError('callback not callable: %r' % self.callback, self)
  463.             if self.callback_args is not None and type(self.callback_args) is not types.TupleType:
  464.                 raise OptionError('callback_args, if supplied, must be a tuple: not %r' % self.callback_args, self)
  465.             if self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType:
  466.                 raise OptionError('callback_kwargs, if supplied, must be a dict: not %r' % self.callback_kwargs, self)
  467.         elif self.callback is not None:
  468.             raise OptionError('callback supplied (%r) for non-callback option' % self.callback, self)
  469.         if self.callback_args is not None:
  470.             raise OptionError('callback_args supplied for non-callback option', self)
  471.         if self.callback_kwargs is not None:
  472.             raise OptionError('callback_kwargs supplied for non-callback option', self)
  473.  
  474.     CHECK_METHODS = [
  475.         _check_action,
  476.         _check_type,
  477.         _check_choice,
  478.         _check_dest,
  479.         _check_const,
  480.         _check_nargs,
  481.         _check_callback]
  482.     
  483.     def __str__(self):
  484.         return '/'.join(self._short_opts + self._long_opts)
  485.  
  486.     __repr__ = _repr
  487.     
  488.     def takes_value(self):
  489.         return self.type is not None
  490.  
  491.     
  492.     def get_opt_string(self):
  493.         if self._long_opts:
  494.             return self._long_opts[0]
  495.         return None._short_opts[0]
  496.  
  497.     
  498.     def check_value(self, opt, value):
  499.         checker = self.TYPE_CHECKER.get(self.type)
  500.         if checker is None:
  501.             return value
  502.         return None(self, opt, value)
  503.  
  504.     
  505.     def convert_value(self, opt, value):
  506.         if value is not None:
  507.             if self.nargs == 1:
  508.                 return self.check_value(opt, value)
  509.             return None([ self.check_value(opt, v) for v in value ])
  510.  
  511.     
  512.     def process(self, opt, value, values, parser):
  513.         value = self.convert_value(opt, value)
  514.         return self.take_action(self.action, self.dest, opt, value, values, parser)
  515.  
  516.     
  517.     def take_action(self, action, dest, opt, value, values, parser):
  518.         if action == 'store':
  519.             setattr(values, dest, value)
  520.         elif action == 'store_const':
  521.             setattr(values, dest, self.const)
  522.         elif action == 'store_true':
  523.             setattr(values, dest, True)
  524.         elif action == 'store_false':
  525.             setattr(values, dest, False)
  526.         elif action == 'append':
  527.             values.ensure_value(dest, []).append(value)
  528.         elif action == 'append_const':
  529.             values.ensure_value(dest, []).append(self.const)
  530.         elif action == 'count':
  531.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  532.         elif action == 'callback':
  533.             if not self.callback_args:
  534.                 pass
  535.             args = ()
  536.             if not self.callback_kwargs:
  537.                 pass
  538.             kwargs = { }
  539.             self.callback(self, opt, value, parser, *args, **kwargs)
  540.         elif action == 'help':
  541.             parser.print_help()
  542.             parser.exit()
  543.         elif action == 'version':
  544.             parser.print_version()
  545.             parser.exit()
  546.         else:
  547.             raise ValueError('unknown action %r' % self.action)
  548.  
  549.  
  550. SUPPRESS_HELP = 'SUPPRESS' + 'HELP'
  551. SUPPRESS_USAGE = 'SUPPRESS' + 'USAGE'
  552.  
  553. try:
  554.     basestring
  555. except NameError:
  556.     
  557.     def isbasestring(x):
  558.         return isinstance(x, (types.StringType, types.UnicodeType))
  559.  
  560.  
  561.  
  562. def isbasestring(x):
  563.     return isinstance(x, basestring)
  564.  
  565.  
  566. class Values:
  567.     
  568.     def __init__(self, defaults = None):
  569.         if defaults:
  570.             for attr, val in defaults.items():
  571.                 setattr(self, attr, val)
  572.             
  573.  
  574.     
  575.     def __str__(self):
  576.         return str(self.__dict__)
  577.  
  578.     __repr__ = _repr
  579.     
  580.     def __cmp__(self, other):
  581.         if isinstance(other, Values):
  582.             return cmp(self.__dict__, other.__dict__)
  583.         if None(other, types.DictType):
  584.             return cmp(self.__dict__, other)
  585.         return None
  586.  
  587.     
  588.     def _update_careful(self, dict):
  589.         for attr in dir(self):
  590.             if attr in dict:
  591.                 dval = dict[attr]
  592.                 if dval is not None:
  593.                     setattr(self, attr, dval)
  594.                 
  595.  
  596.     
  597.     def _update_loose(self, dict):
  598.         self.__dict__.update(dict)
  599.  
  600.     
  601.     def _update(self, dict, mode):
  602.         if mode == 'careful':
  603.             self._update_careful(dict)
  604.         elif mode == 'loose':
  605.             self._update_loose(dict)
  606.         else:
  607.             raise ValueError, 'invalid update mode: %r' % mode
  608.  
  609.     
  610.     def read_module(self, modname, mode = 'careful'):
  611.         __import__(modname)
  612.         mod = sys.modules[modname]
  613.         self._update(vars(mod), mode)
  614.  
  615.     
  616.     def read_file(self, filename, mode = 'careful'):
  617.         vars = { }
  618.         execfile(filename, vars)
  619.         self._update(vars, mode)
  620.  
  621.     
  622.     def ensure_value(self, attr, value):
  623.         if not hasattr(self, attr) or getattr(self, attr) is None:
  624.             setattr(self, attr, value)
  625.         return getattr(self, attr)
  626.  
  627.  
  628.  
  629. class OptionContainer:
  630.     
  631.     def __init__(self, option_class, conflict_handler, description):
  632.         self._create_option_list()
  633.         self.option_class = option_class
  634.         self.set_conflict_handler(conflict_handler)
  635.         self.set_description(description)
  636.  
  637.     
  638.     def _create_option_mappings(self):
  639.         self._short_opt = { }
  640.         self._long_opt = { }
  641.         self.defaults = { }
  642.  
  643.     
  644.     def _share_option_mappings(self, parser):
  645.         self._short_opt = parser._short_opt
  646.         self._long_opt = parser._long_opt
  647.         self.defaults = parser.defaults
  648.  
  649.     
  650.     def set_conflict_handler(self, handler):
  651.         if handler not in ('error', 'resolve'):
  652.             raise ValueError, 'invalid conflict_resolution value %r' % handler
  653.         self.conflict_handler = handler
  654.  
  655.     
  656.     def set_description(self, description):
  657.         self.description = description
  658.  
  659.     
  660.     def get_description(self):
  661.         return self.description
  662.  
  663.     
  664.     def destroy(self):
  665.         del self._short_opt
  666.         del self._long_opt
  667.         del self.defaults
  668.  
  669.     
  670.     def _check_conflict(self, option):
  671.         conflict_opts = []
  672.         for opt in option._short_opts:
  673.             if opt in self._short_opt:
  674.                 conflict_opts.append((opt, self._short_opt[opt]))
  675.                 continue
  676.         for opt in option._long_opts:
  677.             if opt in self._long_opt:
  678.                 conflict_opts.append((opt, self._long_opt[opt]))
  679.                 continue
  680.         if conflict_opts:
  681.             handler = self.conflict_handler
  682.             if handler == 'error':
  683.                 raise OptionConflictError('conflicting option string(s): %s' % ', '.join([ co[0] for co in conflict_opts ]), option)
  684.             if handler == 'resolve':
  685.                 for opt, c_option in conflict_opts:
  686.                     if opt.startswith('--'):
  687.                         c_option._long_opts.remove(opt)
  688.                         del self._long_opt[opt]
  689.                     else:
  690.                         c_option._short_opts.remove(opt)
  691.                         del self._short_opt[opt]
  692.                     if not c_option._short_opts:
  693.                         if not c_option._long_opts:
  694.                             c_option.container.option_list.remove(c_option)
  695.                             continue
  696.                     
  697.  
  698.     
  699.     def add_option(self, *args, **kwargs):
  700.         if type(args[0]) in types.StringTypes:
  701.             option = self.option_class(*args, **kwargs)
  702.         elif len(args) == 1 and not kwargs:
  703.             option = args[0]
  704.             if not isinstance(option, Option):
  705.                 raise TypeError, 'not an Option instance: %r' % option
  706.         else:
  707.             raise TypeError, 'invalid arguments'
  708.         None._check_conflict(option)
  709.         self.option_list.append(option)
  710.         option.container = self
  711.         for opt in option._short_opts:
  712.             self._short_opt[opt] = option
  713.         
  714.         for opt in option._long_opts:
  715.             self._long_opt[opt] = option
  716.         
  717.         if option.dest is not None:
  718.             if option.default is not NO_DEFAULT:
  719.                 self.defaults[option.dest] = option.default
  720.             elif option.dest not in self.defaults:
  721.                 self.defaults[option.dest] = None
  722.             
  723.         return option
  724.  
  725.     
  726.     def add_options(self, option_list):
  727.         for option in option_list:
  728.             self.add_option(option)
  729.         
  730.  
  731.     
  732.     def get_option(self, opt_str):
  733.         if not self._short_opt.get(opt_str):
  734.             pass
  735.         return self._long_opt.get(opt_str)
  736.  
  737.     
  738.     def has_option(self, opt_str):
  739.         if not opt_str in self._short_opt:
  740.             pass
  741.         return opt_str in self._long_opt
  742.  
  743.     
  744.     def remove_option(self, opt_str):
  745.         option = self._short_opt.get(opt_str)
  746.         if option is None:
  747.             option = self._long_opt.get(opt_str)
  748.         if option is None:
  749.             raise ValueError('no such option %r' % opt_str)
  750.         for opt in option._short_opts:
  751.             del self._short_opt[opt]
  752.         
  753.         for opt in option._long_opts:
  754.             del self._long_opt[opt]
  755.         
  756.         option.container.option_list.remove(option)
  757.  
  758.     
  759.     def format_option_help(self, formatter):
  760.         if not self.option_list:
  761.             return ''
  762.         result = None
  763.         for option in self.option_list:
  764.             if option.help is not SUPPRESS_HELP:
  765.                 result.append(formatter.format_option(option))
  766.                 continue
  767.         return ''.join(result)
  768.  
  769.     
  770.     def format_description(self, formatter):
  771.         return formatter.format_description(self.get_description())
  772.  
  773.     
  774.     def format_help(self, formatter):
  775.         result = []
  776.         if self.description:
  777.             result.append(self.format_description(formatter))
  778.         if self.option_list:
  779.             result.append(self.format_option_help(formatter))
  780.         return '\n'.join(result)
  781.  
  782.  
  783.  
  784. class OptionGroup(OptionContainer):
  785.     
  786.     def __init__(self, parser, title, description = None):
  787.         self.parser = parser
  788.         OptionContainer.__init__(self, parser.option_class, parser.conflict_handler, description)
  789.         self.title = title
  790.  
  791.     
  792.     def _create_option_list(self):
  793.         self.option_list = []
  794.         self._share_option_mappings(self.parser)
  795.  
  796.     
  797.     def set_title(self, title):
  798.         self.title = title
  799.  
  800.     
  801.     def destroy(self):
  802.         OptionContainer.destroy(self)
  803.         del self.option_list
  804.  
  805.     
  806.     def format_help(self, formatter):
  807.         result = formatter.format_heading(self.title)
  808.         formatter.indent()
  809.         result += OptionContainer.format_help(self, formatter)
  810.         formatter.dedent()
  811.         return result
  812.  
  813.  
  814.  
  815. class OptionParser(OptionContainer):
  816.     standard_option_list = []
  817.     
  818.     def __init__(self, usage = None, option_list = None, option_class = Option, version = None, conflict_handler = 'error', description = None, formatter = None, add_help_option = True, prog = None, epilog = None):
  819.         OptionContainer.__init__(self, option_class, conflict_handler, description)
  820.         self.set_usage(usage)
  821.         self.prog = prog
  822.         self.version = version
  823.         self.allow_interspersed_args = True
  824.         self.process_default_values = True
  825.         if formatter is None:
  826.             formatter = IndentedHelpFormatter()
  827.         self.formatter = formatter
  828.         self.formatter.set_parser(self)
  829.         self.epilog = epilog
  830.         self._populate_option_list(option_list, add_help = add_help_option)
  831.         self._init_parsing_state()
  832.  
  833.     
  834.     def destroy(self):
  835.         OptionContainer.destroy(self)
  836.         for group in self.option_groups:
  837.             group.destroy()
  838.         
  839.         del self.option_list
  840.         del self.option_groups
  841.         del self.formatter
  842.  
  843.     
  844.     def _create_option_list(self):
  845.         self.option_list = []
  846.         self.option_groups = []
  847.         self._create_option_mappings()
  848.  
  849.     
  850.     def _add_help_option(self):
  851.         self.add_option('-h', '--help', action = 'help', help = _('show this help message and exit'))
  852.  
  853.     
  854.     def _add_version_option(self):
  855.         self.add_option('--version', action = 'version', help = _("show program's version number and exit"))
  856.  
  857.     
  858.     def _populate_option_list(self, option_list, add_help = True):
  859.         if self.standard_option_list:
  860.             self.add_options(self.standard_option_list)
  861.         if option_list:
  862.             self.add_options(option_list)
  863.         if self.version:
  864.             self._add_version_option()
  865.         if add_help:
  866.             self._add_help_option()
  867.  
  868.     
  869.     def _init_parsing_state(self):
  870.         self.rargs = None
  871.         self.largs = None
  872.         self.values = None
  873.  
  874.     
  875.     def set_usage(self, usage):
  876.         if usage is None:
  877.             self.usage = _('%prog [options]')
  878.         elif usage is SUPPRESS_USAGE:
  879.             self.usage = None
  880.         elif usage.lower().startswith('usage: '):
  881.             self.usage = usage[7:]
  882.         else:
  883.             self.usage = usage
  884.  
  885.     
  886.     def enable_interspersed_args(self):
  887.         self.allow_interspersed_args = True
  888.  
  889.     
  890.     def disable_interspersed_args(self):
  891.         self.allow_interspersed_args = False
  892.  
  893.     
  894.     def set_process_default_values(self, process):
  895.         self.process_default_values = process
  896.  
  897.     
  898.     def set_default(self, dest, value):
  899.         self.defaults[dest] = value
  900.  
  901.     
  902.     def set_defaults(self, **kwargs):
  903.         self.defaults.update(kwargs)
  904.  
  905.     
  906.     def _get_all_options(self):
  907.         options = self.option_list[:]
  908.         for group in self.option_groups:
  909.             options.extend(group.option_list)
  910.         
  911.         return options
  912.  
  913.     
  914.     def get_default_values(self):
  915.         if not self.process_default_values:
  916.             return Values(self.defaults)
  917.         defaults = None.defaults.copy()
  918.         for option in self._get_all_options():
  919.             default = defaults.get(option.dest)
  920.             if isbasestring(default):
  921.                 opt_str = option.get_opt_string()
  922.                 defaults[option.dest] = option.check_value(opt_str, default)
  923.                 continue
  924.         return Values(defaults)
  925.  
  926.     
  927.     def add_option_group(self, *args, **kwargs):
  928.         if type(args[0]) is types.StringType:
  929.             group = OptionGroup(self, *args, **kwargs)
  930.         elif len(args) == 1 and not kwargs:
  931.             group = args[0]
  932.             if not isinstance(group, OptionGroup):
  933.                 raise TypeError, 'not an OptionGroup instance: %r' % group
  934.             if group.parser is not self:
  935.                 raise ValueError, 'invalid OptionGroup (wrong parser)'
  936.         else:
  937.             raise TypeError, 'invalid arguments'
  938.         None.option_groups.append(group)
  939.         return group
  940.  
  941.     
  942.     def get_option_group(self, opt_str):
  943.         if not self._short_opt.get(opt_str):
  944.             pass
  945.         option = self._long_opt.get(opt_str)
  946.         if option and option.container is not self:
  947.             return option.container
  948.  
  949.     
  950.     def _get_args(self, args):
  951.         if args is None:
  952.             return sys.argv[1:]
  953.         return None[:]
  954.  
  955.     
  956.     def parse_args(self, args = None, values = None):
  957.         rargs = self._get_args(args)
  958.         if values is None:
  959.             values = self.get_default_values()
  960.         self.rargs = rargs
  961.         self.largs = largs = []
  962.         self.values = values
  963.         
  964.         try:
  965.             stop = self._process_args(largs, rargs, values)
  966.         except (BadOptionError, OptionValueError):
  967.             err = None
  968.             self.error(str(err))
  969.  
  970.         args = largs + rargs
  971.         return self.check_values(values, args)
  972.  
  973.     
  974.     def check_values(self, values, args):
  975.         return (values, args)
  976.  
  977.     
  978.     def _process_args(self, largs, rargs, values):
  979.         while rargs:
  980.             arg = rargs[0]
  981.             if arg == '--':
  982.                 del rargs[0]
  983.                 return None
  984.             if None[0:2] == '--':
  985.                 self._process_long_opt(rargs, values)
  986.                 continue
  987.             if arg[:1] == '-' and len(arg) > 1:
  988.                 self._process_short_opts(rargs, values)
  989.                 continue
  990.             if self.allow_interspersed_args:
  991.                 largs.append(arg)
  992.                 del rargs[0]
  993.                 continue
  994.             return None
  995.  
  996.     
  997.     def _match_long_opt(self, opt):
  998.         return _match_abbrev(opt, self._long_opt)
  999.  
  1000.     
  1001.     def _process_long_opt(self, rargs, values):
  1002.         arg = rargs.pop(0)
  1003.         if '=' in arg:
  1004.             (opt, next_arg) = arg.split('=', 1)
  1005.             rargs.insert(0, next_arg)
  1006.             had_explicit_value = True
  1007.         else:
  1008.             opt = arg
  1009.             had_explicit_value = False
  1010.         opt = self._match_long_opt(opt)
  1011.         option = self._long_opt[opt]
  1012.         if option.takes_value():
  1013.             nargs = option.nargs
  1014.             if len(rargs) < nargs:
  1015.                 if nargs == 1:
  1016.                     self.error(_('%s option requires an argument') % opt)
  1017.                 else:
  1018.                     self.error(_('%s option requires %d arguments') % (opt, nargs))
  1019.             elif nargs == 1:
  1020.                 value = rargs.pop(0)
  1021.             else:
  1022.                 value = tuple(rargs[0:nargs])
  1023.                 del rargs[0:nargs]
  1024.         elif had_explicit_value:
  1025.             self.error(_('%s option does not take a value') % opt)
  1026.         else:
  1027.             value = None
  1028.         option.process(opt, value, values, self)
  1029.  
  1030.     
  1031.     def _process_short_opts(self, rargs, values):
  1032.         arg = rargs.pop(0)
  1033.         stop = False
  1034.         i = 1
  1035.         for ch in arg[1:]:
  1036.             opt = '-' + ch
  1037.             option = self._short_opt.get(opt)
  1038.             i += 1
  1039.             if not option:
  1040.                 raise BadOptionError(opt)
  1041.             if option.takes_value():
  1042.                 if i < len(arg):
  1043.                     rargs.insert(0, arg[i:])
  1044.                     stop = True
  1045.                 nargs = option.nargs
  1046.                 if len(rargs) < nargs:
  1047.                     if nargs == 1:
  1048.                         self.error(_('%s option requires an argument') % opt)
  1049.                     else:
  1050.                         self.error(_('%s option requires %d arguments') % (opt, nargs))
  1051.                 elif nargs == 1:
  1052.                     value = rargs.pop(0)
  1053.                 else:
  1054.                     value = tuple(rargs[0:nargs])
  1055.                     del rargs[0:nargs]
  1056.             else:
  1057.                 value = None
  1058.             option.process(opt, value, values, self)
  1059.             if stop:
  1060.                 break
  1061.                 continue
  1062.  
  1063.     
  1064.     def get_prog_name(self):
  1065.         if self.prog is None:
  1066.             return os.path.basename(sys.argv[0])
  1067.         return None.prog
  1068.  
  1069.     
  1070.     def expand_prog_name(self, s):
  1071.         return s.replace('%prog', self.get_prog_name())
  1072.  
  1073.     
  1074.     def get_description(self):
  1075.         return self.expand_prog_name(self.description)
  1076.  
  1077.     
  1078.     def exit(self, status = 0, msg = None):
  1079.         if msg:
  1080.             sys.stderr.write(msg)
  1081.         sys.exit(status)
  1082.  
  1083.     
  1084.     def error(self, msg):
  1085.         self.print_usage(sys.stderr)
  1086.         self.exit(2, '%s: error: %s\n' % (self.get_prog_name(), msg))
  1087.  
  1088.     
  1089.     def get_usage(self):
  1090.         if self.usage:
  1091.             return self.formatter.format_usage(self.expand_prog_name(self.usage))
  1092.         return None
  1093.  
  1094.     
  1095.     def print_usage(self, file = None):
  1096.         if self.usage:
  1097.             print >>file, self.get_usage()
  1098.  
  1099.     
  1100.     def get_version(self):
  1101.         if self.version:
  1102.             return self.expand_prog_name(self.version)
  1103.         return None
  1104.  
  1105.     
  1106.     def print_version(self, file = None):
  1107.         if self.version:
  1108.             print >>file, self.get_version()
  1109.  
  1110.     
  1111.     def format_option_help(self, formatter = None):
  1112.         if formatter is None:
  1113.             formatter = self.formatter
  1114.         formatter.store_option_strings(self)
  1115.         result = []
  1116.         result.append(formatter.format_heading(_('Options')))
  1117.         formatter.indent()
  1118.         if self.option_list:
  1119.             result.append(OptionContainer.format_option_help(self, formatter))
  1120.             result.append('\n')
  1121.         for group in self.option_groups:
  1122.             result.append(group.format_help(formatter))
  1123.             result.append('\n')
  1124.         
  1125.         formatter.dedent()
  1126.         return ''.join(result[:-1])
  1127.  
  1128.     
  1129.     def format_epilog(self, formatter):
  1130.         return formatter.format_epilog(self.epilog)
  1131.  
  1132.     
  1133.     def format_help(self, formatter = None):
  1134.         if formatter is None:
  1135.             formatter = self.formatter
  1136.         result = []
  1137.         if self.usage:
  1138.             result.append(self.get_usage() + '\n')
  1139.         if self.description:
  1140.             result.append(self.format_description(formatter) + '\n')
  1141.         result.append(self.format_option_help(formatter))
  1142.         result.append(self.format_epilog(formatter))
  1143.         return ''.join(result)
  1144.  
  1145.     
  1146.     def _get_encoding(self, file):
  1147.         encoding = getattr(file, 'encoding', None)
  1148.         if not encoding:
  1149.             encoding = sys.getdefaultencoding()
  1150.         return encoding
  1151.  
  1152.     
  1153.     def print_help(self, file = None):
  1154.         if file is None:
  1155.             file = sys.stdout
  1156.         encoding = self._get_encoding(file)
  1157.         file.write(self.format_help().encode(encoding, 'replace'))
  1158.  
  1159.  
  1160.  
  1161. def _match_abbrev(s, wordmap):
  1162.     if s in wordmap:
  1163.         return s
  1164.     possibilities = [ word for word in wordmap.keys() if word.startswith(s) ]
  1165.     if len(possibilities) == 1:
  1166.         return possibilities[0]
  1167.     if not None:
  1168.         raise BadOptionError(s)
  1169.     possibilities.sort()
  1170.     raise AmbiguousOptionError(s, possibilities)
  1171.  
  1172. make_option = Option
  1173.