~ubuntu-branches/debian/stretch/electrum/stretch

« back to all changes in this revision

Viewing changes to gui/kivy/tools/.buildozer/android/platform/python-for-android/dist/kivy/buildlib/argparse.py

  • Committer: Package Import Robot
  • Author(s): Tristan Seligmann
  • Date: 2016-04-04 03:02:39 UTC
  • mfrom: (1.1.10)
  • Revision ID: package-import@ubuntu.com-20160404030239-0szgkio8yryjv7c9
Tags: 2.6.3-1
* New upstream release.
  - Drop backported install-wizard-connect.patch.
* Add Suggests: python-zbar and update the installation hint to suggest
  apt-get instead of pip (closes: #819517).
* Bump Standards-Version to 3.9.7 (no changes).
* Update Vcs-* links.

Show diffs side-by-side

added added

removed removed

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