external/argparse.py
author Eugen Sawin <sawine@me73.com>
Mon, 20 Feb 2012 15:10:53 +0100
changeset 0 a2f88c3bd824
permissions -rw-r--r--
Initial.
sawine@0
     1
# Author: Steven J. Bethard <steven.bethard@gmail.com>.
sawine@0
     2
sawine@0
     3
"""Command-line parsing library
sawine@0
     4
sawine@0
     5
This module is an optparse-inspired command-line parsing library that:
sawine@0
     6
sawine@0
     7
    - handles both optional and positional arguments
sawine@0
     8
    - produces highly informative usage messages
sawine@0
     9
    - supports parsers that dispatch to sub-parsers
sawine@0
    10
sawine@0
    11
The following is a simple usage example that sums integers from the
sawine@0
    12
command-line and writes the result to a file::
sawine@0
    13
sawine@0
    14
    parser = argparse.ArgumentParser(
sawine@0
    15
        description='sum the integers at the command line')
sawine@0
    16
    parser.add_argument(
sawine@0
    17
        'integers', metavar='int', nargs='+', type=int,
sawine@0
    18
        help='an integer to be summed')
sawine@0
    19
    parser.add_argument(
sawine@0
    20
        '--log', default=sys.stdout, type=argparse.FileType('w'),
sawine@0
    21
        help='the file where the sum should be written')
sawine@0
    22
    args = parser.parse_args()
sawine@0
    23
    args.log.write('%s' % sum(args.integers))
sawine@0
    24
    args.log.close()
sawine@0
    25
sawine@0
    26
The module contains the following public classes:
sawine@0
    27
sawine@0
    28
    - ArgumentParser -- The main entry point for command-line parsing. As the
sawine@0
    29
        example above shows, the add_argument() method is used to populate
sawine@0
    30
        the parser with actions for optional and positional arguments. Then
sawine@0
    31
        the parse_args() method is invoked to convert the args at the
sawine@0
    32
        command-line into an object with attributes.
sawine@0
    33
sawine@0
    34
    - ArgumentError -- The exception raised by ArgumentParser objects when
sawine@0
    35
        there are errors with the parser's actions. Errors raised while
sawine@0
    36
        parsing the command-line are caught by ArgumentParser and emitted
sawine@0
    37
        as command-line messages.
sawine@0
    38
sawine@0
    39
    - FileType -- A factory for defining types of files to be created. As the
sawine@0
    40
        example above shows, instances of FileType are typically passed as
sawine@0
    41
        the type= argument of add_argument() calls.
sawine@0
    42
sawine@0
    43
    - Action -- The base class for parser actions. Typically actions are
sawine@0
    44
        selected by passing strings like 'store_true' or 'append_const' to
sawine@0
    45
        the action= argument of add_argument(). However, for greater
sawine@0
    46
        customization of ArgumentParser actions, subclasses of Action may
sawine@0
    47
        be defined and passed as the action= argument.
sawine@0
    48
sawine@0
    49
    - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
sawine@0
    50
        ArgumentDefaultsHelpFormatter -- Formatter classes which
sawine@0
    51
        may be passed as the formatter_class= argument to the
sawine@0
    52
        ArgumentParser constructor. HelpFormatter is the default,
sawine@0
    53
        RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
sawine@0
    54
        not to change the formatting for help text, and
sawine@0
    55
        ArgumentDefaultsHelpFormatter adds information about argument defaults
sawine@0
    56
        to the help.
sawine@0
    57
sawine@0
    58
All other classes in this module are considered implementation details.
sawine@0
    59
(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
sawine@0
    60
considered public as object names -- the API of the formatter objects is
sawine@0
    61
still considered an implementation detail.)
sawine@0
    62
"""
sawine@0
    63
sawine@0
    64
__version__ = '1.1'
sawine@0
    65
__all__ = [
sawine@0
    66
    'ArgumentParser',
sawine@0
    67
    'ArgumentError',
sawine@0
    68
    'Namespace',
sawine@0
    69
    'Action',
sawine@0
    70
    'FileType',
sawine@0
    71
    'HelpFormatter',
sawine@0
    72
    'RawDescriptionHelpFormatter',
sawine@0
    73
    'RawTextHelpFormatter',
sawine@0
    74
    'ArgumentDefaultsHelpFormatter',
sawine@0
    75
]
sawine@0
    76
sawine@0
    77
sawine@0
    78
import copy as _copy
sawine@0
    79
import os as _os
sawine@0
    80
import re as _re
sawine@0
    81
import sys as _sys
sawine@0
    82
import textwrap as _textwrap
sawine@0
    83
sawine@0
    84
from gettext import gettext as _
sawine@0
    85
sawine@0
    86
sawine@0
    87
def _callable(obj):
sawine@0
    88
    return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
sawine@0
    89
sawine@0
    90
sawine@0
    91
SUPPRESS = '==SUPPRESS=='
sawine@0
    92
sawine@0
    93
OPTIONAL = '?'
sawine@0
    94
ZERO_OR_MORE = '*'
sawine@0
    95
ONE_OR_MORE = '+'
sawine@0
    96
PARSER = 'A...'
sawine@0
    97
REMAINDER = '...'
sawine@0
    98
sawine@0
    99
# =============================
sawine@0
   100
# Utility functions and classes
sawine@0
   101
# =============================
sawine@0
   102
sawine@0
   103
class _AttributeHolder(object):
sawine@0
   104
    """Abstract base class that provides __repr__.
sawine@0
   105
sawine@0
   106
    The __repr__ method returns a string in the format::
sawine@0
   107
        ClassName(attr=name, attr=name, ...)
sawine@0
   108
    The attributes are determined either by a class-level attribute,
sawine@0
   109
    '_kwarg_names', or by inspecting the instance __dict__.
sawine@0
   110
    """
sawine@0
   111
sawine@0
   112
    def __repr__(self):
sawine@0
   113
        type_name = type(self).__name__
sawine@0
   114
        arg_strings = []
sawine@0
   115
        for arg in self._get_args():
sawine@0
   116
            arg_strings.append(repr(arg))
sawine@0
   117
        for name, value in self._get_kwargs():
sawine@0
   118
            arg_strings.append('%s=%r' % (name, value))
sawine@0
   119
        return '%s(%s)' % (type_name, ', '.join(arg_strings))
sawine@0
   120
sawine@0
   121
    def _get_kwargs(self):
sawine@0
   122
        return sorted(self.__dict__.items())
sawine@0
   123
sawine@0
   124
    def _get_args(self):
sawine@0
   125
        return []
sawine@0
   126
sawine@0
   127
sawine@0
   128
def _ensure_value(namespace, name, value):
sawine@0
   129
    if getattr(namespace, name, None) is None:
sawine@0
   130
        setattr(namespace, name, value)
sawine@0
   131
    return getattr(namespace, name)
sawine@0
   132
sawine@0
   133
sawine@0
   134
# ===============
sawine@0
   135
# Formatting Help
sawine@0
   136
# ===============
sawine@0
   137
sawine@0
   138
class HelpFormatter(object):
sawine@0
   139
    """Formatter for generating usage messages and argument help strings.
sawine@0
   140
sawine@0
   141
    Only the name of this class is considered a public API. All the methods
sawine@0
   142
    provided by the class are considered an implementation detail.
sawine@0
   143
    """
sawine@0
   144
sawine@0
   145
    def __init__(self,
sawine@0
   146
                 prog,
sawine@0
   147
                 indent_increment=2,
sawine@0
   148
                 max_help_position=24,
sawine@0
   149
                 width=None):
sawine@0
   150
sawine@0
   151
        # default setting for width
sawine@0
   152
        if width is None:
sawine@0
   153
            try:
sawine@0
   154
                width = int(_os.environ['COLUMNS'])
sawine@0
   155
            except (KeyError, ValueError):
sawine@0
   156
                width = 80
sawine@0
   157
            width -= 2
sawine@0
   158
sawine@0
   159
        self._prog = prog
sawine@0
   160
        self._indent_increment = indent_increment
sawine@0
   161
        self._max_help_position = max_help_position
sawine@0
   162
        self._width = width
sawine@0
   163
sawine@0
   164
        self._current_indent = 0
sawine@0
   165
        self._level = 0
sawine@0
   166
        self._action_max_length = 0
sawine@0
   167
sawine@0
   168
        self._root_section = self._Section(self, None)
sawine@0
   169
        self._current_section = self._root_section
sawine@0
   170
sawine@0
   171
        self._whitespace_matcher = _re.compile(r'\s+')
sawine@0
   172
        self._long_break_matcher = _re.compile(r'\n\n\n+')
sawine@0
   173
sawine@0
   174
    # ===============================
sawine@0
   175
    # Section and indentation methods
sawine@0
   176
    # ===============================
sawine@0
   177
    def _indent(self):
sawine@0
   178
        self._current_indent += self._indent_increment
sawine@0
   179
        self._level += 1
sawine@0
   180
sawine@0
   181
    def _dedent(self):
sawine@0
   182
        self._current_indent -= self._indent_increment
sawine@0
   183
        assert self._current_indent >= 0, 'Indent decreased below 0.'
sawine@0
   184
        self._level -= 1
sawine@0
   185
sawine@0
   186
    class _Section(object):
sawine@0
   187
sawine@0
   188
        def __init__(self, formatter, parent, heading=None):
sawine@0
   189
            self.formatter = formatter
sawine@0
   190
            self.parent = parent
sawine@0
   191
            self.heading = heading
sawine@0
   192
            self.items = []
sawine@0
   193
sawine@0
   194
        def format_help(self):
sawine@0
   195
            # format the indented section
sawine@0
   196
            if self.parent is not None:
sawine@0
   197
                self.formatter._indent()
sawine@0
   198
            join = self.formatter._join_parts
sawine@0
   199
            for func, args in self.items:
sawine@0
   200
                func(*args)
sawine@0
   201
            item_help = join([func(*args) for func, args in self.items])
sawine@0
   202
            if self.parent is not None:
sawine@0
   203
                self.formatter._dedent()
sawine@0
   204
sawine@0
   205
            # return nothing if the section was empty
sawine@0
   206
            if not item_help:
sawine@0
   207
                return ''
sawine@0
   208
sawine@0
   209
            # add the heading if the section was non-empty
sawine@0
   210
            if self.heading is not SUPPRESS and self.heading is not None:
sawine@0
   211
                current_indent = self.formatter._current_indent
sawine@0
   212
                heading = '%*s%s:\n' % (current_indent, '', self.heading)
sawine@0
   213
            else:
sawine@0
   214
                heading = ''
sawine@0
   215
sawine@0
   216
            # join the section-initial newline, the heading and the help
sawine@0
   217
            return join(['\n', heading, item_help, '\n'])
sawine@0
   218
sawine@0
   219
    def _add_item(self, func, args):
sawine@0
   220
        self._current_section.items.append((func, args))
sawine@0
   221
sawine@0
   222
    # ========================
sawine@0
   223
    # Message building methods
sawine@0
   224
    # ========================
sawine@0
   225
    def start_section(self, heading):
sawine@0
   226
        self._indent()
sawine@0
   227
        section = self._Section(self, self._current_section, heading)
sawine@0
   228
        self._add_item(section.format_help, [])
sawine@0
   229
        self._current_section = section
sawine@0
   230
sawine@0
   231
    def end_section(self):
sawine@0
   232
        self._current_section = self._current_section.parent
sawine@0
   233
        self._dedent()
sawine@0
   234
sawine@0
   235
    def add_text(self, text):
sawine@0
   236
        if text is not SUPPRESS and text is not None:
sawine@0
   237
            self._add_item(self._format_text, [text])
sawine@0
   238
sawine@0
   239
    def add_usage(self, usage, actions, groups, prefix=None):
sawine@0
   240
        if usage is not SUPPRESS:
sawine@0
   241
            args = usage, actions, groups, prefix
sawine@0
   242
            self._add_item(self._format_usage, args)
sawine@0
   243
sawine@0
   244
    def add_argument(self, action):
sawine@0
   245
        if action.help is not SUPPRESS:
sawine@0
   246
sawine@0
   247
            # find all invocations
sawine@0
   248
            get_invocation = self._format_action_invocation
sawine@0
   249
            invocations = [get_invocation(action)]
sawine@0
   250
            for subaction in self._iter_indented_subactions(action):
sawine@0
   251
                invocations.append(get_invocation(subaction))
sawine@0
   252
sawine@0
   253
            # update the maximum item length
sawine@0
   254
            invocation_length = max([len(s) for s in invocations])
sawine@0
   255
            action_length = invocation_length + self._current_indent
sawine@0
   256
            self._action_max_length = max(self._action_max_length,
sawine@0
   257
                                          action_length)
sawine@0
   258
sawine@0
   259
            # add the item to the list
sawine@0
   260
            self._add_item(self._format_action, [action])
sawine@0
   261
sawine@0
   262
    def add_arguments(self, actions):
sawine@0
   263
        for action in actions:
sawine@0
   264
            self.add_argument(action)
sawine@0
   265
sawine@0
   266
    # =======================
sawine@0
   267
    # Help-formatting methods
sawine@0
   268
    # =======================
sawine@0
   269
    def format_help(self):
sawine@0
   270
        help = self._root_section.format_help()
sawine@0
   271
        if help:
sawine@0
   272
            help = self._long_break_matcher.sub('\n\n', help)
sawine@0
   273
            help = help.strip('\n') + '\n'
sawine@0
   274
        return help
sawine@0
   275
sawine@0
   276
    def _join_parts(self, part_strings):
sawine@0
   277
        return ''.join([part
sawine@0
   278
                        for part in part_strings
sawine@0
   279
                        if part and part is not SUPPRESS])
sawine@0
   280
sawine@0
   281
    def _format_usage(self, usage, actions, groups, prefix):
sawine@0
   282
        if prefix is None:
sawine@0
   283
            prefix = _('usage: ')
sawine@0
   284
sawine@0
   285
        # if usage is specified, use that
sawine@0
   286
        if usage is not None:
sawine@0
   287
            usage = usage % dict(prog=self._prog)
sawine@0
   288
sawine@0
   289
        # if no optionals or positionals are available, usage is just prog
sawine@0
   290
        elif usage is None and not actions:
sawine@0
   291
            usage = '%(prog)s' % dict(prog=self._prog)
sawine@0
   292
sawine@0
   293
        # if optionals and positionals are available, calculate usage
sawine@0
   294
        elif usage is None:
sawine@0
   295
            prog = '%(prog)s' % dict(prog=self._prog)
sawine@0
   296
sawine@0
   297
            # split optionals from positionals
sawine@0
   298
            optionals = []
sawine@0
   299
            positionals = []
sawine@0
   300
            for action in actions:
sawine@0
   301
                if action.option_strings:
sawine@0
   302
                    optionals.append(action)
sawine@0
   303
                else:
sawine@0
   304
                    positionals.append(action)
sawine@0
   305
sawine@0
   306
            # build full usage string
sawine@0
   307
            format = self._format_actions_usage
sawine@0
   308
            action_usage = format(optionals + positionals, groups)
sawine@0
   309
            usage = ' '.join([s for s in [prog, action_usage] if s])
sawine@0
   310
sawine@0
   311
            # wrap the usage parts if it's too long
sawine@0
   312
            text_width = self._width - self._current_indent
sawine@0
   313
            if len(prefix) + len(usage) > text_width:
sawine@0
   314
sawine@0
   315
                # break usage into wrappable parts
sawine@0
   316
                part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
sawine@0
   317
                opt_usage = format(optionals, groups)
sawine@0
   318
                pos_usage = format(positionals, groups)
sawine@0
   319
                opt_parts = _re.findall(part_regexp, opt_usage)
sawine@0
   320
                pos_parts = _re.findall(part_regexp, pos_usage)
sawine@0
   321
                assert ' '.join(opt_parts) == opt_usage
sawine@0
   322
                assert ' '.join(pos_parts) == pos_usage
sawine@0
   323
sawine@0
   324
                # helper for wrapping lines
sawine@0
   325
                def get_lines(parts, indent, prefix=None):
sawine@0
   326
                    lines = []
sawine@0
   327
                    line = []
sawine@0
   328
                    if prefix is not None:
sawine@0
   329
                        line_len = len(prefix) - 1
sawine@0
   330
                    else:
sawine@0
   331
                        line_len = len(indent) - 1
sawine@0
   332
                    for part in parts:
sawine@0
   333
                        if line_len + 1 + len(part) > text_width:
sawine@0
   334
                            lines.append(indent + ' '.join(line))
sawine@0
   335
                            line = []
sawine@0
   336
                            line_len = len(indent) - 1
sawine@0
   337
                        line.append(part)
sawine@0
   338
                        line_len += len(part) + 1
sawine@0
   339
                    if line:
sawine@0
   340
                        lines.append(indent + ' '.join(line))
sawine@0
   341
                    if prefix is not None:
sawine@0
   342
                        lines[0] = lines[0][len(indent):]
sawine@0
   343
                    return lines
sawine@0
   344
sawine@0
   345
                # if prog is short, follow it with optionals or positionals
sawine@0
   346
                if len(prefix) + len(prog) <= 0.75 * text_width:
sawine@0
   347
                    indent = ' ' * (len(prefix) + len(prog) + 1)
sawine@0
   348
                    if opt_parts:
sawine@0
   349
                        lines = get_lines([prog] + opt_parts, indent, prefix)
sawine@0
   350
                        lines.extend(get_lines(pos_parts, indent))
sawine@0
   351
                    elif pos_parts:
sawine@0
   352
                        lines = get_lines([prog] + pos_parts, indent, prefix)
sawine@0
   353
                    else:
sawine@0
   354
                        lines = [prog]
sawine@0
   355
sawine@0
   356
                # if prog is long, put it on its own line
sawine@0
   357
                else:
sawine@0
   358
                    indent = ' ' * len(prefix)
sawine@0
   359
                    parts = opt_parts + pos_parts
sawine@0
   360
                    lines = get_lines(parts, indent)
sawine@0
   361
                    if len(lines) > 1:
sawine@0
   362
                        lines = []
sawine@0
   363
                        lines.extend(get_lines(opt_parts, indent))
sawine@0
   364
                        lines.extend(get_lines(pos_parts, indent))
sawine@0
   365
                    lines = [prog] + lines
sawine@0
   366
sawine@0
   367
                # join lines into usage
sawine@0
   368
                usage = '\n'.join(lines)
sawine@0
   369
sawine@0
   370
        # prefix with 'usage:'
sawine@0
   371
        return '%s%s\n\n' % (prefix, usage)
sawine@0
   372
sawine@0
   373
    def _format_actions_usage(self, actions, groups):
sawine@0
   374
        # find group indices and identify actions in groups
sawine@0
   375
        group_actions = set()
sawine@0
   376
        inserts = {}
sawine@0
   377
        for group in groups:
sawine@0
   378
            try:
sawine@0
   379
                start = actions.index(group._group_actions[0])
sawine@0
   380
            except ValueError:
sawine@0
   381
                continue
sawine@0
   382
            else:
sawine@0
   383
                end = start + len(group._group_actions)
sawine@0
   384
                if actions[start:end] == group._group_actions:
sawine@0
   385
                    for action in group._group_actions:
sawine@0
   386
                        group_actions.add(action)
sawine@0
   387
                    if not group.required:
sawine@0
   388
                        inserts[start] = '['
sawine@0
   389
                        inserts[end] = ']'
sawine@0
   390
                    else:
sawine@0
   391
                        inserts[start] = '('
sawine@0
   392
                        inserts[end] = ')'
sawine@0
   393
                    for i in range(start + 1, end):
sawine@0
   394
                        inserts[i] = '|'
sawine@0
   395
sawine@0
   396
        # collect all actions format strings
sawine@0
   397
        parts = []
sawine@0
   398
        for i, action in enumerate(actions):
sawine@0
   399
sawine@0
   400
            # suppressed arguments are marked with None
sawine@0
   401
            # remove | separators for suppressed arguments
sawine@0
   402
            if action.help is SUPPRESS:
sawine@0
   403
                parts.append(None)
sawine@0
   404
                if inserts.get(i) == '|':
sawine@0
   405
                    inserts.pop(i)
sawine@0
   406
                elif inserts.get(i + 1) == '|':
sawine@0
   407
                    inserts.pop(i + 1)
sawine@0
   408
sawine@0
   409
            # produce all arg strings
sawine@0
   410
            elif not action.option_strings:
sawine@0
   411
                part = self._format_args(action, action.dest)
sawine@0
   412
sawine@0
   413
                # if it's in a group, strip the outer []
sawine@0
   414
                if action in group_actions:
sawine@0
   415
                    if part[0] == '[' and part[-1] == ']':
sawine@0
   416
                        part = part[1:-1]
sawine@0
   417
sawine@0
   418
                # add the action string to the list
sawine@0
   419
                parts.append(part)
sawine@0
   420
sawine@0
   421
            # produce the first way to invoke the option in brackets
sawine@0
   422
            else:
sawine@0
   423
                option_string = action.option_strings[0]
sawine@0
   424
sawine@0
   425
                # if the Optional doesn't take a value, format is:
sawine@0
   426
                #    -s or --long
sawine@0
   427
                if action.nargs == 0:
sawine@0
   428
                    part = '%s' % option_string
sawine@0
   429
sawine@0
   430
                # if the Optional takes a value, format is:
sawine@0
   431
                #    -s ARGS or --long ARGS
sawine@0
   432
                else:
sawine@0
   433
                    default = action.dest.upper()
sawine@0
   434
                    args_string = self._format_args(action, default)
sawine@0
   435
                    part = '%s %s' % (option_string, args_string)
sawine@0
   436
sawine@0
   437
                # make it look optional if it's not required or in a group
sawine@0
   438
                if not action.required and action not in group_actions:
sawine@0
   439
                    part = '[%s]' % part
sawine@0
   440
sawine@0
   441
                # add the action string to the list
sawine@0
   442
                parts.append(part)
sawine@0
   443
sawine@0
   444
        # insert things at the necessary indices
sawine@0
   445
        for i in sorted(inserts, reverse=True):
sawine@0
   446
            parts[i:i] = [inserts[i]]
sawine@0
   447
sawine@0
   448
        # join all the action items with spaces
sawine@0
   449
        text = ' '.join([item for item in parts if item is not None])
sawine@0
   450
sawine@0
   451
        # clean up separators for mutually exclusive groups
sawine@0
   452
        open = r'[\[(]'
sawine@0
   453
        close = r'[\])]'
sawine@0
   454
        text = _re.sub(r'(%s) ' % open, r'\1', text)
sawine@0
   455
        text = _re.sub(r' (%s)' % close, r'\1', text)
sawine@0
   456
        text = _re.sub(r'%s *%s' % (open, close), r'', text)
sawine@0
   457
        text = _re.sub(r'\(([^|]*)\)', r'\1', text)
sawine@0
   458
        text = text.strip()
sawine@0
   459
sawine@0
   460
        # return the text
sawine@0
   461
        return text
sawine@0
   462
sawine@0
   463
    def _format_text(self, text):
sawine@0
   464
        if '%(prog)' in text:
sawine@0
   465
            text = text % dict(prog=self._prog)
sawine@0
   466
        text_width = self._width - self._current_indent
sawine@0
   467
        indent = ' ' * self._current_indent
sawine@0
   468
        return self._fill_text(text, text_width, indent) + '\n\n'
sawine@0
   469
sawine@0
   470
    def _format_action(self, action):
sawine@0
   471
        # determine the required width and the entry label
sawine@0
   472
        help_position = min(self._action_max_length + 2,
sawine@0
   473
                            self._max_help_position)
sawine@0
   474
        help_width = self._width - help_position
sawine@0
   475
        action_width = help_position - self._current_indent - 2
sawine@0
   476
        action_header = self._format_action_invocation(action)
sawine@0
   477
sawine@0
   478
        # ho nelp; start on same line and add a final newline
sawine@0
   479
        if not action.help:
sawine@0
   480
            tup = self._current_indent, '', action_header
sawine@0
   481
            action_header = '%*s%s\n' % tup
sawine@0
   482
sawine@0
   483
        # short action name; start on the same line and pad two spaces
sawine@0
   484
        elif len(action_header) <= action_width:
sawine@0
   485
            tup = self._current_indent, '', action_width, action_header
sawine@0
   486
            action_header = '%*s%-*s  ' % tup
sawine@0
   487
            indent_first = 0
sawine@0
   488
sawine@0
   489
        # long action name; start on the next line
sawine@0
   490
        else:
sawine@0
   491
            tup = self._current_indent, '', action_header
sawine@0
   492
            action_header = '%*s%s\n' % tup
sawine@0
   493
            indent_first = help_position
sawine@0
   494
sawine@0
   495
        # collect the pieces of the action help
sawine@0
   496
        parts = [action_header]
sawine@0
   497
sawine@0
   498
        # if there was help for the action, add lines of help text
sawine@0
   499
        if action.help:
sawine@0
   500
            help_text = self._expand_help(action)
sawine@0
   501
            help_lines = self._split_lines(help_text, help_width)
sawine@0
   502
            parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
sawine@0
   503
            for line in help_lines[1:]:
sawine@0
   504
                parts.append('%*s%s\n' % (help_position, '', line))
sawine@0
   505
sawine@0
   506
        # or add a newline if the description doesn't end with one
sawine@0
   507
        elif not action_header.endswith('\n'):
sawine@0
   508
            parts.append('\n')
sawine@0
   509
sawine@0
   510
        # if there are any sub-actions, add their help as well
sawine@0
   511
        for subaction in self._iter_indented_subactions(action):
sawine@0
   512
            parts.append(self._format_action(subaction))
sawine@0
   513
sawine@0
   514
        # return a single string
sawine@0
   515
        return self._join_parts(parts)
sawine@0
   516
sawine@0
   517
    def _format_action_invocation(self, action):
sawine@0
   518
        if not action.option_strings:
sawine@0
   519
            metavar, = self._metavar_formatter(action, action.dest)(1)
sawine@0
   520
            return metavar
sawine@0
   521
sawine@0
   522
        else:
sawine@0
   523
            parts = []
sawine@0
   524
sawine@0
   525
            # if the Optional doesn't take a value, format is:
sawine@0
   526
            #    -s, --long
sawine@0
   527
            if action.nargs == 0:
sawine@0
   528
                parts.extend(action.option_strings)
sawine@0
   529
sawine@0
   530
            # if the Optional takes a value, format is:
sawine@0
   531
            #    -s ARGS, --long ARGS
sawine@0
   532
            else:
sawine@0
   533
                default = action.dest.upper()
sawine@0
   534
                args_string = self._format_args(action, default)
sawine@0
   535
                for option_string in action.option_strings:
sawine@0
   536
                    parts.append('%s %s' % (option_string, args_string))
sawine@0
   537
sawine@0
   538
            return ', '.join(parts)
sawine@0
   539
sawine@0
   540
    def _metavar_formatter(self, action, default_metavar):
sawine@0
   541
        if action.metavar is not None:
sawine@0
   542
            result = action.metavar
sawine@0
   543
        elif action.choices is not None:
sawine@0
   544
            choice_strs = [str(choice) for choice in action.choices]
sawine@0
   545
            result = '{%s}' % ','.join(choice_strs)
sawine@0
   546
        else:
sawine@0
   547
            result = default_metavar
sawine@0
   548
sawine@0
   549
        def format(tuple_size):
sawine@0
   550
            if isinstance(result, tuple):
sawine@0
   551
                return result
sawine@0
   552
            else:
sawine@0
   553
                return (result, ) * tuple_size
sawine@0
   554
        return format
sawine@0
   555
sawine@0
   556
    def _format_args(self, action, default_metavar):
sawine@0
   557
        get_metavar = self._metavar_formatter(action, default_metavar)
sawine@0
   558
        if action.nargs is None:
sawine@0
   559
            result = '%s' % get_metavar(1)
sawine@0
   560
        elif action.nargs == OPTIONAL:
sawine@0
   561
            result = '[%s]' % get_metavar(1)
sawine@0
   562
        elif action.nargs == ZERO_OR_MORE:
sawine@0
   563
            result = '[%s [%s ...]]' % get_metavar(2)
sawine@0
   564
        elif action.nargs == ONE_OR_MORE:
sawine@0
   565
            result = '%s [%s ...]' % get_metavar(2)
sawine@0
   566
        elif action.nargs == REMAINDER:
sawine@0
   567
            result = '...'
sawine@0
   568
        elif action.nargs == PARSER:
sawine@0
   569
            result = '%s ...' % get_metavar(1)
sawine@0
   570
        else:
sawine@0
   571
            formats = ['%s' for _ in range(action.nargs)]
sawine@0
   572
            result = ' '.join(formats) % get_metavar(action.nargs)
sawine@0
   573
        return result
sawine@0
   574
sawine@0
   575
    def _expand_help(self, action):
sawine@0
   576
        params = dict(vars(action), prog=self._prog)
sawine@0
   577
        for name in list(params):
sawine@0
   578
            if params[name] is SUPPRESS:
sawine@0
   579
                del params[name]
sawine@0
   580
        for name in list(params):
sawine@0
   581
            if hasattr(params[name], '__name__'):
sawine@0
   582
                params[name] = params[name].__name__
sawine@0
   583
        if params.get('choices') is not None:
sawine@0
   584
            choices_str = ', '.join([str(c) for c in params['choices']])
sawine@0
   585
            params['choices'] = choices_str
sawine@0
   586
        return self._get_help_string(action) % params
sawine@0
   587
sawine@0
   588
    def _iter_indented_subactions(self, action):
sawine@0
   589
        try:
sawine@0
   590
            get_subactions = action._get_subactions
sawine@0
   591
        except AttributeError:
sawine@0
   592
            pass
sawine@0
   593
        else:
sawine@0
   594
            self._indent()
sawine@0
   595
            for subaction in get_subactions():
sawine@0
   596
                yield subaction
sawine@0
   597
            self._dedent()
sawine@0
   598
sawine@0
   599
    def _split_lines(self, text, width):
sawine@0
   600
        text = self._whitespace_matcher.sub(' ', text).strip()
sawine@0
   601
        return _textwrap.wrap(text, width)
sawine@0
   602
sawine@0
   603
    def _fill_text(self, text, width, indent):
sawine@0
   604
        text = self._whitespace_matcher.sub(' ', text).strip()
sawine@0
   605
        return _textwrap.fill(text, width, initial_indent=indent,
sawine@0
   606
                                           subsequent_indent=indent)
sawine@0
   607
sawine@0
   608
    def _get_help_string(self, action):
sawine@0
   609
        return action.help
sawine@0
   610
sawine@0
   611
sawine@0
   612
class RawDescriptionHelpFormatter(HelpFormatter):
sawine@0
   613
    """Help message formatter which retains any formatting in descriptions.
sawine@0
   614
sawine@0
   615
    Only the name of this class is considered a public API. All the methods
sawine@0
   616
    provided by the class are considered an implementation detail.
sawine@0
   617
    """
sawine@0
   618
sawine@0
   619
    def _fill_text(self, text, width, indent):
sawine@0
   620
        return ''.join([indent + line for line in text.splitlines(True)])
sawine@0
   621
sawine@0
   622
sawine@0
   623
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
sawine@0
   624
    """Help message formatter which retains formatting of all help text.
sawine@0
   625
sawine@0
   626
    Only the name of this class is considered a public API. All the methods
sawine@0
   627
    provided by the class are considered an implementation detail.
sawine@0
   628
    """
sawine@0
   629
sawine@0
   630
    def _split_lines(self, text, width):
sawine@0
   631
        return text.splitlines()
sawine@0
   632
sawine@0
   633
sawine@0
   634
class ArgumentDefaultsHelpFormatter(HelpFormatter):
sawine@0
   635
    """Help message formatter which adds default values to argument help.
sawine@0
   636
sawine@0
   637
    Only the name of this class is considered a public API. All the methods
sawine@0
   638
    provided by the class are considered an implementation detail.
sawine@0
   639
    """
sawine@0
   640
sawine@0
   641
    def _get_help_string(self, action):
sawine@0
   642
        help = action.help
sawine@0
   643
        if '%(default)' not in action.help:
sawine@0
   644
            if action.default is not SUPPRESS:
sawine@0
   645
                defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
sawine@0
   646
                if action.option_strings or action.nargs in defaulting_nargs:
sawine@0
   647
                    help += ' (default: %(default)s)'
sawine@0
   648
        return help
sawine@0
   649
sawine@0
   650
sawine@0
   651
# =====================
sawine@0
   652
# Options and Arguments
sawine@0
   653
# =====================
sawine@0
   654
sawine@0
   655
def _get_action_name(argument):
sawine@0
   656
    if argument is None:
sawine@0
   657
        return None
sawine@0
   658
    elif argument.option_strings:
sawine@0
   659
        return  '/'.join(argument.option_strings)
sawine@0
   660
    elif argument.metavar not in (None, SUPPRESS):
sawine@0
   661
        return argument.metavar
sawine@0
   662
    elif argument.dest not in (None, SUPPRESS):
sawine@0
   663
        return argument.dest
sawine@0
   664
    else:
sawine@0
   665
        return None
sawine@0
   666
sawine@0
   667
sawine@0
   668
class ArgumentError(Exception):
sawine@0
   669
    """An error from creating or using an argument (optional or positional).
sawine@0
   670
sawine@0
   671
    The string value of this exception is the message, augmented with
sawine@0
   672
    information about the argument that caused it.
sawine@0
   673
    """
sawine@0
   674
sawine@0
   675
    def __init__(self, argument, message):
sawine@0
   676
        self.argument_name = _get_action_name(argument)
sawine@0
   677
        self.message = message
sawine@0
   678
sawine@0
   679
    def __str__(self):
sawine@0
   680
        if self.argument_name is None:
sawine@0
   681
            format = '%(message)s'
sawine@0
   682
        else:
sawine@0
   683
            format = 'argument %(argument_name)s: %(message)s'
sawine@0
   684
        return format % dict(message=self.message,
sawine@0
   685
                             argument_name=self.argument_name)
sawine@0
   686
sawine@0
   687
sawine@0
   688
class ArgumentTypeError(Exception):
sawine@0
   689
    """An error from trying to convert a command line string to a type."""
sawine@0
   690
    pass
sawine@0
   691
sawine@0
   692
sawine@0
   693
# ==============
sawine@0
   694
# Action classes
sawine@0
   695
# ==============
sawine@0
   696
sawine@0
   697
class Action(_AttributeHolder):
sawine@0
   698
    """Information about how to convert command line strings to Python objects.
sawine@0
   699
sawine@0
   700
    Action objects are used by an ArgumentParser to represent the information
sawine@0
   701
    needed to parse a single argument from one or more strings from the
sawine@0
   702
    command line. The keyword arguments to the Action constructor are also
sawine@0
   703
    all attributes of Action instances.
sawine@0
   704
sawine@0
   705
    Keyword Arguments:
sawine@0
   706
sawine@0
   707
        - option_strings -- A list of command-line option strings which
sawine@0
   708
            should be associated with this action.
sawine@0
   709
sawine@0
   710
        - dest -- The name of the attribute to hold the created object(s)
sawine@0
   711
sawine@0
   712
        - nargs -- The number of command-line arguments that should be
sawine@0
   713
            consumed. By default, one argument will be consumed and a single
sawine@0
   714
            value will be produced.  Other values include:
sawine@0
   715
                - N (an integer) consumes N arguments (and produces a list)
sawine@0
   716
                - '?' consumes zero or one arguments
sawine@0
   717
                - '*' consumes zero or more arguments (and produces a list)
sawine@0
   718
                - '+' consumes one or more arguments (and produces a list)
sawine@0
   719
            Note that the difference between the default and nargs=1 is that
sawine@0
   720
            with the default, a single value will be produced, while with
sawine@0
   721
            nargs=1, a list containing a single value will be produced.
sawine@0
   722
sawine@0
   723
        - const -- The value to be produced if the option is specified and the
sawine@0
   724
            option uses an action that takes no values.
sawine@0
   725
sawine@0
   726
        - default -- The value to be produced if the option is not specified.
sawine@0
   727
sawine@0
   728
        - type -- The type which the command-line arguments should be converted
sawine@0
   729
            to, should be one of 'string', 'int', 'float', 'complex' or a
sawine@0
   730
            callable object that accepts a single string argument. If None,
sawine@0
   731
            'string' is assumed.
sawine@0
   732
sawine@0
   733
        - choices -- A container of values that should be allowed. If not None,
sawine@0
   734
            after a command-line argument has been converted to the appropriate
sawine@0
   735
            type, an exception will be raised if it is not a member of this
sawine@0
   736
            collection.
sawine@0
   737
sawine@0
   738
        - required -- True if the action must always be specified at the
sawine@0
   739
            command line. This is only meaningful for optional command-line
sawine@0
   740
            arguments.
sawine@0
   741
sawine@0
   742
        - help -- The help string describing the argument.
sawine@0
   743
sawine@0
   744
        - metavar -- The name to be used for the option's argument with the
sawine@0
   745
            help string. If None, the 'dest' value will be used as the name.
sawine@0
   746
    """
sawine@0
   747
sawine@0
   748
    def __init__(self,
sawine@0
   749
                 option_strings,
sawine@0
   750
                 dest,
sawine@0
   751
                 nargs=None,
sawine@0
   752
                 const=None,
sawine@0
   753
                 default=None,
sawine@0
   754
                 type=None,
sawine@0
   755
                 choices=None,
sawine@0
   756
                 required=False,
sawine@0
   757
                 help=None,
sawine@0
   758
                 metavar=None):
sawine@0
   759
        self.option_strings = option_strings
sawine@0
   760
        self.dest = dest
sawine@0
   761
        self.nargs = nargs
sawine@0
   762
        self.const = const
sawine@0
   763
        self.default = default
sawine@0
   764
        self.type = type
sawine@0
   765
        self.choices = choices
sawine@0
   766
        self.required = required
sawine@0
   767
        self.help = help
sawine@0
   768
        self.metavar = metavar
sawine@0
   769
sawine@0
   770
    def _get_kwargs(self):
sawine@0
   771
        names = [
sawine@0
   772
            'option_strings',
sawine@0
   773
            'dest',
sawine@0
   774
            'nargs',
sawine@0
   775
            'const',
sawine@0
   776
            'default',
sawine@0
   777
            'type',
sawine@0
   778
            'choices',
sawine@0
   779
            'help',
sawine@0
   780
            'metavar',
sawine@0
   781
        ]
sawine@0
   782
        return [(name, getattr(self, name)) for name in names]
sawine@0
   783
sawine@0
   784
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
   785
        raise NotImplementedError(_('.__call__() not defined'))
sawine@0
   786
sawine@0
   787
sawine@0
   788
class _StoreAction(Action):
sawine@0
   789
sawine@0
   790
    def __init__(self,
sawine@0
   791
                 option_strings,
sawine@0
   792
                 dest,
sawine@0
   793
                 nargs=None,
sawine@0
   794
                 const=None,
sawine@0
   795
                 default=None,
sawine@0
   796
                 type=None,
sawine@0
   797
                 choices=None,
sawine@0
   798
                 required=False,
sawine@0
   799
                 help=None,
sawine@0
   800
                 metavar=None):
sawine@0
   801
        if nargs == 0:
sawine@0
   802
            raise ValueError('nargs for store actions must be > 0; if you '
sawine@0
   803
                             'have nothing to store, actions such as store '
sawine@0
   804
                             'true or store const may be more appropriate')
sawine@0
   805
        if const is not None and nargs != OPTIONAL:
sawine@0
   806
            raise ValueError('nargs must be %r to supply const' % OPTIONAL)
sawine@0
   807
        super(_StoreAction, self).__init__(
sawine@0
   808
            option_strings=option_strings,
sawine@0
   809
            dest=dest,
sawine@0
   810
            nargs=nargs,
sawine@0
   811
            const=const,
sawine@0
   812
            default=default,
sawine@0
   813
            type=type,
sawine@0
   814
            choices=choices,
sawine@0
   815
            required=required,
sawine@0
   816
            help=help,
sawine@0
   817
            metavar=metavar)
sawine@0
   818
sawine@0
   819
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
   820
        setattr(namespace, self.dest, values)
sawine@0
   821
sawine@0
   822
sawine@0
   823
class _StoreConstAction(Action):
sawine@0
   824
sawine@0
   825
    def __init__(self,
sawine@0
   826
                 option_strings,
sawine@0
   827
                 dest,
sawine@0
   828
                 const,
sawine@0
   829
                 default=None,
sawine@0
   830
                 required=False,
sawine@0
   831
                 help=None,
sawine@0
   832
                 metavar=None):
sawine@0
   833
        super(_StoreConstAction, self).__init__(
sawine@0
   834
            option_strings=option_strings,
sawine@0
   835
            dest=dest,
sawine@0
   836
            nargs=0,
sawine@0
   837
            const=const,
sawine@0
   838
            default=default,
sawine@0
   839
            required=required,
sawine@0
   840
            help=help)
sawine@0
   841
sawine@0
   842
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
   843
        setattr(namespace, self.dest, self.const)
sawine@0
   844
sawine@0
   845
sawine@0
   846
class _StoreTrueAction(_StoreConstAction):
sawine@0
   847
sawine@0
   848
    def __init__(self,
sawine@0
   849
                 option_strings,
sawine@0
   850
                 dest,
sawine@0
   851
                 default=False,
sawine@0
   852
                 required=False,
sawine@0
   853
                 help=None):
sawine@0
   854
        super(_StoreTrueAction, self).__init__(
sawine@0
   855
            option_strings=option_strings,
sawine@0
   856
            dest=dest,
sawine@0
   857
            const=True,
sawine@0
   858
            default=default,
sawine@0
   859
            required=required,
sawine@0
   860
            help=help)
sawine@0
   861
sawine@0
   862
sawine@0
   863
class _StoreFalseAction(_StoreConstAction):
sawine@0
   864
sawine@0
   865
    def __init__(self,
sawine@0
   866
                 option_strings,
sawine@0
   867
                 dest,
sawine@0
   868
                 default=True,
sawine@0
   869
                 required=False,
sawine@0
   870
                 help=None):
sawine@0
   871
        super(_StoreFalseAction, self).__init__(
sawine@0
   872
            option_strings=option_strings,
sawine@0
   873
            dest=dest,
sawine@0
   874
            const=False,
sawine@0
   875
            default=default,
sawine@0
   876
            required=required,
sawine@0
   877
            help=help)
sawine@0
   878
sawine@0
   879
sawine@0
   880
class _AppendAction(Action):
sawine@0
   881
sawine@0
   882
    def __init__(self,
sawine@0
   883
                 option_strings,
sawine@0
   884
                 dest,
sawine@0
   885
                 nargs=None,
sawine@0
   886
                 const=None,
sawine@0
   887
                 default=None,
sawine@0
   888
                 type=None,
sawine@0
   889
                 choices=None,
sawine@0
   890
                 required=False,
sawine@0
   891
                 help=None,
sawine@0
   892
                 metavar=None):
sawine@0
   893
        if nargs == 0:
sawine@0
   894
            raise ValueError('nargs for append actions must be > 0; if arg '
sawine@0
   895
                             'strings are not supplying the value to append, '
sawine@0
   896
                             'the append const action may be more appropriate')
sawine@0
   897
        if const is not None and nargs != OPTIONAL:
sawine@0
   898
            raise ValueError('nargs must be %r to supply const' % OPTIONAL)
sawine@0
   899
        super(_AppendAction, self).__init__(
sawine@0
   900
            option_strings=option_strings,
sawine@0
   901
            dest=dest,
sawine@0
   902
            nargs=nargs,
sawine@0
   903
            const=const,
sawine@0
   904
            default=default,
sawine@0
   905
            type=type,
sawine@0
   906
            choices=choices,
sawine@0
   907
            required=required,
sawine@0
   908
            help=help,
sawine@0
   909
            metavar=metavar)
sawine@0
   910
sawine@0
   911
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
   912
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
sawine@0
   913
        items.append(values)
sawine@0
   914
        setattr(namespace, self.dest, items)
sawine@0
   915
sawine@0
   916
sawine@0
   917
class _AppendConstAction(Action):
sawine@0
   918
sawine@0
   919
    def __init__(self,
sawine@0
   920
                 option_strings,
sawine@0
   921
                 dest,
sawine@0
   922
                 const,
sawine@0
   923
                 default=None,
sawine@0
   924
                 required=False,
sawine@0
   925
                 help=None,
sawine@0
   926
                 metavar=None):
sawine@0
   927
        super(_AppendConstAction, self).__init__(
sawine@0
   928
            option_strings=option_strings,
sawine@0
   929
            dest=dest,
sawine@0
   930
            nargs=0,
sawine@0
   931
            const=const,
sawine@0
   932
            default=default,
sawine@0
   933
            required=required,
sawine@0
   934
            help=help,
sawine@0
   935
            metavar=metavar)
sawine@0
   936
sawine@0
   937
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
   938
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
sawine@0
   939
        items.append(self.const)
sawine@0
   940
        setattr(namespace, self.dest, items)
sawine@0
   941
sawine@0
   942
sawine@0
   943
class _CountAction(Action):
sawine@0
   944
sawine@0
   945
    def __init__(self,
sawine@0
   946
                 option_strings,
sawine@0
   947
                 dest,
sawine@0
   948
                 default=None,
sawine@0
   949
                 required=False,
sawine@0
   950
                 help=None):
sawine@0
   951
        super(_CountAction, self).__init__(
sawine@0
   952
            option_strings=option_strings,
sawine@0
   953
            dest=dest,
sawine@0
   954
            nargs=0,
sawine@0
   955
            default=default,
sawine@0
   956
            required=required,
sawine@0
   957
            help=help)
sawine@0
   958
sawine@0
   959
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
   960
        new_count = _ensure_value(namespace, self.dest, 0) + 1
sawine@0
   961
        setattr(namespace, self.dest, new_count)
sawine@0
   962
sawine@0
   963
sawine@0
   964
class _HelpAction(Action):
sawine@0
   965
sawine@0
   966
    def __init__(self,
sawine@0
   967
                 option_strings,
sawine@0
   968
                 dest=SUPPRESS,
sawine@0
   969
                 default=SUPPRESS,
sawine@0
   970
                 help=None):
sawine@0
   971
        super(_HelpAction, self).__init__(
sawine@0
   972
            option_strings=option_strings,
sawine@0
   973
            dest=dest,
sawine@0
   974
            default=default,
sawine@0
   975
            nargs=0,
sawine@0
   976
            help=help)
sawine@0
   977
sawine@0
   978
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
   979
        parser.print_help()
sawine@0
   980
        parser.exit()
sawine@0
   981
sawine@0
   982
sawine@0
   983
class _VersionAction(Action):
sawine@0
   984
sawine@0
   985
    def __init__(self,
sawine@0
   986
                 option_strings,
sawine@0
   987
                 version=None,
sawine@0
   988
                 dest=SUPPRESS,
sawine@0
   989
                 default=SUPPRESS,
sawine@0
   990
                 help="show program's version number and exit"):
sawine@0
   991
        super(_VersionAction, self).__init__(
sawine@0
   992
            option_strings=option_strings,
sawine@0
   993
            dest=dest,
sawine@0
   994
            default=default,
sawine@0
   995
            nargs=0,
sawine@0
   996
            help=help)
sawine@0
   997
        self.version = version
sawine@0
   998
sawine@0
   999
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
  1000
        version = self.version
sawine@0
  1001
        if version is None:
sawine@0
  1002
            version = parser.version
sawine@0
  1003
        formatter = parser._get_formatter()
sawine@0
  1004
        formatter.add_text(version)
sawine@0
  1005
        parser.exit(message=formatter.format_help())
sawine@0
  1006
sawine@0
  1007
sawine@0
  1008
class _SubParsersAction(Action):
sawine@0
  1009
sawine@0
  1010
    class _ChoicesPseudoAction(Action):
sawine@0
  1011
sawine@0
  1012
        def __init__(self, name, help):
sawine@0
  1013
            sup = super(_SubParsersAction._ChoicesPseudoAction, self)
sawine@0
  1014
            sup.__init__(option_strings=[], dest=name, help=help)
sawine@0
  1015
sawine@0
  1016
    def __init__(self,
sawine@0
  1017
                 option_strings,
sawine@0
  1018
                 prog,
sawine@0
  1019
                 parser_class,
sawine@0
  1020
                 dest=SUPPRESS,
sawine@0
  1021
                 help=None,
sawine@0
  1022
                 metavar=None):
sawine@0
  1023
sawine@0
  1024
        self._prog_prefix = prog
sawine@0
  1025
        self._parser_class = parser_class
sawine@0
  1026
        self._name_parser_map = {}
sawine@0
  1027
        self._choices_actions = []
sawine@0
  1028
sawine@0
  1029
        super(_SubParsersAction, self).__init__(
sawine@0
  1030
            option_strings=option_strings,
sawine@0
  1031
            dest=dest,
sawine@0
  1032
            nargs=PARSER,
sawine@0
  1033
            choices=self._name_parser_map,
sawine@0
  1034
            help=help,
sawine@0
  1035
            metavar=metavar)
sawine@0
  1036
sawine@0
  1037
    def add_parser(self, name, **kwargs):
sawine@0
  1038
        # set prog from the existing prefix
sawine@0
  1039
        if kwargs.get('prog') is None:
sawine@0
  1040
            kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
sawine@0
  1041
sawine@0
  1042
        # create a pseudo-action to hold the choice help
sawine@0
  1043
        if 'help' in kwargs:
sawine@0
  1044
            help = kwargs.pop('help')
sawine@0
  1045
            choice_action = self._ChoicesPseudoAction(name, help)
sawine@0
  1046
            self._choices_actions.append(choice_action)
sawine@0
  1047
sawine@0
  1048
        # create the parser and add it to the map
sawine@0
  1049
        parser = self._parser_class(**kwargs)
sawine@0
  1050
        self._name_parser_map[name] = parser
sawine@0
  1051
        return parser
sawine@0
  1052
sawine@0
  1053
    def _get_subactions(self):
sawine@0
  1054
        return self._choices_actions
sawine@0
  1055
sawine@0
  1056
    def __call__(self, parser, namespace, values, option_string=None):
sawine@0
  1057
        parser_name = values[0]
sawine@0
  1058
        arg_strings = values[1:]
sawine@0
  1059
sawine@0
  1060
        # set the parser name if requested
sawine@0
  1061
        if self.dest is not SUPPRESS:
sawine@0
  1062
            setattr(namespace, self.dest, parser_name)
sawine@0
  1063
sawine@0
  1064
        # select the parser
sawine@0
  1065
        try:
sawine@0
  1066
            parser = self._name_parser_map[parser_name]
sawine@0
  1067
        except KeyError:
sawine@0
  1068
            tup = parser_name, ', '.join(self._name_parser_map)
sawine@0
  1069
            msg = _('unknown parser %r (choices: %s)' % tup)
sawine@0
  1070
            raise ArgumentError(self, msg)
sawine@0
  1071
sawine@0
  1072
        # parse all the remaining options into the namespace
sawine@0
  1073
        parser.parse_args(arg_strings, namespace)
sawine@0
  1074
sawine@0
  1075
sawine@0
  1076
# ==============
sawine@0
  1077
# Type classes
sawine@0
  1078
# ==============
sawine@0
  1079
sawine@0
  1080
class FileType(object):
sawine@0
  1081
    """Factory for creating file object types
sawine@0
  1082
sawine@0
  1083
    Instances of FileType are typically passed as type= arguments to the
sawine@0
  1084
    ArgumentParser add_argument() method.
sawine@0
  1085
sawine@0
  1086
    Keyword Arguments:
sawine@0
  1087
        - mode -- A string indicating how the file is to be opened. Accepts the
sawine@0
  1088
            same values as the builtin open() function.
sawine@0
  1089
        - bufsize -- The file's desired buffer size. Accepts the same values as
sawine@0
  1090
            the builtin open() function.
sawine@0
  1091
    """
sawine@0
  1092
sawine@0
  1093
    def __init__(self, mode='r', bufsize=None):
sawine@0
  1094
        self._mode = mode
sawine@0
  1095
        self._bufsize = bufsize
sawine@0
  1096
sawine@0
  1097
    def __call__(self, string):
sawine@0
  1098
        # the special argument "-" means sys.std{in,out}
sawine@0
  1099
        if string == '-':
sawine@0
  1100
            if 'r' in self._mode:
sawine@0
  1101
                return _sys.stdin
sawine@0
  1102
            elif 'w' in self._mode:
sawine@0
  1103
                return _sys.stdout
sawine@0
  1104
            else:
sawine@0
  1105
                msg = _('argument "-" with mode %r' % self._mode)
sawine@0
  1106
                raise ValueError(msg)
sawine@0
  1107
sawine@0
  1108
        # all other arguments are used as file names
sawine@0
  1109
        if self._bufsize:
sawine@0
  1110
            return open(string, self._mode, self._bufsize)
sawine@0
  1111
        else:
sawine@0
  1112
            return open(string, self._mode)
sawine@0
  1113
sawine@0
  1114
    def __repr__(self):
sawine@0
  1115
        args = [self._mode, self._bufsize]
sawine@0
  1116
        args_str = ', '.join([repr(arg) for arg in args if arg is not None])
sawine@0
  1117
        return '%s(%s)' % (type(self).__name__, args_str)
sawine@0
  1118
sawine@0
  1119
# ===========================
sawine@0
  1120
# Optional and Positional Parsing
sawine@0
  1121
# ===========================
sawine@0
  1122
sawine@0
  1123
class Namespace(_AttributeHolder):
sawine@0
  1124
    """Simple object for storing attributes.
sawine@0
  1125
sawine@0
  1126
    Implements equality by attribute names and values, and provides a simple
sawine@0
  1127
    string representation.
sawine@0
  1128
    """
sawine@0
  1129
sawine@0
  1130
    def __init__(self, **kwargs):
sawine@0
  1131
        for name in kwargs:
sawine@0
  1132
            setattr(self, name, kwargs[name])
sawine@0
  1133
sawine@0
  1134
    def __eq__(self, other):
sawine@0
  1135
        return vars(self) == vars(other)
sawine@0
  1136
sawine@0
  1137
    def __ne__(self, other):
sawine@0
  1138
        return not (self == other)
sawine@0
  1139
sawine@0
  1140
    def __contains__(self, key):
sawine@0
  1141
        return key in self.__dict__
sawine@0
  1142
sawine@0
  1143
sawine@0
  1144
class _ActionsContainer(object):
sawine@0
  1145
sawine@0
  1146
    def __init__(self,
sawine@0
  1147
                 description,
sawine@0
  1148
                 prefix_chars,
sawine@0
  1149
                 argument_default,
sawine@0
  1150
                 conflict_handler):
sawine@0
  1151
        super(_ActionsContainer, self).__init__()
sawine@0
  1152
sawine@0
  1153
        self.description = description
sawine@0
  1154
        self.argument_default = argument_default
sawine@0
  1155
        self.prefix_chars = prefix_chars
sawine@0
  1156
        self.conflict_handler = conflict_handler
sawine@0
  1157
sawine@0
  1158
        # set up registries
sawine@0
  1159
        self._registries = {}
sawine@0
  1160
sawine@0
  1161
        # register actions
sawine@0
  1162
        self.register('action', None, _StoreAction)
sawine@0
  1163
        self.register('action', 'store', _StoreAction)
sawine@0
  1164
        self.register('action', 'store_const', _StoreConstAction)
sawine@0
  1165
        self.register('action', 'store_true', _StoreTrueAction)
sawine@0
  1166
        self.register('action', 'store_false', _StoreFalseAction)
sawine@0
  1167
        self.register('action', 'append', _AppendAction)
sawine@0
  1168
        self.register('action', 'append_const', _AppendConstAction)
sawine@0
  1169
        self.register('action', 'count', _CountAction)
sawine@0
  1170
        self.register('action', 'help', _HelpAction)
sawine@0
  1171
        self.register('action', 'version', _VersionAction)
sawine@0
  1172
        self.register('action', 'parsers', _SubParsersAction)
sawine@0
  1173
sawine@0
  1174
        # raise an exception if the conflict handler is invalid
sawine@0
  1175
        self._get_handler()
sawine@0
  1176
sawine@0
  1177
        # action storage
sawine@0
  1178
        self._actions = []
sawine@0
  1179
        self._option_string_actions = {}
sawine@0
  1180
sawine@0
  1181
        # groups
sawine@0
  1182
        self._action_groups = []
sawine@0
  1183
        self._mutually_exclusive_groups = []
sawine@0
  1184
sawine@0
  1185
        # defaults storage
sawine@0
  1186
        self._defaults = {}
sawine@0
  1187
sawine@0
  1188
        # determines whether an "option" looks like a negative number
sawine@0
  1189
        self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
sawine@0
  1190
sawine@0
  1191
        # whether or not there are any optionals that look like negative
sawine@0
  1192
        # numbers -- uses a list so it can be shared and edited
sawine@0
  1193
        self._has_negative_number_optionals = []
sawine@0
  1194
sawine@0
  1195
    # ====================
sawine@0
  1196
    # Registration methods
sawine@0
  1197
    # ====================
sawine@0
  1198
    def register(self, registry_name, value, object):
sawine@0
  1199
        registry = self._registries.setdefault(registry_name, {})
sawine@0
  1200
        registry[value] = object
sawine@0
  1201
sawine@0
  1202
    def _registry_get(self, registry_name, value, default=None):
sawine@0
  1203
        return self._registries[registry_name].get(value, default)
sawine@0
  1204
sawine@0
  1205
    # ==================================
sawine@0
  1206
    # Namespace default accessor methods
sawine@0
  1207
    # ==================================
sawine@0
  1208
    def set_defaults(self, **kwargs):
sawine@0
  1209
        self._defaults.update(kwargs)
sawine@0
  1210
sawine@0
  1211
        # if these defaults match any existing arguments, replace
sawine@0
  1212
        # the previous default on the object with the new one
sawine@0
  1213
        for action in self._actions:
sawine@0
  1214
            if action.dest in kwargs:
sawine@0
  1215
                action.default = kwargs[action.dest]
sawine@0
  1216
sawine@0
  1217
    def get_default(self, dest):
sawine@0
  1218
        for action in self._actions:
sawine@0
  1219
            if action.dest == dest and action.default is not None:
sawine@0
  1220
                return action.default
sawine@0
  1221
        return self._defaults.get(dest, None)
sawine@0
  1222
sawine@0
  1223
sawine@0
  1224
    # =======================
sawine@0
  1225
    # Adding argument actions
sawine@0
  1226
    # =======================
sawine@0
  1227
    def add_argument(self, *args, **kwargs):
sawine@0
  1228
        """
sawine@0
  1229
        add_argument(dest, ..., name=value, ...)
sawine@0
  1230
        add_argument(option_string, option_string, ..., name=value, ...)
sawine@0
  1231
        """
sawine@0
  1232
sawine@0
  1233
        # if no positional args are supplied or only one is supplied and
sawine@0
  1234
        # it doesn't look like an option string, parse a positional
sawine@0
  1235
        # argument
sawine@0
  1236
        chars = self.prefix_chars
sawine@0
  1237
        if not args or len(args) == 1 and args[0][0] not in chars:
sawine@0
  1238
            if args and 'dest' in kwargs:
sawine@0
  1239
                raise ValueError('dest supplied twice for positional argument')
sawine@0
  1240
            kwargs = self._get_positional_kwargs(*args, **kwargs)
sawine@0
  1241
sawine@0
  1242
        # otherwise, we're adding an optional argument
sawine@0
  1243
        else:
sawine@0
  1244
            kwargs = self._get_optional_kwargs(*args, **kwargs)
sawine@0
  1245
sawine@0
  1246
        # if no default was supplied, use the parser-level default
sawine@0
  1247
        if 'default' not in kwargs:
sawine@0
  1248
            dest = kwargs['dest']
sawine@0
  1249
            if dest in self._defaults:
sawine@0
  1250
                kwargs['default'] = self._defaults[dest]
sawine@0
  1251
            elif self.argument_default is not None:
sawine@0
  1252
                kwargs['default'] = self.argument_default
sawine@0
  1253
sawine@0
  1254
        # create the action object, and add it to the parser
sawine@0
  1255
        action_class = self._pop_action_class(kwargs)
sawine@0
  1256
        if not _callable(action_class):
sawine@0
  1257
            raise ValueError('unknown action "%s"' % action_class)
sawine@0
  1258
        action = action_class(**kwargs)
sawine@0
  1259
sawine@0
  1260
        # raise an error if the action type is not callable
sawine@0
  1261
        type_func = self._registry_get('type', action.type, action.type)
sawine@0
  1262
        if not _callable(type_func):
sawine@0
  1263
            raise ValueError('%r is not callable' % type_func)
sawine@0
  1264
sawine@0
  1265
        return self._add_action(action)
sawine@0
  1266
sawine@0
  1267
    def add_argument_group(self, *args, **kwargs):
sawine@0
  1268
        group = _ArgumentGroup(self, *args, **kwargs)
sawine@0
  1269
        self._action_groups.append(group)
sawine@0
  1270
        return group
sawine@0
  1271
sawine@0
  1272
    def add_mutually_exclusive_group(self, **kwargs):
sawine@0
  1273
        group = _MutuallyExclusiveGroup(self, **kwargs)
sawine@0
  1274
        self._mutually_exclusive_groups.append(group)
sawine@0
  1275
        return group
sawine@0
  1276
sawine@0
  1277
    def _add_action(self, action):
sawine@0
  1278
        # resolve any conflicts
sawine@0
  1279
        self._check_conflict(action)
sawine@0
  1280
sawine@0
  1281
        # add to actions list
sawine@0
  1282
        self._actions.append(action)
sawine@0
  1283
        action.container = self
sawine@0
  1284
sawine@0
  1285
        # index the action by any option strings it has
sawine@0
  1286
        for option_string in action.option_strings:
sawine@0
  1287
            self._option_string_actions[option_string] = action
sawine@0
  1288
sawine@0
  1289
        # set the flag if any option strings look like negative numbers
sawine@0
  1290
        for option_string in action.option_strings:
sawine@0
  1291
            if self._negative_number_matcher.match(option_string):
sawine@0
  1292
                if not self._has_negative_number_optionals:
sawine@0
  1293
                    self._has_negative_number_optionals.append(True)
sawine@0
  1294
sawine@0
  1295
        # return the created action
sawine@0
  1296
        return action
sawine@0
  1297
sawine@0
  1298
    def _remove_action(self, action):
sawine@0
  1299
        self._actions.remove(action)
sawine@0
  1300
sawine@0
  1301
    def _add_container_actions(self, container):
sawine@0
  1302
        # collect groups by titles
sawine@0
  1303
        title_group_map = {}
sawine@0
  1304
        for group in self._action_groups:
sawine@0
  1305
            if group.title in title_group_map:
sawine@0
  1306
                msg = _('cannot merge actions - two groups are named %r')
sawine@0
  1307
                raise ValueError(msg % (group.title))
sawine@0
  1308
            title_group_map[group.title] = group
sawine@0
  1309
sawine@0
  1310
        # map each action to its group
sawine@0
  1311
        group_map = {}
sawine@0
  1312
        for group in container._action_groups:
sawine@0
  1313
sawine@0
  1314
            # if a group with the title exists, use that, otherwise
sawine@0
  1315
            # create a new group matching the container's group
sawine@0
  1316
            if group.title not in title_group_map:
sawine@0
  1317
                title_group_map[group.title] = self.add_argument_group(
sawine@0
  1318
                    title=group.title,
sawine@0
  1319
                    description=group.description,
sawine@0
  1320
                    conflict_handler=group.conflict_handler)
sawine@0
  1321
sawine@0
  1322
            # map the actions to their new group
sawine@0
  1323
            for action in group._group_actions:
sawine@0
  1324
                group_map[action] = title_group_map[group.title]
sawine@0
  1325
sawine@0
  1326
        # add container's mutually exclusive groups
sawine@0
  1327
        # NOTE: if add_mutually_exclusive_group ever gains title= and
sawine@0
  1328
        # description= then this code will need to be expanded as above
sawine@0
  1329
        for group in container._mutually_exclusive_groups:
sawine@0
  1330
            mutex_group = self.add_mutually_exclusive_group(
sawine@0
  1331
                required=group.required)
sawine@0
  1332
sawine@0
  1333
            # map the actions to their new mutex group
sawine@0
  1334
            for action in group._group_actions:
sawine@0
  1335
                group_map[action] = mutex_group
sawine@0
  1336
sawine@0
  1337
        # add all actions to this container or their group
sawine@0
  1338
        for action in container._actions:
sawine@0
  1339
            group_map.get(action, self)._add_action(action)
sawine@0
  1340
sawine@0
  1341
    def _get_positional_kwargs(self, dest, **kwargs):
sawine@0
  1342
        # make sure required is not specified
sawine@0
  1343
        if 'required' in kwargs:
sawine@0
  1344
            msg = _("'required' is an invalid argument for positionals")
sawine@0
  1345
            raise TypeError(msg)
sawine@0
  1346
sawine@0
  1347
        # mark positional arguments as required if at least one is
sawine@0
  1348
        # always required
sawine@0
  1349
        if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
sawine@0
  1350
            kwargs['required'] = True
sawine@0
  1351
        if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
sawine@0
  1352
            kwargs['required'] = True
sawine@0
  1353
sawine@0
  1354
        # return the keyword arguments with no option strings
sawine@0
  1355
        return dict(kwargs, dest=dest, option_strings=[])
sawine@0
  1356
sawine@0
  1357
    def _get_optional_kwargs(self, *args, **kwargs):
sawine@0
  1358
        # determine short and long option strings
sawine@0
  1359
        option_strings = []
sawine@0
  1360
        long_option_strings = []
sawine@0
  1361
        for option_string in args:
sawine@0
  1362
            # error on strings that don't start with an appropriate prefix
sawine@0
  1363
            if not option_string[0] in self.prefix_chars:
sawine@0
  1364
                msg = _('invalid option string %r: '
sawine@0
  1365
                        'must start with a character %r')
sawine@0
  1366
                tup = option_string, self.prefix_chars
sawine@0
  1367
                raise ValueError(msg % tup)
sawine@0
  1368
sawine@0
  1369
            # strings starting with two prefix characters are long options
sawine@0
  1370
            option_strings.append(option_string)
sawine@0
  1371
            if option_string[0] in self.prefix_chars:
sawine@0
  1372
                if len(option_string) > 1:
sawine@0
  1373
                    if option_string[1] in self.prefix_chars:
sawine@0
  1374
                        long_option_strings.append(option_string)
sawine@0
  1375
sawine@0
  1376
        # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
sawine@0
  1377
        dest = kwargs.pop('dest', None)
sawine@0
  1378
        if dest is None:
sawine@0
  1379
            if long_option_strings:
sawine@0
  1380
                dest_option_string = long_option_strings[0]
sawine@0
  1381
            else:
sawine@0
  1382
                dest_option_string = option_strings[0]
sawine@0
  1383
            dest = dest_option_string.lstrip(self.prefix_chars)
sawine@0
  1384
            if not dest:
sawine@0
  1385
                msg = _('dest= is required for options like %r')
sawine@0
  1386
                raise ValueError(msg % option_string)
sawine@0
  1387
            dest = dest.replace('-', '_')
sawine@0
  1388
sawine@0
  1389
        # return the updated keyword arguments
sawine@0
  1390
        return dict(kwargs, dest=dest, option_strings=option_strings)
sawine@0
  1391
sawine@0
  1392
    def _pop_action_class(self, kwargs, default=None):
sawine@0
  1393
        action = kwargs.pop('action', default)
sawine@0
  1394
        return self._registry_get('action', action, action)
sawine@0
  1395
sawine@0
  1396
    def _get_handler(self):
sawine@0
  1397
        # determine function from conflict handler string
sawine@0
  1398
        handler_func_name = '_handle_conflict_%s' % self.conflict_handler
sawine@0
  1399
        try:
sawine@0
  1400
            return getattr(self, handler_func_name)
sawine@0
  1401
        except AttributeError:
sawine@0
  1402
            msg = _('invalid conflict_resolution value: %r')
sawine@0
  1403
            raise ValueError(msg % self.conflict_handler)
sawine@0
  1404
sawine@0
  1405
    def _check_conflict(self, action):
sawine@0
  1406
sawine@0
  1407
        # find all options that conflict with this option
sawine@0
  1408
        confl_optionals = []
sawine@0
  1409
        for option_string in action.option_strings:
sawine@0
  1410
            if option_string in self._option_string_actions:
sawine@0
  1411
                confl_optional = self._option_string_actions[option_string]
sawine@0
  1412
                confl_optionals.append((option_string, confl_optional))
sawine@0
  1413
sawine@0
  1414
        # resolve any conflicts
sawine@0
  1415
        if confl_optionals:
sawine@0
  1416
            conflict_handler = self._get_handler()
sawine@0
  1417
            conflict_handler(action, confl_optionals)
sawine@0
  1418
sawine@0
  1419
    def _handle_conflict_error(self, action, conflicting_actions):
sawine@0
  1420
        message = _('conflicting option string(s): %s')
sawine@0
  1421
        conflict_string = ', '.join([option_string
sawine@0
  1422
                                     for option_string, action
sawine@0
  1423
                                     in conflicting_actions])
sawine@0
  1424
        raise ArgumentError(action, message % conflict_string)
sawine@0
  1425
sawine@0
  1426
    def _handle_conflict_resolve(self, action, conflicting_actions):
sawine@0
  1427
sawine@0
  1428
        # remove all conflicting options
sawine@0
  1429
        for option_string, action in conflicting_actions:
sawine@0
  1430
sawine@0
  1431
            # remove the conflicting option
sawine@0
  1432
            action.option_strings.remove(option_string)
sawine@0
  1433
            self._option_string_actions.pop(option_string, None)
sawine@0
  1434
sawine@0
  1435
            # if the option now has no option string, remove it from the
sawine@0
  1436
            # container holding it
sawine@0
  1437
            if not action.option_strings:
sawine@0
  1438
                action.container._remove_action(action)
sawine@0
  1439
sawine@0
  1440
sawine@0
  1441
class _ArgumentGroup(_ActionsContainer):
sawine@0
  1442
sawine@0
  1443
    def __init__(self, container, title=None, description=None, **kwargs):
sawine@0
  1444
        # add any missing keyword arguments by checking the container
sawine@0
  1445
        update = kwargs.setdefault
sawine@0
  1446
        update('conflict_handler', container.conflict_handler)
sawine@0
  1447
        update('prefix_chars', container.prefix_chars)
sawine@0
  1448
        update('argument_default', container.argument_default)
sawine@0
  1449
        super_init = super(_ArgumentGroup, self).__init__
sawine@0
  1450
        super_init(description=description, **kwargs)
sawine@0
  1451
sawine@0
  1452
        # group attributes
sawine@0
  1453
        self.title = title
sawine@0
  1454
        self._group_actions = []
sawine@0
  1455
sawine@0
  1456
        # share most attributes with the container
sawine@0
  1457
        self._registries = container._registries
sawine@0
  1458
        self._actions = container._actions
sawine@0
  1459
        self._option_string_actions = container._option_string_actions
sawine@0
  1460
        self._defaults = container._defaults
sawine@0
  1461
        self._has_negative_number_optionals = \
sawine@0
  1462
            container._has_negative_number_optionals
sawine@0
  1463
sawine@0
  1464
    def _add_action(self, action):
sawine@0
  1465
        action = super(_ArgumentGroup, self)._add_action(action)
sawine@0
  1466
        self._group_actions.append(action)
sawine@0
  1467
        return action
sawine@0
  1468
sawine@0
  1469
    def _remove_action(self, action):
sawine@0
  1470
        super(_ArgumentGroup, self)._remove_action(action)
sawine@0
  1471
        self._group_actions.remove(action)
sawine@0
  1472
sawine@0
  1473
sawine@0
  1474
class _MutuallyExclusiveGroup(_ArgumentGroup):
sawine@0
  1475
sawine@0
  1476
    def __init__(self, container, required=False):
sawine@0
  1477
        super(_MutuallyExclusiveGroup, self).__init__(container)
sawine@0
  1478
        self.required = required
sawine@0
  1479
        self._container = container
sawine@0
  1480
sawine@0
  1481
    def _add_action(self, action):
sawine@0
  1482
        if action.required:
sawine@0
  1483
            msg = _('mutually exclusive arguments must be optional')
sawine@0
  1484
            raise ValueError(msg)
sawine@0
  1485
        action = self._container._add_action(action)
sawine@0
  1486
        self._group_actions.append(action)
sawine@0
  1487
        return action
sawine@0
  1488
sawine@0
  1489
    def _remove_action(self, action):
sawine@0
  1490
        self._container._remove_action(action)
sawine@0
  1491
        self._group_actions.remove(action)
sawine@0
  1492
sawine@0
  1493
sawine@0
  1494
class ArgumentParser(_AttributeHolder, _ActionsContainer):
sawine@0
  1495
    """Object for parsing command line strings into Python objects.
sawine@0
  1496
sawine@0
  1497
    Keyword Arguments:
sawine@0
  1498
        - prog -- The name of the program (default: sys.argv[0])
sawine@0
  1499
        - usage -- A usage message (default: auto-generated from arguments)
sawine@0
  1500
        - description -- A description of what the program does
sawine@0
  1501
        - epilog -- Text following the argument descriptions
sawine@0
  1502
        - parents -- Parsers whose arguments should be copied into this one
sawine@0
  1503
        - formatter_class -- HelpFormatter class for printing help messages
sawine@0
  1504
        - prefix_chars -- Characters that prefix optional arguments
sawine@0
  1505
        - fromfile_prefix_chars -- Characters that prefix files containing
sawine@0
  1506
            additional arguments
sawine@0
  1507
        - argument_default -- The default value for all arguments
sawine@0
  1508
        - conflict_handler -- String indicating how to handle conflicts
sawine@0
  1509
        - add_help -- Add a -h/-help option
sawine@0
  1510
    """
sawine@0
  1511
sawine@0
  1512
    def __init__(self,
sawine@0
  1513
                 prog=None,
sawine@0
  1514
                 usage=None,
sawine@0
  1515
                 description=None,
sawine@0
  1516
                 epilog=None,
sawine@0
  1517
                 version=None,
sawine@0
  1518
                 parents=[],
sawine@0
  1519
                 formatter_class=HelpFormatter,
sawine@0
  1520
                 prefix_chars='-',
sawine@0
  1521
                 fromfile_prefix_chars=None,
sawine@0
  1522
                 argument_default=None,
sawine@0
  1523
                 conflict_handler='error',
sawine@0
  1524
                 add_help=True):
sawine@0
  1525
sawine@0
  1526
        if version is not None:
sawine@0
  1527
            import warnings
sawine@0
  1528
            warnings.warn(
sawine@0
  1529
                """The "version" argument to ArgumentParser is deprecated. """
sawine@0
  1530
                """Please use """
sawine@0
  1531
                """"add_argument(..., action='version', version="N", ...)" """
sawine@0
  1532
                """instead""", DeprecationWarning)
sawine@0
  1533
sawine@0
  1534
        superinit = super(ArgumentParser, self).__init__
sawine@0
  1535
        superinit(description=description,
sawine@0
  1536
                  prefix_chars=prefix_chars,
sawine@0
  1537
                  argument_default=argument_default,
sawine@0
  1538
                  conflict_handler=conflict_handler)
sawine@0
  1539
sawine@0
  1540
        # default setting for prog
sawine@0
  1541
        if prog is None:
sawine@0
  1542
            prog = _os.path.basename(_sys.argv[0])
sawine@0
  1543
sawine@0
  1544
        self.prog = prog
sawine@0
  1545
        self.usage = usage
sawine@0
  1546
        self.epilog = epilog
sawine@0
  1547
        self.version = version
sawine@0
  1548
        self.formatter_class = formatter_class
sawine@0
  1549
        self.fromfile_prefix_chars = fromfile_prefix_chars
sawine@0
  1550
        self.add_help = add_help
sawine@0
  1551
sawine@0
  1552
        add_group = self.add_argument_group
sawine@0
  1553
        self._positionals = add_group(_('positional arguments'))
sawine@0
  1554
        self._optionals = add_group(_('optional arguments'))
sawine@0
  1555
        self._subparsers = None
sawine@0
  1556
sawine@0
  1557
        # register types
sawine@0
  1558
        def identity(string):
sawine@0
  1559
            return string
sawine@0
  1560
        self.register('type', None, identity)
sawine@0
  1561
sawine@0
  1562
        # add help and version arguments if necessary
sawine@0
  1563
        # (using explicit default to override global argument_default)
sawine@0
  1564
        default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
sawine@0
  1565
        if self.add_help:
sawine@0
  1566
            self.add_argument(
sawine@0
  1567
                default_prefix+'h', default_prefix*2+'help',
sawine@0
  1568
                action='help', default=SUPPRESS,
sawine@0
  1569
                help=_('show this help message and exit'))
sawine@0
  1570
        if self.version:
sawine@0
  1571
            self.add_argument(
sawine@0
  1572
                default_prefix+'v', default_prefix*2+'version',
sawine@0
  1573
                action='version', default=SUPPRESS,
sawine@0
  1574
                version=self.version,
sawine@0
  1575
                help=_("show program's version number and exit"))
sawine@0
  1576
sawine@0
  1577
        # add parent arguments and defaults
sawine@0
  1578
        for parent in parents:
sawine@0
  1579
            self._add_container_actions(parent)
sawine@0
  1580
            try:
sawine@0
  1581
                defaults = parent._defaults
sawine@0
  1582
            except AttributeError:
sawine@0
  1583
                pass
sawine@0
  1584
            else:
sawine@0
  1585
                self._defaults.update(defaults)
sawine@0
  1586
sawine@0
  1587
    # =======================
sawine@0
  1588
    # Pretty __repr__ methods
sawine@0
  1589
    # =======================
sawine@0
  1590
    def _get_kwargs(self):
sawine@0
  1591
        names = [
sawine@0
  1592
            'prog',
sawine@0
  1593
            'usage',
sawine@0
  1594
            'description',
sawine@0
  1595
            'version',
sawine@0
  1596
            'formatter_class',
sawine@0
  1597
            'conflict_handler',
sawine@0
  1598
            'add_help',
sawine@0
  1599
        ]
sawine@0
  1600
        return [(name, getattr(self, name)) for name in names]
sawine@0
  1601
sawine@0
  1602
    # ==================================
sawine@0
  1603
    # Optional/Positional adding methods
sawine@0
  1604
    # ==================================
sawine@0
  1605
    def add_subparsers(self, **kwargs):
sawine@0
  1606
        if self._subparsers is not None:
sawine@0
  1607
            self.error(_('cannot have multiple subparser arguments'))
sawine@0
  1608
sawine@0
  1609
        # add the parser class to the arguments if it's not present
sawine@0
  1610
        kwargs.setdefault('parser_class', type(self))
sawine@0
  1611
sawine@0
  1612
        if 'title' in kwargs or 'description' in kwargs:
sawine@0
  1613
            title = _(kwargs.pop('title', 'subcommands'))
sawine@0
  1614
            description = _(kwargs.pop('description', None))
sawine@0
  1615
            self._subparsers = self.add_argument_group(title, description)
sawine@0
  1616
        else:
sawine@0
  1617
            self._subparsers = self._positionals
sawine@0
  1618
sawine@0
  1619
        # prog defaults to the usage message of this parser, skipping
sawine@0
  1620
        # optional arguments and with no "usage:" prefix
sawine@0
  1621
        if kwargs.get('prog') is None:
sawine@0
  1622
            formatter = self._get_formatter()
sawine@0
  1623
            positionals = self._get_positional_actions()
sawine@0
  1624
            groups = self._mutually_exclusive_groups
sawine@0
  1625
            formatter.add_usage(self.usage, positionals, groups, '')
sawine@0
  1626
            kwargs['prog'] = formatter.format_help().strip()
sawine@0
  1627
sawine@0
  1628
        # create the parsers action and add it to the positionals list
sawine@0
  1629
        parsers_class = self._pop_action_class(kwargs, 'parsers')
sawine@0
  1630
        action = parsers_class(option_strings=[], **kwargs)
sawine@0
  1631
        self._subparsers._add_action(action)
sawine@0
  1632
sawine@0
  1633
        # return the created parsers action
sawine@0
  1634
        return action
sawine@0
  1635
sawine@0
  1636
    def _add_action(self, action):
sawine@0
  1637
        if action.option_strings:
sawine@0
  1638
            self._optionals._add_action(action)
sawine@0
  1639
        else:
sawine@0
  1640
            self._positionals._add_action(action)
sawine@0
  1641
        return action
sawine@0
  1642
sawine@0
  1643
    def _get_optional_actions(self):
sawine@0
  1644
        return [action
sawine@0
  1645
                for action in self._actions
sawine@0
  1646
                if action.option_strings]
sawine@0
  1647
sawine@0
  1648
    def _get_positional_actions(self):
sawine@0
  1649
        return [action
sawine@0
  1650
                for action in self._actions
sawine@0
  1651
                if not action.option_strings]
sawine@0
  1652
sawine@0
  1653
    # =====================================
sawine@0
  1654
    # Command line argument parsing methods
sawine@0
  1655
    # =====================================
sawine@0
  1656
    def parse_args(self, args=None, namespace=None):
sawine@0
  1657
        args, argv = self.parse_known_args(args, namespace)
sawine@0
  1658
        if argv:
sawine@0
  1659
            msg = _('unrecognized arguments: %s')
sawine@0
  1660
            self.error(msg % ' '.join(argv))
sawine@0
  1661
        return args
sawine@0
  1662
sawine@0
  1663
    def parse_known_args(self, args=None, namespace=None):
sawine@0
  1664
        # args default to the system args
sawine@0
  1665
        if args is None:
sawine@0
  1666
            args = _sys.argv[1:]
sawine@0
  1667
sawine@0
  1668
        # default Namespace built from parser defaults
sawine@0
  1669
        if namespace is None:
sawine@0
  1670
            namespace = Namespace()
sawine@0
  1671
sawine@0
  1672
        # add any action defaults that aren't present
sawine@0
  1673
        for action in self._actions:
sawine@0
  1674
            if action.dest is not SUPPRESS:
sawine@0
  1675
                if not hasattr(namespace, action.dest):
sawine@0
  1676
                    if action.default is not SUPPRESS:
sawine@0
  1677
                        default = action.default
sawine@0
  1678
                        if isinstance(action.default, str):
sawine@0
  1679
                            default = self._get_value(action, default)
sawine@0
  1680
                        setattr(namespace, action.dest, default)
sawine@0
  1681
sawine@0
  1682
        # add any parser defaults that aren't present
sawine@0
  1683
        for dest in self._defaults:
sawine@0
  1684
            if not hasattr(namespace, dest):
sawine@0
  1685
                setattr(namespace, dest, self._defaults[dest])
sawine@0
  1686
sawine@0
  1687
        # parse the arguments and exit if there are any errors
sawine@0
  1688
        try:
sawine@0
  1689
            return self._parse_known_args(args, namespace)
sawine@0
  1690
        except ArgumentError:
sawine@0
  1691
            err = _sys.exc_info()[1]
sawine@0
  1692
            self.error(str(err))
sawine@0
  1693
sawine@0
  1694
    def _parse_known_args(self, arg_strings, namespace):
sawine@0
  1695
        # replace arg strings that are file references
sawine@0
  1696
        if self.fromfile_prefix_chars is not None:
sawine@0
  1697
            arg_strings = self._read_args_from_files(arg_strings)
sawine@0
  1698
sawine@0
  1699
        # map all mutually exclusive arguments to the other arguments
sawine@0
  1700
        # they can't occur with
sawine@0
  1701
        action_conflicts = {}
sawine@0
  1702
        for mutex_group in self._mutually_exclusive_groups:
sawine@0
  1703
            group_actions = mutex_group._group_actions
sawine@0
  1704
            for i, mutex_action in enumerate(mutex_group._group_actions):
sawine@0
  1705
                conflicts = action_conflicts.setdefault(mutex_action, [])
sawine@0
  1706
                conflicts.extend(group_actions[:i])
sawine@0
  1707
                conflicts.extend(group_actions[i + 1:])
sawine@0
  1708
sawine@0
  1709
        # find all option indices, and determine the arg_string_pattern
sawine@0
  1710
        # which has an 'O' if there is an option at an index,
sawine@0
  1711
        # an 'A' if there is an argument, or a '-' if there is a '--'
sawine@0
  1712
        option_string_indices = {}
sawine@0
  1713
        arg_string_pattern_parts = []
sawine@0
  1714
        arg_strings_iter = iter(arg_strings)
sawine@0
  1715
        for i, arg_string in enumerate(arg_strings_iter):
sawine@0
  1716
sawine@0
  1717
            # all args after -- are non-options
sawine@0
  1718
            if arg_string == '--':
sawine@0
  1719
                arg_string_pattern_parts.append('-')
sawine@0
  1720
                for arg_string in arg_strings_iter:
sawine@0
  1721
                    arg_string_pattern_parts.append('A')
sawine@0
  1722
sawine@0
  1723
            # otherwise, add the arg to the arg strings
sawine@0
  1724
            # and note the index if it was an option
sawine@0
  1725
            else:
sawine@0
  1726
                option_tuple = self._parse_optional(arg_string)
sawine@0
  1727
                if option_tuple is None:
sawine@0
  1728
                    pattern = 'A'
sawine@0
  1729
                else:
sawine@0
  1730
                    option_string_indices[i] = option_tuple
sawine@0
  1731
                    pattern = 'O'
sawine@0
  1732
                arg_string_pattern_parts.append(pattern)
sawine@0
  1733
sawine@0
  1734
        # join the pieces together to form the pattern
sawine@0
  1735
        arg_strings_pattern = ''.join(arg_string_pattern_parts)
sawine@0
  1736
sawine@0
  1737
        # converts arg strings to the appropriate and then takes the action
sawine@0
  1738
        seen_actions = set()
sawine@0
  1739
        seen_non_default_actions = set()
sawine@0
  1740
sawine@0
  1741
        def take_action(action, argument_strings, option_string=None):
sawine@0
  1742
            seen_actions.add(action)
sawine@0
  1743
            argument_values = self._get_values(action, argument_strings)
sawine@0
  1744
sawine@0
  1745
            # error if this argument is not allowed with other previously
sawine@0
  1746
            # seen arguments, assuming that actions that use the default
sawine@0
  1747
            # value don't really count as "present"
sawine@0
  1748
            if argument_values is not action.default:
sawine@0
  1749
                seen_non_default_actions.add(action)
sawine@0
  1750
                for conflict_action in action_conflicts.get(action, []):
sawine@0
  1751
                    if conflict_action in seen_non_default_actions:
sawine@0
  1752
                        msg = _('not allowed with argument %s')
sawine@0
  1753
                        action_name = _get_action_name(conflict_action)
sawine@0
  1754
                        raise ArgumentError(action, msg % action_name)
sawine@0
  1755
sawine@0
  1756
            # take the action if we didn't receive a SUPPRESS value
sawine@0
  1757
            # (e.g. from a default)
sawine@0
  1758
            if argument_values is not SUPPRESS:
sawine@0
  1759
                action(self, namespace, argument_values, option_string)
sawine@0
  1760
sawine@0
  1761
        # function to convert arg_strings into an optional action
sawine@0
  1762
        def consume_optional(start_index):
sawine@0
  1763
sawine@0
  1764
            # get the optional identified at this index
sawine@0
  1765
            option_tuple = option_string_indices[start_index]
sawine@0
  1766
            action, option_string, explicit_arg = option_tuple
sawine@0
  1767
sawine@0
  1768
            # identify additional optionals in the same arg string
sawine@0
  1769
            # (e.g. -xyz is the same as -x -y -z if no args are required)
sawine@0
  1770
            match_argument = self._match_argument
sawine@0
  1771
            action_tuples = []
sawine@0
  1772
            while True:
sawine@0
  1773
sawine@0
  1774
                # if we found no optional action, skip it
sawine@0
  1775
                if action is None:
sawine@0
  1776
                    extras.append(arg_strings[start_index])
sawine@0
  1777
                    return start_index + 1
sawine@0
  1778
sawine@0
  1779
                # if there is an explicit argument, try to match the
sawine@0
  1780
                # optional's string arguments to only this
sawine@0
  1781
                if explicit_arg is not None:
sawine@0
  1782
                    arg_count = match_argument(action, 'A')
sawine@0
  1783
sawine@0
  1784
                    # if the action is a single-dash option and takes no
sawine@0
  1785
                    # arguments, try to parse more single-dash options out
sawine@0
  1786
                    # of the tail of the option string
sawine@0
  1787
                    chars = self.prefix_chars
sawine@0
  1788
                    if arg_count == 0 and option_string[1] not in chars:
sawine@0
  1789
                        action_tuples.append((action, [], option_string))
sawine@0
  1790
                        for char in self.prefix_chars:
sawine@0
  1791
                            option_string = char + explicit_arg[0]
sawine@0
  1792
                            explicit_arg = explicit_arg[1:] or None
sawine@0
  1793
                            optionals_map = self._option_string_actions
sawine@0
  1794
                            if option_string in optionals_map:
sawine@0
  1795
                                action = optionals_map[option_string]
sawine@0
  1796
                                break
sawine@0
  1797
                        else:
sawine@0
  1798
                            msg = _('ignored explicit argument %r')
sawine@0
  1799
                            raise ArgumentError(action, msg % explicit_arg)
sawine@0
  1800
sawine@0
  1801
                    # if the action expect exactly one argument, we've
sawine@0
  1802
                    # successfully matched the option; exit the loop
sawine@0
  1803
                    elif arg_count == 1:
sawine@0
  1804
                        stop = start_index + 1
sawine@0
  1805
                        args = [explicit_arg]
sawine@0
  1806
                        action_tuples.append((action, args, option_string))
sawine@0
  1807
                        break
sawine@0
  1808
sawine@0
  1809
                    # error if a double-dash option did not use the
sawine@0
  1810
                    # explicit argument
sawine@0
  1811
                    else:
sawine@0
  1812
                        msg = _('ignored explicit argument %r')
sawine@0
  1813
                        raise ArgumentError(action, msg % explicit_arg)
sawine@0
  1814
sawine@0
  1815
                # if there is no explicit argument, try to match the
sawine@0
  1816
                # optional's string arguments with the following strings
sawine@0
  1817
                # if successful, exit the loop
sawine@0
  1818
                else:
sawine@0
  1819
                    start = start_index + 1
sawine@0
  1820
                    selected_patterns = arg_strings_pattern[start:]
sawine@0
  1821
                    arg_count = match_argument(action, selected_patterns)
sawine@0
  1822
                    stop = start + arg_count
sawine@0
  1823
                    args = arg_strings[start:stop]
sawine@0
  1824
                    action_tuples.append((action, args, option_string))
sawine@0
  1825
                    break
sawine@0
  1826
sawine@0
  1827
            # add the Optional to the list and return the index at which
sawine@0
  1828
            # the Optional's string args stopped
sawine@0
  1829
            assert action_tuples
sawine@0
  1830
            for action, args, option_string in action_tuples:
sawine@0
  1831
                take_action(action, args, option_string)
sawine@0
  1832
            return stop
sawine@0
  1833
sawine@0
  1834
        # the list of Positionals left to be parsed; this is modified
sawine@0
  1835
        # by consume_positionals()
sawine@0
  1836
        positionals = self._get_positional_actions()
sawine@0
  1837
sawine@0
  1838
        # function to convert arg_strings into positional actions
sawine@0
  1839
        def consume_positionals(start_index):
sawine@0
  1840
            # match as many Positionals as possible
sawine@0
  1841
            match_partial = self._match_arguments_partial
sawine@0
  1842
            selected_pattern = arg_strings_pattern[start_index:]
sawine@0
  1843
            arg_counts = match_partial(positionals, selected_pattern)
sawine@0
  1844
sawine@0
  1845
            # slice off the appropriate arg strings for each Positional
sawine@0
  1846
            # and add the Positional and its args to the list
sawine@0
  1847
            for action, arg_count in zip(positionals, arg_counts):
sawine@0
  1848
                args = arg_strings[start_index: start_index + arg_count]
sawine@0
  1849
                start_index += arg_count
sawine@0
  1850
                take_action(action, args)
sawine@0
  1851
sawine@0
  1852
            # slice off the Positionals that we just parsed and return the
sawine@0
  1853
            # index at which the Positionals' string args stopped
sawine@0
  1854
            positionals[:] = positionals[len(arg_counts):]
sawine@0
  1855
            return start_index
sawine@0
  1856
sawine@0
  1857
        # consume Positionals and Optionals alternately, until we have
sawine@0
  1858
        # passed the last option string
sawine@0
  1859
        extras = []
sawine@0
  1860
        start_index = 0
sawine@0
  1861
        if option_string_indices:
sawine@0
  1862
            max_option_string_index = max(option_string_indices)
sawine@0
  1863
        else:
sawine@0
  1864
            max_option_string_index = -1
sawine@0
  1865
        while start_index <= max_option_string_index:
sawine@0
  1866
sawine@0
  1867
            # consume any Positionals preceding the next option
sawine@0
  1868
            next_option_string_index = min([
sawine@0
  1869
                index
sawine@0
  1870
                for index in option_string_indices
sawine@0
  1871
                if index >= start_index])
sawine@0
  1872
            if start_index != next_option_string_index:
sawine@0
  1873
                positionals_end_index = consume_positionals(start_index)
sawine@0
  1874
sawine@0
  1875
                # only try to parse the next optional if we didn't consume
sawine@0
  1876
                # the option string during the positionals parsing
sawine@0
  1877
                if positionals_end_index > start_index:
sawine@0
  1878
                    start_index = positionals_end_index
sawine@0
  1879
                    continue
sawine@0
  1880
                else:
sawine@0
  1881
                    start_index = positionals_end_index
sawine@0
  1882
sawine@0
  1883
            # if we consumed all the positionals we could and we're not
sawine@0
  1884
            # at the index of an option string, there were extra arguments
sawine@0
  1885
            if start_index not in option_string_indices:
sawine@0
  1886
                strings = arg_strings[start_index:next_option_string_index]
sawine@0
  1887
                extras.extend(strings)
sawine@0
  1888
                start_index = next_option_string_index
sawine@0
  1889
sawine@0
  1890
            # consume the next optional and any arguments for it
sawine@0
  1891
            start_index = consume_optional(start_index)
sawine@0
  1892
sawine@0
  1893
        # consume any positionals following the last Optional
sawine@0
  1894
        stop_index = consume_positionals(start_index)
sawine@0
  1895
sawine@0
  1896
        # if we didn't consume all the argument strings, there were extras
sawine@0
  1897
        extras.extend(arg_strings[stop_index:])
sawine@0
  1898
sawine@0
  1899
        # if we didn't use all the Positional objects, there were too few
sawine@0
  1900
        # arg strings supplied.
sawine@0
  1901
        if positionals:
sawine@0
  1902
            self.error(_('too few arguments'))
sawine@0
  1903
sawine@0
  1904
        # make sure all required actions were present
sawine@0
  1905
        for action in self._actions:
sawine@0
  1906
            if action.required:
sawine@0
  1907
                if action not in seen_actions:
sawine@0
  1908
                    name = _get_action_name(action)
sawine@0
  1909
                    self.error(_('argument %s is required') % name)
sawine@0
  1910
sawine@0
  1911
        # make sure all required groups had one option present
sawine@0
  1912
        for group in self._mutually_exclusive_groups:
sawine@0
  1913
            if group.required:
sawine@0
  1914
                for action in group._group_actions:
sawine@0
  1915
                    if action in seen_non_default_actions:
sawine@0
  1916
                        break
sawine@0
  1917
sawine@0
  1918
                # if no actions were used, report the error
sawine@0
  1919
                else:
sawine@0
  1920
                    names = [_get_action_name(action)
sawine@0
  1921
                             for action in group._group_actions
sawine@0
  1922
                             if action.help is not SUPPRESS]
sawine@0
  1923
                    msg = _('one of the arguments %s is required')
sawine@0
  1924
                    self.error(msg % ' '.join(names))
sawine@0
  1925
sawine@0
  1926
        # return the updated namespace and the extra arguments
sawine@0
  1927
        return namespace, extras
sawine@0
  1928
sawine@0
  1929
    def _read_args_from_files(self, arg_strings):
sawine@0
  1930
        # expand arguments referencing files
sawine@0
  1931
        new_arg_strings = []
sawine@0
  1932
        for arg_string in arg_strings:
sawine@0
  1933
sawine@0
  1934
            # for regular arguments, just add them back into the list
sawine@0
  1935
            if arg_string[0] not in self.fromfile_prefix_chars:
sawine@0
  1936
                new_arg_strings.append(arg_string)
sawine@0
  1937
sawine@0
  1938
            # replace arguments referencing files with the file content
sawine@0
  1939
            else:
sawine@0
  1940
                try:
sawine@0
  1941
                    args_file = open(arg_string[1:])
sawine@0
  1942
                    try:
sawine@0
  1943
                        arg_strings = []
sawine@0
  1944
                        for arg_line in args_file.read().splitlines():
sawine@0
  1945
                            for arg in self.convert_arg_line_to_args(arg_line):
sawine@0
  1946
                                arg_strings.append(arg)
sawine@0
  1947
                        arg_strings = self._read_args_from_files(arg_strings)
sawine@0
  1948
                        new_arg_strings.extend(arg_strings)
sawine@0
  1949
                    finally:
sawine@0
  1950
                        args_file.close()
sawine@0
  1951
                except IOError:
sawine@0
  1952
                    err = _sys.exc_info()[1]
sawine@0
  1953
                    self.error(str(err))
sawine@0
  1954
sawine@0
  1955
        # return the modified argument list
sawine@0
  1956
        return new_arg_strings
sawine@0
  1957
sawine@0
  1958
    def convert_arg_line_to_args(self, arg_line):
sawine@0
  1959
        return [arg_line]
sawine@0
  1960
sawine@0
  1961
    def _match_argument(self, action, arg_strings_pattern):
sawine@0
  1962
        # match the pattern for this action to the arg strings
sawine@0
  1963
        nargs_pattern = self._get_nargs_pattern(action)
sawine@0
  1964
        match = _re.match(nargs_pattern, arg_strings_pattern)
sawine@0
  1965
sawine@0
  1966
        # raise an exception if we weren't able to find a match
sawine@0
  1967
        if match is None:
sawine@0
  1968
            nargs_errors = {
sawine@0
  1969
                None: _('expected one argument'),
sawine@0
  1970
                OPTIONAL: _('expected at most one argument'),
sawine@0
  1971
                ONE_OR_MORE: _('expected at least one argument'),
sawine@0
  1972
            }
sawine@0
  1973
            default = _('expected %s argument(s)') % action.nargs
sawine@0
  1974
            msg = nargs_errors.get(action.nargs, default)
sawine@0
  1975
            raise ArgumentError(action, msg)
sawine@0
  1976
sawine@0
  1977
        # return the number of arguments matched
sawine@0
  1978
        return len(match.group(1))
sawine@0
  1979
sawine@0
  1980
    def _match_arguments_partial(self, actions, arg_strings_pattern):
sawine@0
  1981
        # progressively shorten the actions list by slicing off the
sawine@0
  1982
        # final actions until we find a match
sawine@0
  1983
        result = []
sawine@0
  1984
        for i in range(len(actions), 0, -1):
sawine@0
  1985
            actions_slice = actions[:i]
sawine@0
  1986
            pattern = ''.join([self._get_nargs_pattern(action)
sawine@0
  1987
                               for action in actions_slice])
sawine@0
  1988
            match = _re.match(pattern, arg_strings_pattern)
sawine@0
  1989
            if match is not None:
sawine@0
  1990
                result.extend([len(string) for string in match.groups()])
sawine@0
  1991
                break
sawine@0
  1992
sawine@0
  1993
        # return the list of arg string counts
sawine@0
  1994
        return result
sawine@0
  1995
sawine@0
  1996
    def _parse_optional(self, arg_string):
sawine@0
  1997
        # if it's an empty string, it was meant to be a positional
sawine@0
  1998
        if not arg_string:
sawine@0
  1999
            return None
sawine@0
  2000
sawine@0
  2001
        # if it doesn't start with a prefix, it was meant to be positional
sawine@0
  2002
        if not arg_string[0] in self.prefix_chars:
sawine@0
  2003
            return None
sawine@0
  2004
sawine@0
  2005
        # if the option string is present in the parser, return the action
sawine@0
  2006
        if arg_string in self._option_string_actions:
sawine@0
  2007
            action = self._option_string_actions[arg_string]
sawine@0
  2008
            return action, arg_string, None
sawine@0
  2009
sawine@0
  2010
        # if it's just a single character, it was meant to be positional
sawine@0
  2011
        if len(arg_string) == 1:
sawine@0
  2012
            return None
sawine@0
  2013
sawine@0
  2014
        # if the option string before the "=" is present, return the action
sawine@0
  2015
        if '=' in arg_string:
sawine@0
  2016
            option_string, explicit_arg = arg_string.split('=', 1)
sawine@0
  2017
            if option_string in self._option_string_actions:
sawine@0
  2018
                action = self._option_string_actions[option_string]
sawine@0
  2019
                return action, option_string, explicit_arg
sawine@0
  2020
sawine@0
  2021
        # search through all possible prefixes of the option string
sawine@0
  2022
        # and all actions in the parser for possible interpretations
sawine@0
  2023
        option_tuples = self._get_option_tuples(arg_string)
sawine@0
  2024
sawine@0
  2025
        # if multiple actions match, the option string was ambiguous
sawine@0
  2026
        if len(option_tuples) > 1:
sawine@0
  2027
            options = ', '.join([option_string
sawine@0
  2028
                for action, option_string, explicit_arg in option_tuples])
sawine@0
  2029
            tup = arg_string, options
sawine@0
  2030
            self.error(_('ambiguous option: %s could match %s') % tup)
sawine@0
  2031
sawine@0
  2032
        # if exactly one action matched, this segmentation is good,
sawine@0
  2033
        # so return the parsed action
sawine@0
  2034
        elif len(option_tuples) == 1:
sawine@0
  2035
            option_tuple, = option_tuples
sawine@0
  2036
            return option_tuple
sawine@0
  2037
sawine@0
  2038
        # if it was not found as an option, but it looks like a negative
sawine@0
  2039
        # number, it was meant to be positional
sawine@0
  2040
        # unless there are negative-number-like options
sawine@0
  2041
        if self._negative_number_matcher.match(arg_string):
sawine@0
  2042
            if not self._has_negative_number_optionals:
sawine@0
  2043
                return None
sawine@0
  2044
sawine@0
  2045
        # if it contains a space, it was meant to be a positional
sawine@0
  2046
        if ' ' in arg_string:
sawine@0
  2047
            return None
sawine@0
  2048
sawine@0
  2049
        # it was meant to be an optional but there is no such option
sawine@0
  2050
        # in this parser (though it might be a valid option in a subparser)
sawine@0
  2051
        return None, arg_string, None
sawine@0
  2052
sawine@0
  2053
    def _get_option_tuples(self, option_string):
sawine@0
  2054
        result = []
sawine@0
  2055
sawine@0
  2056
        # option strings starting with two prefix characters are only
sawine@0
  2057
        # split at the '='
sawine@0
  2058
        chars = self.prefix_chars
sawine@0
  2059
        if option_string[0] in chars and option_string[1] in chars:
sawine@0
  2060
            if '=' in option_string:
sawine@0
  2061
                option_prefix, explicit_arg = option_string.split('=', 1)
sawine@0
  2062
            else:
sawine@0
  2063
                option_prefix = option_string
sawine@0
  2064
                explicit_arg = None
sawine@0
  2065
            for option_string in self._option_string_actions:
sawine@0
  2066
                if option_string.startswith(option_prefix):
sawine@0
  2067
                    action = self._option_string_actions[option_string]
sawine@0
  2068
                    tup = action, option_string, explicit_arg
sawine@0
  2069
                    result.append(tup)
sawine@0
  2070
sawine@0
  2071
        # single character options can be concatenated with their arguments
sawine@0
  2072
        # but multiple character options always have to have their argument
sawine@0
  2073
        # separate
sawine@0
  2074
        elif option_string[0] in chars and option_string[1] not in chars:
sawine@0
  2075
            option_prefix = option_string
sawine@0
  2076
            explicit_arg = None
sawine@0
  2077
            short_option_prefix = option_string[:2]
sawine@0
  2078
            short_explicit_arg = option_string[2:]
sawine@0
  2079
sawine@0
  2080
            for option_string in self._option_string_actions:
sawine@0
  2081
                if option_string == short_option_prefix:
sawine@0
  2082
                    action = self._option_string_actions[option_string]
sawine@0
  2083
                    tup = action, option_string, short_explicit_arg
sawine@0
  2084
                    result.append(tup)
sawine@0
  2085
                elif option_string.startswith(option_prefix):
sawine@0
  2086
                    action = self._option_string_actions[option_string]
sawine@0
  2087
                    tup = action, option_string, explicit_arg
sawine@0
  2088
                    result.append(tup)
sawine@0
  2089
sawine@0
  2090
        # shouldn't ever get here
sawine@0
  2091
        else:
sawine@0
  2092
            self.error(_('unexpected option string: %s') % option_string)
sawine@0
  2093
sawine@0
  2094
        # return the collected option tuples
sawine@0
  2095
        return result
sawine@0
  2096
sawine@0
  2097
    def _get_nargs_pattern(self, action):
sawine@0
  2098
        # in all examples below, we have to allow for '--' args
sawine@0
  2099
        # which are represented as '-' in the pattern
sawine@0
  2100
        nargs = action.nargs
sawine@0
  2101
sawine@0
  2102
        # the default (None) is assumed to be a single argument
sawine@0
  2103
        if nargs is None:
sawine@0
  2104
            nargs_pattern = '(-*A-*)'
sawine@0
  2105
sawine@0
  2106
        # allow zero or one arguments
sawine@0
  2107
        elif nargs == OPTIONAL:
sawine@0
  2108
            nargs_pattern = '(-*A?-*)'
sawine@0
  2109
sawine@0
  2110
        # allow zero or more arguments
sawine@0
  2111
        elif nargs == ZERO_OR_MORE:
sawine@0
  2112
            nargs_pattern = '(-*[A-]*)'
sawine@0
  2113
sawine@0
  2114
        # allow one or more arguments
sawine@0
  2115
        elif nargs == ONE_OR_MORE:
sawine@0
  2116
            nargs_pattern = '(-*A[A-]*)'
sawine@0
  2117
sawine@0
  2118
        # allow any number of options or arguments
sawine@0
  2119
        elif nargs == REMAINDER:
sawine@0
  2120
            nargs_pattern = '([-AO]*)'
sawine@0
  2121
sawine@0
  2122
        # allow one argument followed by any number of options or arguments
sawine@0
  2123
        elif nargs == PARSER:
sawine@0
  2124
            nargs_pattern = '(-*A[-AO]*)'
sawine@0
  2125
sawine@0
  2126
        # all others should be integers
sawine@0
  2127
        else:
sawine@0
  2128
            nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
sawine@0
  2129
sawine@0
  2130
        # if this is an optional action, -- is not allowed
sawine@0
  2131
        if action.option_strings:
sawine@0
  2132
            nargs_pattern = nargs_pattern.replace('-*', '')
sawine@0
  2133
            nargs_pattern = nargs_pattern.replace('-', '')
sawine@0
  2134
sawine@0
  2135
        # return the pattern
sawine@0
  2136
        return nargs_pattern
sawine@0
  2137
sawine@0
  2138
    # ========================
sawine@0
  2139
    # Value conversion methods
sawine@0
  2140
    # ========================
sawine@0
  2141
    def _get_values(self, action, arg_strings):
sawine@0
  2142
        # for everything but PARSER args, strip out '--'
sawine@0
  2143
        if action.nargs not in [PARSER, REMAINDER]:
sawine@0
  2144
            arg_strings = [s for s in arg_strings if s != '--']
sawine@0
  2145
sawine@0
  2146
        # optional argument produces a default when not present
sawine@0
  2147
        if not arg_strings and action.nargs == OPTIONAL:
sawine@0
  2148
            if action.option_strings:
sawine@0
  2149
                value = action.const
sawine@0
  2150
            else:
sawine@0
  2151
                value = action.default
sawine@0
  2152
            if isinstance(value, str):
sawine@0
  2153
                value = self._get_value(action, value)
sawine@0
  2154
                self._check_value(action, value)
sawine@0
  2155
sawine@0
  2156
        # when nargs='*' on a positional, if there were no command-line
sawine@0
  2157
        # args, use the default if it is anything other than None
sawine@0
  2158
        elif (not arg_strings and action.nargs == ZERO_OR_MORE and
sawine@0
  2159
              not action.option_strings):
sawine@0
  2160
            if action.default is not None:
sawine@0
  2161
                value = action.default
sawine@0
  2162
            else:
sawine@0
  2163
                value = arg_strings
sawine@0
  2164
            self._check_value(action, value)
sawine@0
  2165
sawine@0
  2166
        # single argument or optional argument produces a single value
sawine@0
  2167
        elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
sawine@0
  2168
            arg_string, = arg_strings
sawine@0
  2169
            value = self._get_value(action, arg_string)
sawine@0
  2170
            self._check_value(action, value)
sawine@0
  2171
sawine@0
  2172
        # REMAINDER arguments convert all values, checking none
sawine@0
  2173
        elif action.nargs == REMAINDER:
sawine@0
  2174
            value = [self._get_value(action, v) for v in arg_strings]
sawine@0
  2175
sawine@0
  2176
        # PARSER arguments convert all values, but check only the first
sawine@0
  2177
        elif action.nargs == PARSER:
sawine@0
  2178
            value = [self._get_value(action, v) for v in arg_strings]
sawine@0
  2179
            self._check_value(action, value[0])
sawine@0
  2180
sawine@0
  2181
        # all other types of nargs produce a list
sawine@0
  2182
        else:
sawine@0
  2183
            value = [self._get_value(action, v) for v in arg_strings]
sawine@0
  2184
            for v in value:
sawine@0
  2185
                self._check_value(action, v)
sawine@0
  2186
sawine@0
  2187
        # return the converted value
sawine@0
  2188
        return value
sawine@0
  2189
sawine@0
  2190
    def _get_value(self, action, arg_string):
sawine@0
  2191
        type_func = self._registry_get('type', action.type, action.type)
sawine@0
  2192
        if not _callable(type_func):
sawine@0
  2193
            msg = _('%r is not callable')
sawine@0
  2194
            raise ArgumentError(action, msg % type_func)
sawine@0
  2195
sawine@0
  2196
        # convert the value to the appropriate type
sawine@0
  2197
        try:
sawine@0
  2198
            result = type_func(arg_string)
sawine@0
  2199
sawine@0
  2200
        # ArgumentTypeErrors indicate errors
sawine@0
  2201
        except ArgumentTypeError:
sawine@0
  2202
            name = getattr(action.type, '__name__', repr(action.type))
sawine@0
  2203
            msg = str(_sys.exc_info()[1])
sawine@0
  2204
            raise ArgumentError(action, msg)
sawine@0
  2205
sawine@0
  2206
        # TypeErrors or ValueErrors also indicate errors
sawine@0
  2207
        except (TypeError, ValueError):
sawine@0
  2208
            name = getattr(action.type, '__name__', repr(action.type))
sawine@0
  2209
            msg = _('invalid %s value: %r')
sawine@0
  2210
            raise ArgumentError(action, msg % (name, arg_string))
sawine@0
  2211
sawine@0
  2212
        # return the converted value
sawine@0
  2213
        return result
sawine@0
  2214
sawine@0
  2215
    def _check_value(self, action, value):
sawine@0
  2216
        # converted value must be one of the choices (if specified)
sawine@0
  2217
        if action.choices is not None and value not in action.choices:
sawine@0
  2218
            tup = value, ', '.join(map(repr, action.choices))
sawine@0
  2219
            msg = _('invalid choice: %r (choose from %s)') % tup
sawine@0
  2220
            raise ArgumentError(action, msg)
sawine@0
  2221
sawine@0
  2222
    # =======================
sawine@0
  2223
    # Help-formatting methods
sawine@0
  2224
    # =======================
sawine@0
  2225
    def format_usage(self):
sawine@0
  2226
        formatter = self._get_formatter()
sawine@0
  2227
        formatter.add_usage(self.usage, self._actions,
sawine@0
  2228
                            self._mutually_exclusive_groups)
sawine@0
  2229
        return formatter.format_help()
sawine@0
  2230
sawine@0
  2231
    def format_help(self):
sawine@0
  2232
        formatter = self._get_formatter()
sawine@0
  2233
sawine@0
  2234
        # usage
sawine@0
  2235
        formatter.add_usage(self.usage, self._actions,
sawine@0
  2236
                            self._mutually_exclusive_groups)
sawine@0
  2237
sawine@0
  2238
        # description
sawine@0
  2239
        formatter.add_text(self.description)
sawine@0
  2240
sawine@0
  2241
        # positionals, optionals and user-defined groups
sawine@0
  2242
        for action_group in self._action_groups:
sawine@0
  2243
            formatter.start_section(action_group.title)
sawine@0
  2244
            formatter.add_text(action_group.description)
sawine@0
  2245
            formatter.add_arguments(action_group._group_actions)
sawine@0
  2246
            formatter.end_section()
sawine@0
  2247
sawine@0
  2248
        # epilog
sawine@0
  2249
        formatter.add_text(self.epilog)
sawine@0
  2250
sawine@0
  2251
        # determine help from format above
sawine@0
  2252
        return formatter.format_help()
sawine@0
  2253
sawine@0
  2254
    def format_version(self):
sawine@0
  2255
        import warnings
sawine@0
  2256
        warnings.warn(
sawine@0
  2257
            'The format_version method is deprecated -- the "version" '
sawine@0
  2258
            'argument to ArgumentParser is no longer supported.',
sawine@0
  2259
            DeprecationWarning)
sawine@0
  2260
        formatter = self._get_formatter()
sawine@0
  2261
        formatter.add_text(self.version)
sawine@0
  2262
        return formatter.format_help()
sawine@0
  2263
sawine@0
  2264
    def _get_formatter(self):
sawine@0
  2265
        return self.formatter_class(prog=self.prog)
sawine@0
  2266
sawine@0
  2267
    # =====================
sawine@0
  2268
    # Help-printing methods
sawine@0
  2269
    # =====================
sawine@0
  2270
    def print_usage(self, file=None):
sawine@0
  2271
        if file is None:
sawine@0
  2272
            file = _sys.stdout
sawine@0
  2273
        self._print_message(self.format_usage(), file)
sawine@0
  2274
sawine@0
  2275
    def print_help(self, file=None):
sawine@0
  2276
        if file is None:
sawine@0
  2277
            file = _sys.stdout
sawine@0
  2278
        self._print_message(self.format_help(), file)
sawine@0
  2279
sawine@0
  2280
    def print_version(self, file=None):
sawine@0
  2281
        import warnings
sawine@0
  2282
        warnings.warn(
sawine@0
  2283
            'The print_version method is deprecated -- the "version" '
sawine@0
  2284
            'argument to ArgumentParser is no longer supported.',
sawine@0
  2285
            DeprecationWarning)
sawine@0
  2286
        self._print_message(self.format_version(), file)
sawine@0
  2287
sawine@0
  2288
    def _print_message(self, message, file=None):
sawine@0
  2289
        if message:
sawine@0
  2290
            if file is None:
sawine@0
  2291
                file = _sys.stderr
sawine@0
  2292
            file.write(message)
sawine@0
  2293
sawine@0
  2294
    # ===============
sawine@0
  2295
    # Exiting methods
sawine@0
  2296
    # ===============
sawine@0
  2297
    def exit(self, status=0, message=None):
sawine@0
  2298
        if message:
sawine@0
  2299
            self._print_message(message, _sys.stderr)
sawine@0
  2300
        _sys.exit(status)
sawine@0
  2301
sawine@0
  2302
    def error(self, message):
sawine@0
  2303
        """error(message: string)
sawine@0
  2304
sawine@0
  2305
        Prints a usage message incorporating the message to stderr and
sawine@0
  2306
        exits.
sawine@0
  2307
sawine@0
  2308
        If you override this in a subclass, it should not return -- it
sawine@0
  2309
        should either exit or raise an exception.
sawine@0
  2310
        """
sawine@0
  2311
        self.print_usage(_sys.stderr)
sawine@0
  2312
        self.exit(2, _('%s: error: %s\n') % (self.prog, message))