home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_661 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  38.1 KB  |  1,235 lines

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