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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __version__ = '1.0'
  5. __all__ = [
  6.     'ArgumentParser',
  7.     'ArgumentError',
  8.     'Namespace',
  9.     'Action',
  10.     'FileType',
  11.     'HelpFormatter',
  12.     'RawDescriptionHelpFormatter',
  13.     'RawTextHelpFormatterArgumentDefaultsHelpFormatter']
  14. import copy as _copy
  15. import os as _os
  16. import re as _re
  17. import sys as _sys
  18. import textwrap as _textwrap
  19. from gettext import gettext as _
  20.  
  21. try:
  22.     _set = set
  23. except NameError:
  24.     from sets import Set as _set
  25.  
  26.  
  27. try:
  28.     _basestring = basestring
  29. except NameError:
  30.     _basestring = str
  31.  
  32.  
  33. try:
  34.     _sorted = sorted
  35. except NameError:
  36.     
  37.     def _sorted(iterable, reverse = False):
  38.         result = list(iterable)
  39.         result.sort()
  40.         if reverse:
  41.             result.reverse()
  42.         
  43.         return result
  44.  
  45.  
  46. SUPPRESS = '==SUPPRESS=='
  47. OPTIONAL = '?'
  48. ZERO_OR_MORE = '*'
  49. ONE_OR_MORE = '+'
  50. PARSER = '==PARSER=='
  51.  
  52. class _AttributeHolder(object):
  53.     
  54.     def __repr__(self):
  55.         type_name = type(self).__name__
  56.         arg_strings = []
  57.         for arg in self._get_args():
  58.             arg_strings.append(repr(arg))
  59.         
  60.         for name, value in self._get_kwargs():
  61.             arg_strings.append('%s=%r' % (name, value))
  62.         
  63.         return '%s(%s)' % (type_name, ', '.join(arg_strings))
  64.  
  65.     
  66.     def _get_kwargs(self):
  67.         return _sorted(self.__dict__.items())
  68.  
  69.     
  70.     def _get_args(self):
  71.         return []
  72.  
  73.  
  74.  
  75. def _ensure_value(namespace, name, value):
  76.     if getattr(namespace, name, None) is None:
  77.         setattr(namespace, name, value)
  78.     
  79.     return getattr(namespace, name)
  80.  
  81.  
  82. class HelpFormatter(object):
  83.     
  84.     def __init__(self, prog, indent_increment = 2, max_help_position = 24, width = None):
  85.         if width is None:
  86.             
  87.             try:
  88.                 width = int(_os.environ['COLUMNS'])
  89.             except (KeyError, ValueError):
  90.                 width = 80
  91.  
  92.             width -= 2
  93.         
  94.         self._prog = prog
  95.         self._indent_increment = indent_increment
  96.         self._max_help_position = max_help_position
  97.         self._width = width
  98.         self._current_indent = 0
  99.         self._level = 0
  100.         self._action_max_length = 0
  101.         self._root_section = self._Section(self, None)
  102.         self._current_section = self._root_section
  103.         self._whitespace_matcher = _re.compile('\\s+')
  104.         self._long_break_matcher = _re.compile('\\n\\n\\n+')
  105.  
  106.     
  107.     def _indent(self):
  108.         self._current_indent += self._indent_increment
  109.         self._level += 1
  110.  
  111.     
  112.     def _dedent(self):
  113.         self._current_indent -= self._indent_increment
  114.         self._level -= 1
  115.  
  116.     
  117.     class _Section(object):
  118.         
  119.         def __init__(self, formatter, parent, heading = None):
  120.             self.formatter = formatter
  121.             self.parent = parent
  122.             self.heading = heading
  123.             self.items = []
  124.  
  125.         
  126.         def format_help(self):
  127.             if self.parent is not None:
  128.                 self.formatter._indent()
  129.             
  130.             join = self.formatter._join_parts
  131.             for func, args in self.items:
  132.                 func(*args)
  133.             
  134.             item_help = []([ func(*args) for func, args in self.items ])
  135.             if not item_help:
  136.                 return ''
  137.             return join([
  138.                 '\n',
  139.                 heading,
  140.                 item_help,
  141.                 '\n'])
  142.  
  143.  
  144.     
  145.     def _add_item(self, func, args):
  146.         self._current_section.items.append((func, args))
  147.  
  148.     
  149.     def start_section(self, heading):
  150.         self._indent()
  151.         section = self._Section(self, self._current_section, heading)
  152.         self._add_item(section.format_help, [])
  153.         self._current_section = section
  154.  
  155.     
  156.     def end_section(self):
  157.         self._current_section = self._current_section.parent
  158.         self._dedent()
  159.  
  160.     
  161.     def add_text(self, text):
  162.         if text is not SUPPRESS and text is not None:
  163.             self._add_item(self._format_text, [
  164.                 text])
  165.         
  166.  
  167.     
  168.     def add_usage(self, usage, actions, groups, prefix = None):
  169.         if usage is not SUPPRESS:
  170.             args = (usage, actions, groups, prefix)
  171.             self._add_item(self._format_usage, args)
  172.         
  173.  
  174.     
  175.     def add_argument(self, action):
  176.         pass
  177.  
  178.     
  179.     def add_arguments(self, actions):
  180.         for action in actions:
  181.             self.add_argument(action)
  182.         
  183.  
  184.     
  185.     def format_help(self):
  186.         help = self._root_section.format_help() % dict(prog = self._prog)
  187.         if help:
  188.             help = self._long_break_matcher.sub('\n\n', help)
  189.             help = help.strip('\n') + '\n'
  190.         
  191.         return help
  192.  
  193.     
  194.     def _join_parts(self, part_strings):
  195.         return [](_[1])
  196.  
  197.     
  198.     def _format_usage(self, usage, actions, groups, prefix):
  199.         if prefix is None:
  200.             prefix = _('usage: ')
  201.         
  202.         if usage is None and not actions:
  203.             usage = '%(prog)s'
  204.         elif usage is None:
  205.             usage = '%(prog)s' % dict(prog = self._prog)
  206.             optionals = []
  207.             positionals = []
  208.             for action in actions:
  209.                 if action.option_strings:
  210.                     optionals.append(action)
  211.                     continue
  212.                 positionals.append(action)
  213.             
  214.             prefix_width = len(prefix) + len(usage) + 1
  215.             prefix_indent = self._current_indent + prefix_width
  216.             text_width = self._width - self._current_indent
  217.             format = self._format_actions_usage
  218.             action_usage = format(optionals + positionals, groups)
  219.             if prefix_width + len(action_usage) + 1 < text_width:
  220.                 usage = '%s %s' % (usage, action_usage)
  221.             else:
  222.                 optional_usage = format(optionals, groups)
  223.                 positional_usage = format(positionals, groups)
  224.                 indent = ' ' * prefix_indent
  225.                 parts = [
  226.                     usage,
  227.                     ' ']
  228.                 if optional_usage:
  229.                     parts.append(_textwrap.fill(optional_usage, text_width, initial_indent = indent, subsequent_indent = indent).lstrip())
  230.                 
  231.                 if positional_usage:
  232.                     part = _textwrap.fill(positional_usage, text_width, initial_indent = indent, subsequent_indent = indent).lstrip()
  233.                     if optional_usage:
  234.                         part = '\n' + indent + part
  235.                     
  236.                     parts.append(part)
  237.                 
  238.                 usage = ''.join(parts)
  239.         
  240.         return '%s%s\n\n' % (prefix, usage)
  241.  
  242.     
  243.     def _format_actions_usage(self, actions, groups):
  244.         group_actions = _set()
  245.         inserts = { }
  246.         for group in groups:
  247.             
  248.             try:
  249.                 start = actions.index(group._group_actions[0])
  250.             except ValueError:
  251.                 continue
  252.                 continue
  253.  
  254.             end = start + len(group._group_actions)
  255.             if actions[start:end] == group._group_actions:
  256.                 for action in group._group_actions:
  257.                     group_actions.add(action)
  258.                 
  259.                 if not group.required:
  260.                     inserts[start] = '['
  261.                     inserts[end] = ']'
  262.                 else:
  263.                     inserts[start] = '('
  264.                     inserts[end] = ')'
  265.                 for i in range(start + 1, end):
  266.                     inserts[i] = '|'
  267.                 
  268.         
  269.         parts = []
  270.         for i, action in enumerate(actions):
  271.             if action.help is SUPPRESS:
  272.                 parts.append(None)
  273.                 if inserts.get(i) == '|':
  274.                     inserts.pop(i)
  275.                 elif inserts.get(i + 1) == '|':
  276.                     inserts.pop(i + 1)
  277.                 
  278.             inserts.get(i) == '|'
  279.             if not action.option_strings:
  280.                 part = self._format_args(action, action.dest)
  281.                 if action in group_actions:
  282.                     if part[0] == '[' and part[-1] == ']':
  283.                         part = part[1:-1]
  284.                     
  285.                 
  286.                 parts.append(part)
  287.                 continue
  288.             option_string = action.option_strings[0]
  289.             if action.nargs == 0:
  290.                 part = '%s' % option_string
  291.             else:
  292.                 default = action.dest.upper()
  293.                 args_string = self._format_args(action, default)
  294.                 part = '%s %s' % (option_string, args_string)
  295.             if not (action.required) and action not in group_actions:
  296.                 part = '[%s]' % part
  297.             
  298.             parts.append(part)
  299.         
  300.         for i in _sorted(inserts, reverse = True):
  301.             parts[i:i] = [
  302.                 inserts[i]]
  303.         
  304.         text = [](_[1])
  305.         open = '[\\[(]'
  306.         close = '[\\])]'
  307.         text = _re.sub('(%s) ' % open, '\\1', text)
  308.         text = _re.sub(' (%s)' % close, '\\1', text)
  309.         text = _re.sub('%s *%s' % (open, close), '', text)
  310.         text = _re.sub('\\(([^|]*)\\)', '\\1', text)
  311.         text = text.strip()
  312.         return text
  313.  
  314.     
  315.     def _format_text(self, text):
  316.         text_width = self._width - self._current_indent
  317.         indent = ' ' * self._current_indent
  318.         return self._fill_text(text, text_width, indent) + '\n\n'
  319.  
  320.     
  321.     def _format_action(self, action):
  322.         help_position = min(self._action_max_length + 2, self._max_help_position)
  323.         help_width = self._width - help_position
  324.         action_width = help_position - self._current_indent - 2
  325.         action_header = self._format_action_invocation(action)
  326.         if not action.help:
  327.             tup = (self._current_indent, '', action_header)
  328.             action_header = '%*s%s\n' % tup
  329.         elif len(action_header) <= action_width:
  330.             tup = (self._current_indent, '', action_width, action_header)
  331.             action_header = '%*s%-*s  ' % tup
  332.             indent_first = 0
  333.         else:
  334.             tup = (self._current_indent, '', action_header)
  335.             action_header = '%*s%s\n' % tup
  336.             indent_first = help_position
  337.         parts = [
  338.             action_header]
  339.         if action.help:
  340.             help_text = self._expand_help(action)
  341.             help_lines = self._split_lines(help_text, help_width)
  342.             parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  343.             for line in help_lines[1:]:
  344.                 parts.append('%*s%s\n' % (help_position, '', line))
  345.             
  346.         elif not action_header.endswith('\n'):
  347.             parts.append('\n')
  348.         
  349.         for subaction in self._iter_indented_subactions(action):
  350.             parts.append(self._format_action(subaction))
  351.         
  352.         return self._join_parts(parts)
  353.  
  354.     
  355.     def _format_action_invocation(self, action):
  356.         if not action.option_strings:
  357.             (metavar,) = self._metavar_formatter(action, action.dest)(1)
  358.             return metavar
  359.         parts = []
  360.         if action.nargs == 0:
  361.             parts.extend(action.option_strings)
  362.         else:
  363.             default = action.dest.upper()
  364.             args_string = self._format_args(action, default)
  365.             for option_string in action.option_strings:
  366.                 parts.append('%s %s' % (option_string, args_string))
  367.             
  368.         return ', '.join(parts)
  369.  
  370.     
  371.     def _metavar_formatter(self, action, default_metavar):
  372.         if action.metavar is not None:
  373.             result = action.metavar
  374.         elif action.choices is not None:
  375.             choice_strs = [ str(choice) for choice in action.choices ]
  376.             result = '{%s}' % ','.join(choice_strs)
  377.         else:
  378.             result = default_metavar
  379.         
  380.         def format(tuple_size):
  381.             if isinstance(result, tuple):
  382.                 return result
  383.             return (result,) * tuple_size
  384.  
  385.         return format
  386.  
  387.     
  388.     def _format_args(self, action, default_metavar):
  389.         get_metavar = self._metavar_formatter(action, default_metavar)
  390.         if action.nargs is None:
  391.             result = '%s' % get_metavar(1)
  392.         elif action.nargs == OPTIONAL:
  393.             result = '[%s]' % get_metavar(1)
  394.         elif action.nargs == ZERO_OR_MORE:
  395.             result = '[%s [%s ...]]' % get_metavar(2)
  396.         elif action.nargs == ONE_OR_MORE:
  397.             result = '%s [%s ...]' % get_metavar(2)
  398.         elif action.nargs is PARSER:
  399.             result = '%s ...' % get_metavar(1)
  400.         else:
  401.             formats = [ '%s' for _ in range(action.nargs) ]
  402.             result = ' '.join(formats) % get_metavar(action.nargs)
  403.         return result
  404.  
  405.     
  406.     def _expand_help(self, action):
  407.         params = dict(vars(action), prog = self._prog)
  408.         for name in list(params):
  409.             if params[name] is SUPPRESS:
  410.                 del params[name]
  411.                 continue
  412.         
  413.         return self._get_help_string(action) % params
  414.  
  415.     
  416.     def _iter_indented_subactions(self, action):
  417.         
  418.         try:
  419.             get_subactions = action._get_subactions
  420.         except AttributeError:
  421.             pass
  422.  
  423.         self._indent()
  424.         for subaction in get_subactions():
  425.             yield subaction
  426.         
  427.         self._dedent()
  428.  
  429.     
  430.     def _split_lines(self, text, width):
  431.         text = self._whitespace_matcher.sub(' ', text).strip()
  432.         return _textwrap.wrap(text, width)
  433.  
  434.     
  435.     def _fill_text(self, text, width, indent):
  436.         text = self._whitespace_matcher.sub(' ', text).strip()
  437.         return _textwrap.fill(text, width, initial_indent = indent, subsequent_indent = indent)
  438.  
  439.     
  440.     def _get_help_string(self, action):
  441.         return action.help
  442.  
  443.  
  444.  
  445. class RawDescriptionHelpFormatter(HelpFormatter):
  446.     
  447.     def _fill_text(self, text, width, indent):
  448.         return []([ indent + line for line in text.splitlines(True) ])
  449.  
  450.  
  451.  
  452. class RawTextHelpFormatter(RawDescriptionHelpFormatter):
  453.     
  454.     def _split_lines(self, text, width):
  455.         return text.splitlines()
  456.  
  457.  
  458.  
  459. class ArgumentDefaultsHelpFormatter(HelpFormatter):
  460.     
  461.     def _get_help_string(self, action):
  462.         help = action.help
  463.         if '%(default)' not in action.help:
  464.             if action.default is not SUPPRESS:
  465.                 defaulting_nargs = [
  466.                     OPTIONAL,
  467.                     ZERO_OR_MORE]
  468.                 if action.option_strings or action.nargs in defaulting_nargs:
  469.                     help += ' (default: %(default)s)'
  470.                 
  471.             
  472.         
  473.         return help
  474.  
  475.  
  476.  
  477. def _get_action_name(argument):
  478.     if argument is None:
  479.         return None
  480.     if argument.option_strings:
  481.         return '/'.join(argument.option_strings)
  482.     if argument.metavar not in (None, SUPPRESS):
  483.         return argument.metavar
  484.     if argument.dest not in (None, SUPPRESS):
  485.         return argument.dest
  486.     return None
  487.  
  488.  
  489. class ArgumentError(Exception):
  490.     
  491.     def __init__(self, argument, message):
  492.         self.argument_name = _get_action_name(argument)
  493.         self.message = message
  494.  
  495.     
  496.     def __str__(self):
  497.         if self.argument_name is None:
  498.             format = '%(message)s'
  499.         else:
  500.             format = 'argument %(argument_name)s: %(message)s'
  501.         return format % dict(message = self.message, argument_name = self.argument_name)
  502.  
  503.  
  504.  
  505. class Action(_AttributeHolder):
  506.     
  507.     def __init__(self, option_strings, dest, nargs = None, const = None, default = None, type = None, choices = None, required = False, help = None, metavar = None):
  508.         self.option_strings = option_strings
  509.         self.dest = dest
  510.         self.nargs = nargs
  511.         self.const = const
  512.         self.default = default
  513.         self.type = type
  514.         self.choices = choices
  515.         self.required = required
  516.         self.help = help
  517.         self.metavar = metavar
  518.  
  519.     
  520.     def _get_kwargs(self):
  521.         names = [
  522.             'option_strings',
  523.             'dest',
  524.             'nargs',
  525.             'const',
  526.             'default',
  527.             'type',
  528.             'choices',
  529.             'help',
  530.             'metavar']
  531.         return [ (name, getattr(self, name)) for name in names ]
  532.  
  533.     
  534.     def __call__(self, parser, namespace, values, option_string = None):
  535.         raise NotImplementedError(_('.__call__() not defined'))
  536.  
  537.  
  538.  
  539. class _StoreAction(Action):
  540.     
  541.     def __init__(self, option_strings, dest, nargs = None, const = None, default = None, type = None, choices = None, required = False, help = None, metavar = None):
  542.         if nargs == 0:
  543.             raise ValueError('nargs must be > 0')
  544.         nargs == 0
  545.         if const is not None and nargs != OPTIONAL:
  546.             raise ValueError('nargs must be %r to supply const' % OPTIONAL)
  547.         nargs != OPTIONAL
  548.         super(_StoreAction, self).__init__(option_strings = option_strings, dest = dest, nargs = nargs, const = const, default = default, type = type, choices = choices, required = required, help = help, metavar = metavar)
  549.  
  550.     
  551.     def __call__(self, parser, namespace, values, option_string = None):
  552.         setattr(namespace, self.dest, values)
  553.  
  554.  
  555.  
  556. class _StoreConstAction(Action):
  557.     
  558.     def __init__(self, option_strings, dest, const, default = None, required = False, help = None, metavar = None):
  559.         super(_StoreConstAction, self).__init__(option_strings = option_strings, dest = dest, nargs = 0, const = const, default = default, required = required, help = help)
  560.  
  561.     
  562.     def __call__(self, parser, namespace, values, option_string = None):
  563.         setattr(namespace, self.dest, self.const)
  564.  
  565.  
  566.  
  567. class _StoreTrueAction(_StoreConstAction):
  568.     
  569.     def __init__(self, option_strings, dest, default = False, required = False, help = None):
  570.         super(_StoreTrueAction, self).__init__(option_strings = option_strings, dest = dest, const = True, default = default, required = required, help = help)
  571.  
  572.  
  573.  
  574. class _StoreFalseAction(_StoreConstAction):
  575.     
  576.     def __init__(self, option_strings, dest, default = True, required = False, help = None):
  577.         super(_StoreFalseAction, self).__init__(option_strings = option_strings, dest = dest, const = False, default = default, required = required, help = help)
  578.  
  579.  
  580.  
  581. class _AppendAction(Action):
  582.     
  583.     def __init__(self, option_strings, dest, nargs = None, const = None, default = None, type = None, choices = None, required = False, help = None, metavar = None):
  584.         if nargs == 0:
  585.             raise ValueError('nargs must be > 0')
  586.         nargs == 0
  587.         if const is not None and nargs != OPTIONAL:
  588.             raise ValueError('nargs must be %r to supply const' % OPTIONAL)
  589.         nargs != OPTIONAL
  590.         super(_AppendAction, self).__init__(option_strings = option_strings, dest = dest, nargs = nargs, const = const, default = default, type = type, choices = choices, required = required, help = help, metavar = metavar)
  591.  
  592.     
  593.     def __call__(self, parser, namespace, values, option_string = None):
  594.         items = _copy.copy(_ensure_value(namespace, self.dest, []))
  595.         items.append(values)
  596.         setattr(namespace, self.dest, items)
  597.  
  598.  
  599.  
  600. class _AppendConstAction(Action):
  601.     
  602.     def __init__(self, option_strings, dest, const, default = None, required = False, help = None, metavar = None):
  603.         super(_AppendConstAction, self).__init__(option_strings = option_strings, dest = dest, nargs = 0, const = const, default = default, required = required, help = help, metavar = metavar)
  604.  
  605.     
  606.     def __call__(self, parser, namespace, values, option_string = None):
  607.         items = _copy.copy(_ensure_value(namespace, self.dest, []))
  608.         items.append(self.const)
  609.         setattr(namespace, self.dest, items)
  610.  
  611.  
  612.  
  613. class _CountAction(Action):
  614.     
  615.     def __init__(self, option_strings, dest, default = None, required = False, help = None):
  616.         super(_CountAction, self).__init__(option_strings = option_strings, dest = dest, nargs = 0, default = default, required = required, help = help)
  617.  
  618.     
  619.     def __call__(self, parser, namespace, values, option_string = None):
  620.         new_count = _ensure_value(namespace, self.dest, 0) + 1
  621.         setattr(namespace, self.dest, new_count)
  622.  
  623.  
  624.  
  625. class _HelpAction(Action):
  626.     
  627.     def __init__(self, option_strings, dest = SUPPRESS, default = SUPPRESS, help = None):
  628.         super(_HelpAction, self).__init__(option_strings = option_strings, dest = dest, default = default, nargs = 0, help = help)
  629.  
  630.     
  631.     def __call__(self, parser, namespace, values, option_string = None):
  632.         parser.print_help()
  633.         parser.exit()
  634.  
  635.  
  636.  
  637. class _VersionAction(Action):
  638.     
  639.     def __init__(self, option_strings, dest = SUPPRESS, default = SUPPRESS, help = None):
  640.         super(_VersionAction, self).__init__(option_strings = option_strings, dest = dest, default = default, nargs = 0, help = help)
  641.  
  642.     
  643.     def __call__(self, parser, namespace, values, option_string = None):
  644.         parser.print_version()
  645.         parser.exit()
  646.  
  647.  
  648.  
  649. class _SubParsersAction(Action):
  650.     
  651.     class _ChoicesPseudoAction(Action):
  652.         
  653.         def __init__(self, name, help):
  654.             sup = super(_SubParsersAction._ChoicesPseudoAction, self)
  655.             sup.__init__(option_strings = [], dest = name, help = help)
  656.  
  657.  
  658.     
  659.     def __init__(self, option_strings, prog, parser_class, dest = SUPPRESS, help = None, metavar = None):
  660.         self._prog_prefix = prog
  661.         self._parser_class = parser_class
  662.         self._name_parser_map = { }
  663.         self._choices_actions = []
  664.         super(_SubParsersAction, self).__init__(option_strings = option_strings, dest = dest, nargs = PARSER, choices = self._name_parser_map, help = help, metavar = metavar)
  665.  
  666.     
  667.     def add_parser(self, name, **kwargs):
  668.         if kwargs.get('prog') is None:
  669.             kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
  670.         
  671.         if 'help' in kwargs:
  672.             help = kwargs.pop('help')
  673.             choice_action = self._ChoicesPseudoAction(name, help)
  674.             self._choices_actions.append(choice_action)
  675.         
  676.         parser = self._parser_class(**kwargs)
  677.         self._name_parser_map[name] = parser
  678.         return parser
  679.  
  680.     
  681.     def _get_subactions(self):
  682.         return self._choices_actions
  683.  
  684.     
  685.     def __call__(self, parser, namespace, values, option_string = None):
  686.         parser_name = values[0]
  687.         arg_strings = values[1:]
  688.         if self.dest is not SUPPRESS:
  689.             setattr(namespace, self.dest, parser_name)
  690.         
  691.         
  692.         try:
  693.             parser = self._name_parser_map[parser_name]
  694.         except KeyError:
  695.             tup = (parser_name, ', '.join(self._name_parser_map))
  696.             msg = _('unknown parser %r (choices: %s)' % tup)
  697.             raise ArgumentError(self, msg)
  698.  
  699.         parser.parse_args(arg_strings, namespace)
  700.  
  701.  
  702.  
  703. class FileType(object):
  704.     
  705.     def __init__(self, mode = 'r', bufsize = None):
  706.         self._mode = mode
  707.         self._bufsize = bufsize
  708.  
  709.     
  710.     def __call__(self, string):
  711.         if string == '-':
  712.             if 'r' in self._mode:
  713.                 return _sys.stdin
  714.             if 'w' in self._mode:
  715.                 return _sys.stdout
  716.             msg = _('argument "-" with mode %r' % self._mode)
  717.             raise ValueError(msg)
  718.         string == '-'
  719.         if self._bufsize:
  720.             return open(string, self._mode, self._bufsize)
  721.         return open(string, self._mode)
  722.  
  723.     
  724.     def __repr__(self):
  725.         args = [
  726.             self._mode,
  727.             self._bufsize]
  728.         args_str = [](_[1])
  729.         return '%s(%s)' % (type(self).__name__, args_str)
  730.  
  731.  
  732.  
  733. class Namespace(_AttributeHolder):
  734.     
  735.     def __init__(self, **kwargs):
  736.         for name in kwargs:
  737.             setattr(self, name, kwargs[name])
  738.         
  739.  
  740.     
  741.     def __eq__(self, other):
  742.         return vars(self) == vars(other)
  743.  
  744.     
  745.     def __ne__(self, other):
  746.         return not (self == other)
  747.  
  748.  
  749.  
  750. class _ActionsContainer(object):
  751.     
  752.     def __init__(self, description, prefix_chars, argument_default, conflict_handler):
  753.         super(_ActionsContainer, self).__init__()
  754.         self.description = description
  755.         self.argument_default = argument_default
  756.         self.prefix_chars = prefix_chars
  757.         self.conflict_handler = conflict_handler
  758.         self._registries = { }
  759.         self.register('action', None, _StoreAction)
  760.         self.register('action', 'store', _StoreAction)
  761.         self.register('action', 'store_const', _StoreConstAction)
  762.         self.register('action', 'store_true', _StoreTrueAction)
  763.         self.register('action', 'store_false', _StoreFalseAction)
  764.         self.register('action', 'append', _AppendAction)
  765.         self.register('action', 'append_const', _AppendConstAction)
  766.         self.register('action', 'count', _CountAction)
  767.         self.register('action', 'help', _HelpAction)
  768.         self.register('action', 'version', _VersionAction)
  769.         self.register('action', 'parsers', _SubParsersAction)
  770.         self._get_handler()
  771.         self._actions = []
  772.         self._option_string_actions = { }
  773.         self._action_groups = []
  774.         self._mutually_exclusive_groups = []
  775.         self._defaults = { }
  776.         self._negative_number_matcher = _re.compile('^-\\d+|-\\d*.\\d+$')
  777.         self._has_negative_number_optionals = []
  778.  
  779.     
  780.     def register(self, registry_name, value, object):
  781.         registry = self._registries.setdefault(registry_name, { })
  782.         registry[value] = object
  783.  
  784.     
  785.     def _registry_get(self, registry_name, value, default = None):
  786.         return self._registries[registry_name].get(value, default)
  787.  
  788.     
  789.     def set_defaults(self, **kwargs):
  790.         self._defaults.update(kwargs)
  791.         for action in self._actions:
  792.             if action.dest in kwargs:
  793.                 action.default = kwargs[action.dest]
  794.                 continue
  795.         
  796.  
  797.     
  798.     def add_argument(self, *args, **kwargs):
  799.         chars = self.prefix_chars
  800.         if (not args or len(args) == 1) and args[0][0] not in chars:
  801.             kwargs = self._get_positional_kwargs(*args, **kwargs)
  802.         else:
  803.             kwargs = self._get_optional_kwargs(*args, **kwargs)
  804.         if 'default' not in kwargs:
  805.             dest = kwargs['dest']
  806.             if dest in self._defaults:
  807.                 kwargs['default'] = self._defaults[dest]
  808.             elif self.argument_default is not None:
  809.                 kwargs['default'] = self.argument_default
  810.             
  811.         
  812.         action_class = self._pop_action_class(kwargs)
  813.         action = action_class(**kwargs)
  814.         return self._add_action(action)
  815.  
  816.     
  817.     def add_argument_group(self, *args, **kwargs):
  818.         group = _ArgumentGroup(self, *args, **kwargs)
  819.         self._action_groups.append(group)
  820.         return group
  821.  
  822.     
  823.     def add_mutually_exclusive_group(self, **kwargs):
  824.         group = _MutuallyExclusiveGroup(self, **kwargs)
  825.         self._mutually_exclusive_groups.append(group)
  826.         return group
  827.  
  828.     
  829.     def _add_action(self, action):
  830.         self._check_conflict(action)
  831.         self._actions.append(action)
  832.         action.container = self
  833.         for option_string in action.option_strings:
  834.             self._option_string_actions[option_string] = action
  835.         
  836.         for option_string in action.option_strings:
  837.             if self._negative_number_matcher.match(option_string):
  838.                 if not self._has_negative_number_optionals:
  839.                     self._has_negative_number_optionals.append(True)
  840.                 
  841.             self._has_negative_number_optionals
  842.         
  843.         return action
  844.  
  845.     
  846.     def _remove_action(self, action):
  847.         self._actions.remove(action)
  848.  
  849.     
  850.     def _add_container_actions(self, container):
  851.         title_group_map = { }
  852.         for group in self._action_groups:
  853.             if group.title in title_group_map:
  854.                 msg = _('cannot merge actions - two groups are named %r')
  855.                 raise ValueError(msg % group.title)
  856.             group.title in title_group_map
  857.             title_group_map[group.title] = group
  858.         
  859.         group_map = { }
  860.         for group in container._action_groups:
  861.             if group.title not in title_group_map:
  862.                 title_group_map[group.title] = self.add_argument_group(title = group.title, description = group.description, conflict_handler = group.conflict_handler)
  863.             
  864.             for action in group._group_actions:
  865.                 group_map[action] = title_group_map[group.title]
  866.             
  867.         
  868.         for action in container._actions:
  869.             group_map.get(action, self)._add_action(action)
  870.         
  871.  
  872.     
  873.     def _get_positional_kwargs(self, dest, **kwargs):
  874.         if 'required' in kwargs:
  875.             msg = _("'required' is an invalid argument for positionals")
  876.             raise TypeError(msg)
  877.         'required' in kwargs
  878.         if kwargs.get('nargs') not in [
  879.             OPTIONAL,
  880.             ZERO_OR_MORE]:
  881.             kwargs['required'] = True
  882.         
  883.         if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
  884.             kwargs['required'] = True
  885.         
  886.         return dict(kwargs, dest = dest, option_strings = [])
  887.  
  888.     
  889.     def _get_optional_kwargs(self, *args, **kwargs):
  890.         option_strings = []
  891.         long_option_strings = []
  892.         for option_string in args:
  893.             if len(option_string) < 2:
  894.                 msg = _('invalid option string %r: must be at least two characters long')
  895.                 raise ValueError(msg % option_string)
  896.             len(option_string) < 2
  897.             if option_string[0] not in self.prefix_chars:
  898.                 msg = _('invalid option string %r: must start with a character %r')
  899.                 tup = (option_string, self.prefix_chars)
  900.                 raise ValueError(msg % tup)
  901.             option_string[0] not in self.prefix_chars
  902.             if not _set(option_string) - _set(self.prefix_chars):
  903.                 msg = _('invalid option string %r: must contain characters other than %r')
  904.                 tup = (option_string, self.prefix_chars)
  905.                 raise ValueError(msg % tup)
  906.             _set(option_string) - _set(self.prefix_chars)
  907.             option_strings.append(option_string)
  908.             if option_string[0] in self.prefix_chars:
  909.                 if option_string[1] in self.prefix_chars:
  910.                     long_option_strings.append(option_string)
  911.                 
  912.             option_string[1] in self.prefix_chars
  913.         
  914.         dest = kwargs.pop('dest', None)
  915.         if dest is None:
  916.             if long_option_strings:
  917.                 dest_option_string = long_option_strings[0]
  918.             else:
  919.                 dest_option_string = option_strings[0]
  920.             dest = dest_option_string.lstrip(self.prefix_chars)
  921.             dest = dest.replace('-', '_')
  922.         
  923.         return dict(kwargs, dest = dest, option_strings = option_strings)
  924.  
  925.     
  926.     def _pop_action_class(self, kwargs, default = None):
  927.         action = kwargs.pop('action', default)
  928.         return self._registry_get('action', action, action)
  929.  
  930.     
  931.     def _get_handler(self):
  932.         handler_func_name = '_handle_conflict_%s' % self.conflict_handler
  933.         
  934.         try:
  935.             return getattr(self, handler_func_name)
  936.         except AttributeError:
  937.             msg = _('invalid conflict_resolution value: %r')
  938.             raise ValueError(msg % self.conflict_handler)
  939.  
  940.  
  941.     
  942.     def _check_conflict(self, action):
  943.         confl_optionals = []
  944.         for option_string in action.option_strings:
  945.             if option_string in self._option_string_actions:
  946.                 confl_optional = self._option_string_actions[option_string]
  947.                 confl_optionals.append((option_string, confl_optional))
  948.                 continue
  949.         
  950.         if confl_optionals:
  951.             conflict_handler = self._get_handler()
  952.             conflict_handler(action, confl_optionals)
  953.         
  954.  
  955.     
  956.     def _handle_conflict_error(self, action, conflicting_actions):
  957.         message = _('conflicting option string(s): %s')
  958.         conflict_string = []([ option_string for option_string, action in conflicting_actions ])
  959.         raise ArgumentError(action, message % conflict_string)
  960.  
  961.     
  962.     def _handle_conflict_resolve(self, action, conflicting_actions):
  963.         for option_string, action in conflicting_actions:
  964.             action.option_strings.remove(option_string)
  965.             self._option_string_actions.pop(option_string, None)
  966.             if not action.option_strings:
  967.                 action.container._remove_action(action)
  968.                 continue
  969.         
  970.  
  971.  
  972.  
  973. class _ArgumentGroup(_ActionsContainer):
  974.     
  975.     def __init__(self, container, title = None, description = None, **kwargs):
  976.         update = kwargs.setdefault
  977.         update('conflict_handler', container.conflict_handler)
  978.         update('prefix_chars', container.prefix_chars)
  979.         update('argument_default', container.argument_default)
  980.         super_init = super(_ArgumentGroup, self).__init__
  981.         super_init(description = description, **kwargs)
  982.         self.title = title
  983.         self._group_actions = []
  984.         self._registries = container._registries
  985.         self._actions = container._actions
  986.         self._option_string_actions = container._option_string_actions
  987.         self._defaults = container._defaults
  988.         self._has_negative_number_optionals = container._has_negative_number_optionals
  989.  
  990.     
  991.     def _add_action(self, action):
  992.         action = super(_ArgumentGroup, self)._add_action(action)
  993.         self._group_actions.append(action)
  994.         return action
  995.  
  996.     
  997.     def _remove_action(self, action):
  998.         super(_ArgumentGroup, self)._remove_action(action)
  999.         self._group_actions.remove(action)
  1000.  
  1001.  
  1002.  
  1003. class _MutuallyExclusiveGroup(_ArgumentGroup):
  1004.     
  1005.     def __init__(self, container, required = False):
  1006.         super(_MutuallyExclusiveGroup, self).__init__(container)
  1007.         self.required = required
  1008.         self._container = container
  1009.  
  1010.     
  1011.     def _add_action(self, action):
  1012.         if action.required:
  1013.             msg = _('mutually exclusive arguments must be optional')
  1014.             raise ValueError(msg)
  1015.         action.required
  1016.         action = self._container._add_action(action)
  1017.         self._group_actions.append(action)
  1018.         return action
  1019.  
  1020.     
  1021.     def _remove_action(self, action):
  1022.         self._container._remove_action(action)
  1023.         self._group_actions.remove(action)
  1024.  
  1025.  
  1026.  
  1027. class ArgumentParser(_AttributeHolder, _ActionsContainer):
  1028.     
  1029.     def __init__(self, prog = None, usage = None, description = None, epilog = None, version = None, parents = [], formatter_class = HelpFormatter, prefix_chars = '-', fromfile_prefix_chars = None, argument_default = None, conflict_handler = 'error', add_help = True):
  1030.         superinit = super(ArgumentParser, self).__init__
  1031.         superinit(description = description, prefix_chars = prefix_chars, argument_default = argument_default, conflict_handler = conflict_handler)
  1032.         if prog is None:
  1033.             prog = _os.path.basename(_sys.argv[0])
  1034.         
  1035.         self.prog = prog
  1036.         self.usage = usage
  1037.         self.epilog = epilog
  1038.         self.version = version
  1039.         self.formatter_class = formatter_class
  1040.         self.fromfile_prefix_chars = fromfile_prefix_chars
  1041.         self.add_help = add_help
  1042.         add_group = self.add_argument_group
  1043.         self._positionals = add_group(_('positional arguments'))
  1044.         self._optionals = add_group(_('optional arguments'))
  1045.         self._subparsers = None
  1046.         
  1047.         def identity(string):
  1048.             return string
  1049.  
  1050.         self.register('type', None, identity)
  1051.         if self.add_help:
  1052.             self.add_argument('-h', '--help', action = 'help', default = SUPPRESS, help = _('show this help message and exit'))
  1053.         
  1054.         if self.version:
  1055.             self.add_argument('-v', '--version', action = 'version', default = SUPPRESS, help = _("show program's version number and exit"))
  1056.         
  1057.         for parent in parents:
  1058.             self._add_container_actions(parent)
  1059.             
  1060.             try:
  1061.                 defaults = parent._defaults
  1062.             except AttributeError:
  1063.                 continue
  1064.  
  1065.             self._defaults.update(defaults)
  1066.         
  1067.  
  1068.     
  1069.     def _get_kwargs(self):
  1070.         names = [
  1071.             'prog',
  1072.             'usage',
  1073.             'description',
  1074.             'version',
  1075.             'formatter_class',
  1076.             'conflict_handler',
  1077.             'add_help']
  1078.         return [ (name, getattr(self, name)) for name in names ]
  1079.  
  1080.     
  1081.     def add_subparsers(self, **kwargs):
  1082.         if self._subparsers is not None:
  1083.             self.error(_('cannot have multiple subparser arguments'))
  1084.         
  1085.         kwargs.setdefault('parser_class', type(self))
  1086.         if 'title' in kwargs or 'description' in kwargs:
  1087.             title = _(kwargs.pop('title', 'subcommands'))
  1088.             description = _(kwargs.pop('description', None))
  1089.             self._subparsers = self.add_argument_group(title, description)
  1090.         else:
  1091.             self._subparsers = self._positionals
  1092.         if kwargs.get('prog') is None:
  1093.             formatter = self._get_formatter()
  1094.             positionals = self._get_positional_actions()
  1095.             groups = self._mutually_exclusive_groups
  1096.             formatter.add_usage(self.usage, positionals, groups, '')
  1097.             kwargs['prog'] = formatter.format_help().strip()
  1098.         
  1099.         parsers_class = self._pop_action_class(kwargs, 'parsers')
  1100.         action = parsers_class(option_strings = [], **kwargs)
  1101.         self._subparsers._add_action(action)
  1102.         return action
  1103.  
  1104.     
  1105.     def _add_action(self, action):
  1106.         if action.option_strings:
  1107.             self._optionals._add_action(action)
  1108.         else:
  1109.             self._positionals._add_action(action)
  1110.         return action
  1111.  
  1112.     
  1113.     def _get_optional_actions(self):
  1114.         return _[1]
  1115.  
  1116.     
  1117.     def _get_positional_actions(self):
  1118.         return _[1]
  1119.  
  1120.     
  1121.     def parse_args(self, args = None, namespace = None):
  1122.         (args, argv) = self.parse_known_args(args, namespace)
  1123.         if argv:
  1124.             msg = _('unrecognized arguments: %s')
  1125.             self.error(msg % ' '.join(argv))
  1126.         
  1127.         return args
  1128.  
  1129.     
  1130.     def parse_known_args(self, args = None, namespace = None):
  1131.         if args is None:
  1132.             args = _sys.argv[1:]
  1133.         
  1134.         if namespace is None:
  1135.             namespace = Namespace()
  1136.         
  1137.         for action in self._actions:
  1138.             if action.dest is not SUPPRESS:
  1139.                 if not hasattr(namespace, action.dest):
  1140.                     if action.default is not SUPPRESS:
  1141.                         default = action.default
  1142.                         if isinstance(action.default, _basestring):
  1143.                             default = self._get_value(action, default)
  1144.                         
  1145.                         setattr(namespace, action.dest, default)
  1146.                     
  1147.                 
  1148.             hasattr(namespace, action.dest)
  1149.         
  1150.         for dest in self._defaults:
  1151.             if not hasattr(namespace, dest):
  1152.                 setattr(namespace, dest, self._defaults[dest])
  1153.                 continue
  1154.         
  1155.         
  1156.         try:
  1157.             return self._parse_known_args(args, namespace)
  1158.         except ArgumentError:
  1159.             err = _sys.exc_info()[1]
  1160.             self.error(str(err))
  1161.  
  1162.  
  1163.     
  1164.     def _parse_known_args(self, arg_strings, namespace):
  1165.         if self.fromfile_prefix_chars is not None:
  1166.             arg_strings = self._read_args_from_files(arg_strings)
  1167.         
  1168.         action_conflicts = { }
  1169.         for mutex_group in self._mutually_exclusive_groups:
  1170.             group_actions = mutex_group._group_actions
  1171.             for i, mutex_action in enumerate(mutex_group._group_actions):
  1172.                 conflicts = action_conflicts.setdefault(mutex_action, [])
  1173.                 conflicts.extend(group_actions[:i])
  1174.                 conflicts.extend(group_actions[i + 1:])
  1175.             
  1176.         
  1177.         option_string_indices = { }
  1178.         arg_string_pattern_parts = []
  1179.         arg_strings_iter = iter(arg_strings)
  1180.         for i, arg_string in enumerate(arg_strings_iter):
  1181.             if arg_string == '--':
  1182.                 arg_string_pattern_parts.append('-')
  1183.                 for arg_string in arg_strings_iter:
  1184.                     arg_string_pattern_parts.append('A')
  1185.                 
  1186.             option_tuple = self._parse_optional(arg_string)
  1187.             if option_tuple is None:
  1188.                 pattern = 'A'
  1189.             else:
  1190.                 option_string_indices[i] = option_tuple
  1191.                 pattern = 'O'
  1192.             arg_string_pattern_parts.append(pattern)
  1193.         
  1194.         arg_strings_pattern = ''.join(arg_string_pattern_parts)
  1195.         seen_actions = _set()
  1196.         seen_non_default_actions = _set()
  1197.         
  1198.         def take_action(action, argument_strings, option_string = (None, None, None, None, None)):
  1199.             seen_actions.add(action)
  1200.             argument_values = self._get_values(action, argument_strings)
  1201.             if argument_values is not action.default:
  1202.                 seen_non_default_actions.add(action)
  1203.                 for conflict_action in action_conflicts.get(action, []):
  1204.                     if conflict_action in seen_non_default_actions:
  1205.                         msg = _('not allowed with argument %s')
  1206.                         action_name = _get_action_name(conflict_action)
  1207.                         raise ArgumentError(action, msg % action_name)
  1208.                     conflict_action in seen_non_default_actions
  1209.                 
  1210.             
  1211.             if argument_values is not SUPPRESS:
  1212.                 action(self, namespace, argument_values, option_string)
  1213.             
  1214.  
  1215.         
  1216.         def consume_optional(start_index):
  1217.             option_tuple = option_string_indices[start_index]
  1218.             (action, option_string, explicit_arg) = option_tuple
  1219.             match_argument = self._match_argument
  1220.             action_tuples = []
  1221.             while True:
  1222.                 if action is None:
  1223.                     extras.append(arg_strings[start_index])
  1224.                     return start_index + 1
  1225.                 if explicit_arg is not None:
  1226.                     arg_count = match_argument(action, 'A')
  1227.                     chars = self.prefix_chars
  1228.                     if arg_count == 0 and option_string[1] not in chars:
  1229.                         action_tuples.append((action, [], option_string))
  1230.                         for char in self.prefix_chars:
  1231.                             option_string = char + explicit_arg[0]
  1232.                             if not explicit_arg[1:]:
  1233.                                 pass
  1234.                             explicit_arg = None
  1235.                             optionals_map = self._option_string_actions
  1236.                             if option_string in optionals_map:
  1237.                                 action = optionals_map[option_string]
  1238.                                 break
  1239.                                 continue
  1240.                             action is None
  1241.                         else:
  1242.                             msg = _('ignored explicit argument %r')
  1243.                             raise ArgumentError(action, msg % explicit_arg)
  1244.                     if arg_count == 1:
  1245.                         stop = start_index + 1
  1246.                         args = [
  1247.                             explicit_arg]
  1248.                         action_tuples.append((action, args, option_string))
  1249.                         break
  1250.                     else:
  1251.                         msg = _('ignored explicit argument %r')
  1252.                         raise ArgumentError(action, msg % explicit_arg)
  1253.                 arg_count == 1
  1254.                 start = start_index + 1
  1255.                 selected_patterns = arg_strings_pattern[start:]
  1256.                 arg_count = match_argument(action, selected_patterns)
  1257.                 stop = start + arg_count
  1258.                 args = arg_strings[start:stop]
  1259.                 action_tuples.append((action, args, option_string))
  1260.                 break
  1261.             for action, args, option_string in action_tuples:
  1262.                 take_action(action, args, option_string)
  1263.             
  1264.             return stop
  1265.  
  1266.         positionals = self._get_positional_actions()
  1267.         
  1268.         def consume_positionals(start_index):
  1269.             match_partial = self._match_arguments_partial
  1270.             selected_pattern = arg_strings_pattern[start_index:]
  1271.             arg_counts = match_partial(positionals, selected_pattern)
  1272.             for action, arg_count in zip(positionals, arg_counts):
  1273.                 args = arg_strings[start_index:start_index + arg_count]
  1274.                 start_index += arg_count
  1275.                 take_action(action, args)
  1276.             
  1277.             positionals[:] = positionals[len(arg_counts):]
  1278.             return start_index
  1279.  
  1280.         extras = []
  1281.         start_index = 0
  1282.         if option_string_indices:
  1283.             max_option_string_index = max(option_string_indices)
  1284.         else:
  1285.             max_option_string_index = -1
  1286.         for index in option_string_indices:
  1287.             if index >= start_index:
  1288.                 continue
  1289.             _[1][index]
  1290.             next_option_string_index = [](_[1])
  1291.             if start_index not in option_string_indices:
  1292.                 strings = arg_strings[start_index:next_option_string_index]
  1293.                 extras.extend(strings)
  1294.                 start_index = next_option_string_index
  1295.             
  1296.             start_index = consume_optional(start_index)
  1297.         stop_index = consume_positionals(start_index)
  1298.         extras.extend(arg_strings[stop_index:])
  1299.         if positionals:
  1300.             self.error(_('too few arguments'))
  1301.         
  1302.         for action in self._actions:
  1303.             if action.required:
  1304.                 if action not in seen_actions:
  1305.                     name = _get_action_name(action)
  1306.                     self.error(_('argument %s is required') % name)
  1307.                 
  1308.             action not in seen_actions
  1309.         
  1310.         for group in self._mutually_exclusive_groups:
  1311.             if group.required:
  1312.                 for action in group._group_actions:
  1313.                     if action in seen_non_default_actions:
  1314.                         break
  1315.                         continue
  1316.                 else:
  1317.                     names = _[2]
  1318.                     msg = _('one of the arguments %s is required')
  1319.         
  1320.         return (namespace, extras)
  1321.  
  1322.     
  1323.     def _read_args_from_files(self, arg_strings):
  1324.         new_arg_strings = []
  1325.         for arg_string in arg_strings:
  1326.             if arg_string[0] not in self.fromfile_prefix_chars:
  1327.                 new_arg_strings.append(arg_string)
  1328.                 continue
  1329.             
  1330.             try:
  1331.                 args_file = open(arg_string[1:])
  1332.                 
  1333.                 try:
  1334.                     arg_strings = args_file.read().splitlines()
  1335.                     arg_strings = self._read_args_from_files(arg_strings)
  1336.                     new_arg_strings.extend(arg_strings)
  1337.                 finally:
  1338.                     args_file.close()
  1339.  
  1340.             continue
  1341.             except IOError:
  1342.                 err = _sys.exc_info()[1]
  1343.                 self.error(str(err))
  1344.                 continue
  1345.             
  1346.  
  1347.         
  1348.         return new_arg_strings
  1349.  
  1350.     
  1351.     def _match_argument(self, action, arg_strings_pattern):
  1352.         nargs_pattern = self._get_nargs_pattern(action)
  1353.         match = _re.match(nargs_pattern, arg_strings_pattern)
  1354.         if match is None:
  1355.             nargs_errors = {
  1356.                 None: _('expected one argument'),
  1357.                 OPTIONAL: _('expected at most one argument'),
  1358.                 ONE_OR_MORE: _('expected at least one argument') }
  1359.             default = _('expected %s argument(s)') % action.nargs
  1360.             msg = nargs_errors.get(action.nargs, default)
  1361.             raise ArgumentError(action, msg)
  1362.         match is None
  1363.         return len(match.group(1))
  1364.  
  1365.     
  1366.     def _match_arguments_partial(self, actions, arg_strings_pattern):
  1367.         result = []
  1368.         for i in range(len(actions), 0, -1):
  1369.             actions_slice = actions[:i]
  1370.             pattern = []([ self._get_nargs_pattern(action) for action in actions_slice ])
  1371.             match = _re.match(pattern, arg_strings_pattern)
  1372.             if match is not None:
  1373.                 []([ len(string) for string in match.groups() ])
  1374.                 break
  1375.                 continue
  1376.             []
  1377.         
  1378.         return result
  1379.  
  1380.     
  1381.     def _parse_optional(self, arg_string):
  1382.         if not arg_string:
  1383.             return None
  1384.         if arg_string[0] not in self.prefix_chars:
  1385.             return None
  1386.         if not arg_string.strip('-'):
  1387.             return None
  1388.         if arg_string in self._option_string_actions:
  1389.             action = self._option_string_actions[arg_string]
  1390.             return (action, arg_string, None)
  1391.         option_tuples = self._get_option_tuples(arg_string)
  1392.         if len(option_tuples) > 1:
  1393.             options = []([ option_string for action, option_string, explicit_arg in option_tuples ])
  1394.             tup = (arg_string, options)
  1395.             self.error(_('ambiguous option: %s could match %s') % tup)
  1396.         elif len(option_tuples) == 1:
  1397.             (option_tuple,) = option_tuples
  1398.             return option_tuple
  1399.         ', '.join
  1400.         if ' ' in arg_string:
  1401.             return None
  1402.         return (None, arg_string, None)
  1403.  
  1404.     
  1405.     def _get_option_tuples(self, option_string):
  1406.         result = []
  1407.         chars = self.prefix_chars
  1408.         if option_string[0] in chars and option_string[1] in chars:
  1409.             if '=' in option_string:
  1410.                 (option_prefix, explicit_arg) = option_string.split('=', 1)
  1411.             else:
  1412.                 option_prefix = option_string
  1413.                 explicit_arg = None
  1414.             for option_string in self._option_string_actions:
  1415.                 if option_string.startswith(option_prefix):
  1416.                     action = self._option_string_actions[option_string]
  1417.                     tup = (action, option_string, explicit_arg)
  1418.                     result.append(tup)
  1419.                     continue
  1420.             
  1421.         elif option_string[0] in chars and option_string[1] not in chars:
  1422.             option_prefix = option_string
  1423.             explicit_arg = None
  1424.             short_option_prefix = option_string[:2]
  1425.             short_explicit_arg = option_string[2:]
  1426.             for option_string in self._option_string_actions:
  1427.                 if option_string == short_option_prefix:
  1428.                     action = self._option_string_actions[option_string]
  1429.                     tup = (action, option_string, short_explicit_arg)
  1430.                     result.append(tup)
  1431.                     continue
  1432.                 if option_string.startswith(option_prefix):
  1433.                     action = self._option_string_actions[option_string]
  1434.                     tup = (action, option_string, explicit_arg)
  1435.                     result.append(tup)
  1436.                     continue
  1437.             
  1438.         else:
  1439.             self.error(_('unexpected option string: %s') % option_string)
  1440.         return result
  1441.  
  1442.     
  1443.     def _get_nargs_pattern(self, action):
  1444.         nargs = action.nargs
  1445.         if nargs is None:
  1446.             nargs_pattern = '(-*A-*)'
  1447.         elif nargs == OPTIONAL:
  1448.             nargs_pattern = '(-*A?-*)'
  1449.         elif nargs == ZERO_OR_MORE:
  1450.             nargs_pattern = '(-*[A-]*)'
  1451.         elif nargs == ONE_OR_MORE:
  1452.             nargs_pattern = '(-*A[A-]*)'
  1453.         elif nargs is PARSER:
  1454.             nargs_pattern = '(-*A[-AO]*)'
  1455.         else:
  1456.             nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
  1457.         if action.option_strings:
  1458.             nargs_pattern = nargs_pattern.replace('-*', '')
  1459.             nargs_pattern = nargs_pattern.replace('-', '')
  1460.         
  1461.         return nargs_pattern
  1462.  
  1463.     
  1464.     def _get_values(self, action, arg_strings):
  1465.         if not arg_strings and action.nargs == OPTIONAL:
  1466.             if action.option_strings:
  1467.                 value = action.const
  1468.             else:
  1469.                 value = action.default
  1470.             if isinstance(value, _basestring):
  1471.                 value = self._get_value(action, value)
  1472.                 self._check_value(action, value)
  1473.             
  1474.         elif not arg_strings and action.nargs == ZERO_OR_MORE and not (action.option_strings):
  1475.             if action.default is not None:
  1476.                 value = action.default
  1477.             else:
  1478.                 value = arg_strings
  1479.             self._check_value(action, value)
  1480.         elif len(arg_strings) == 1 and action.nargs in [
  1481.             None,
  1482.             OPTIONAL]:
  1483.             (arg_string,) = arg_strings
  1484.             value = self._get_value(action, arg_string)
  1485.             self._check_value(action, value)
  1486.         elif action.nargs is PARSER:
  1487.             value = [ self._get_value(action, v) for v in arg_strings ]
  1488.             self._check_value(action, value[0])
  1489.         else:
  1490.             value = [ self._get_value(action, v) for v in arg_strings ]
  1491.             for v in value:
  1492.                 self._check_value(action, v)
  1493.             
  1494.         return value
  1495.  
  1496.     
  1497.     def _get_value(self, action, arg_string):
  1498.         type_func = self._registry_get('type', action.type, action.type)
  1499.         if not hasattr(type_func, '__call__'):
  1500.             msg = _('%r is not callable')
  1501.             raise ArgumentError(action, msg % type_func)
  1502.         hasattr(type_func, '__call__')
  1503.         
  1504.         try:
  1505.             result = type_func(arg_string)
  1506.         except (TypeError, ValueError):
  1507.             name = getattr(action.type, '__name__', repr(action.type))
  1508.             msg = _('invalid %s value: %r')
  1509.             raise ArgumentError(action, msg % (name, arg_string))
  1510.  
  1511.         return result
  1512.  
  1513.     
  1514.     def _check_value(self, action, value):
  1515.         if action.choices is not None and value not in action.choices:
  1516.             tup = (value, ', '.join(map(repr, action.choices)))
  1517.             msg = _('invalid choice: %r (choose from %s)') % tup
  1518.             raise ArgumentError(action, msg)
  1519.         value not in action.choices
  1520.  
  1521.     
  1522.     def format_usage(self):
  1523.         formatter = self._get_formatter()
  1524.         formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
  1525.         return formatter.format_help()
  1526.  
  1527.     
  1528.     def format_help(self):
  1529.         formatter = self._get_formatter()
  1530.         formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
  1531.         formatter.add_text(self.description)
  1532.         for action_group in self._action_groups:
  1533.             formatter.start_section(action_group.title)
  1534.             formatter.add_text(action_group.description)
  1535.             formatter.add_arguments(action_group._group_actions)
  1536.             formatter.end_section()
  1537.         
  1538.         formatter.add_text(self.epilog)
  1539.         return formatter.format_help()
  1540.  
  1541.     
  1542.     def format_version(self):
  1543.         formatter = self._get_formatter()
  1544.         formatter.add_text(self.version)
  1545.         return formatter.format_help()
  1546.  
  1547.     
  1548.     def _get_formatter(self):
  1549.         return self.formatter_class(prog = self.prog)
  1550.  
  1551.     
  1552.     def print_usage(self, file = None):
  1553.         self._print_message(self.format_usage(), file)
  1554.  
  1555.     
  1556.     def print_help(self, file = None):
  1557.         self._print_message(self.format_help(), file)
  1558.  
  1559.     
  1560.     def print_version(self, file = None):
  1561.         self._print_message(self.format_version(), file)
  1562.  
  1563.     
  1564.     def _print_message(self, message, file = None):
  1565.         if message:
  1566.             if file is None:
  1567.                 file = _sys.stderr
  1568.             
  1569.             file.write(message)
  1570.         
  1571.  
  1572.     
  1573.     def exit(self, status = 0, message = None):
  1574.         if message:
  1575.             _sys.stderr.write(message)
  1576.         
  1577.         _sys.exit(status)
  1578.  
  1579.     
  1580.     def error(self, message):
  1581.         self.print_usage(_sys.stderr)
  1582.         self.exit(2, _('%s: error: %s\n') % (self.prog, message))
  1583.  
  1584.  
  1585.