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