##// END OF EJS Templates
Update internal argparse to version 1.1...
Thomas Spura -
Show More
@@ -1,18 +1,4 b''
1 # -*- coding: utf-8 -*-
1 # Author: Steven J. Bethard <steven.bethard@gmail.com>.
2
3 # Copyright © 2006-2009 Steven J. Bethard <steven.bethard@gmail.com>.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
6 # use this file except in compliance with the License. You may obtain a copy
7 # of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16
2
17 """Command-line parsing library
3 """Command-line parsing library
18
4
@@ -75,7 +61,7 b' considered public as object names -- the API of the formatter objects is'
75 still considered an implementation detail.)
61 still considered an implementation detail.)
76 """
62 """
77
63
78 __version__ = '1.1a1'
64 __version__ = '1.1'
79 __all__ = [
65 __all__ = [
80 'ArgumentParser',
66 'ArgumentParser',
81 'ArgumentError',
67 'ArgumentError',
@@ -97,40 +83,10 b' import textwrap as _textwrap'
97
83
98 from gettext import gettext as _
84 from gettext import gettext as _
99
85
100 try:
101 _set = set
102 except NameError:
103 from sets import Set as _set
104
105 try:
106 _basestring = basestring
107 except NameError:
108 _basestring = str
109
110 try:
111 _sorted = sorted
112 except NameError:
113
114 def _sorted(iterable, reverse=False):
115 result = list(iterable)
116 result.sort()
117 if reverse:
118 result.reverse()
119 return result
120
121
86
122 def _callable(obj):
87 def _callable(obj):
123 return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
88 return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
124
89
125 # silence Python 2.6 buggy warnings about Exception.message
126 if _sys.version_info[:2] == (2, 6):
127 import warnings
128 warnings.filterwarnings(
129 action='ignore',
130 message='BaseException.message has been deprecated as of Python 2.6',
131 category=DeprecationWarning,
132 module='argparse')
133
134
90
135 SUPPRESS = '==SUPPRESS=='
91 SUPPRESS = '==SUPPRESS=='
136
92
@@ -163,7 +119,7 b' class _AttributeHolder(object):'
163 return '%s(%s)' % (type_name, ', '.join(arg_strings))
119 return '%s(%s)' % (type_name, ', '.join(arg_strings))
164
120
165 def _get_kwargs(self):
121 def _get_kwargs(self):
166 return _sorted(self.__dict__.items())
122 return sorted(self.__dict__.items())
167
123
168 def _get_args(self):
124 def _get_args(self):
169 return []
125 return []
@@ -416,7 +372,7 b' class HelpFormatter(object):'
416
372
417 def _format_actions_usage(self, actions, groups):
373 def _format_actions_usage(self, actions, groups):
418 # find group indices and identify actions in groups
374 # find group indices and identify actions in groups
419 group_actions = _set()
375 group_actions = set()
420 inserts = {}
376 inserts = {}
421 for group in groups:
377 for group in groups:
422 try:
378 try:
@@ -486,7 +442,7 b' class HelpFormatter(object):'
486 parts.append(part)
442 parts.append(part)
487
443
488 # insert things at the necessary indices
444 # insert things at the necessary indices
489 for i in _sorted(inserts, reverse=True):
445 for i in sorted(inserts, reverse=True):
490 parts[i:i] = [inserts[i]]
446 parts[i:i] = [inserts[i]]
491
447
492 # join all the action items with spaces
448 # join all the action items with spaces
@@ -621,6 +577,9 b' class HelpFormatter(object):'
621 for name in list(params):
577 for name in list(params):
622 if params[name] is SUPPRESS:
578 if params[name] is SUPPRESS:
623 del params[name]
579 del params[name]
580 for name in list(params):
581 if hasattr(params[name], '__name__'):
582 params[name] = params[name].__name__
624 if params.get('choices') is not None:
583 if params.get('choices') is not None:
625 choices_str = ', '.join([str(c) for c in params['choices']])
584 choices_str = ', '.join([str(c) for c in params['choices']])
626 params['choices'] = choices_str
585 params['choices'] = choices_str
@@ -1028,7 +987,7 b' class _VersionAction(Action):'
1028 version=None,
987 version=None,
1029 dest=SUPPRESS,
988 dest=SUPPRESS,
1030 default=SUPPRESS,
989 default=SUPPRESS,
1031 help=None):
990 help="show program's version number and exit"):
1032 super(_VersionAction, self).__init__(
991 super(_VersionAction, self).__init__(
1033 option_strings=option_strings,
992 option_strings=option_strings,
1034 dest=dest,
993 dest=dest,
@@ -1169,7 +1128,10 b' class Namespace(_AttributeHolder):'
1169 """
1128 """
1170
1129
1171 def __init__(self, **kwargs):
1130 def __init__(self, **kwargs):
1172 self.__dict__.update(**kwargs)
1131 for name in kwargs:
1132 setattr(self, name, kwargs[name])
1133
1134 __hash__ = None
1173
1135
1174 def __eq__(self, other):
1136 def __eq__(self, other):
1175 return vars(self) == vars(other)
1137 return vars(self) == vars(other)
@@ -1296,6 +1258,12 b' class _ActionsContainer(object):'
1296 if not _callable(action_class):
1258 if not _callable(action_class):
1297 raise ValueError('unknown action "%s"' % action_class)
1259 raise ValueError('unknown action "%s"' % action_class)
1298 action = action_class(**kwargs)
1260 action = action_class(**kwargs)
1261
1262 # raise an error if the action type is not callable
1263 type_func = self._registry_get('type', action.type, action.type)
1264 if not _callable(type_func):
1265 raise ValueError('%r is not callable' % type_func)
1266
1299 return self._add_action(action)
1267 return self._add_action(action)
1300
1268
1301 def add_argument_group(self, *args, **kwargs):
1269 def add_argument_group(self, *args, **kwargs):
@@ -1393,12 +1361,6 b' class _ActionsContainer(object):'
1393 option_strings = []
1361 option_strings = []
1394 long_option_strings = []
1362 long_option_strings = []
1395 for option_string in args:
1363 for option_string in args:
1396 # error on one-or-fewer-character option strings
1397 if len(option_string) < 2:
1398 msg = _('invalid option string %r: '
1399 'must be at least two characters long')
1400 raise ValueError(msg % option_string)
1401
1402 # error on strings that don't start with an appropriate prefix
1364 # error on strings that don't start with an appropriate prefix
1403 if not option_string[0] in self.prefix_chars:
1365 if not option_string[0] in self.prefix_chars:
1404 msg = _('invalid option string %r: '
1366 msg = _('invalid option string %r: '
@@ -1406,18 +1368,12 b' class _ActionsContainer(object):'
1406 tup = option_string, self.prefix_chars
1368 tup = option_string, self.prefix_chars
1407 raise ValueError(msg % tup)
1369 raise ValueError(msg % tup)
1408
1370
1409 # error on strings that are all prefix characters
1410 if not (_set(option_string) - _set(self.prefix_chars)):
1411 msg = _('invalid option string %r: '
1412 'must contain characters other than %r')
1413 tup = option_string, self.prefix_chars
1414 raise ValueError(msg % tup)
1415
1416 # strings starting with two prefix characters are long options
1371 # strings starting with two prefix characters are long options
1417 option_strings.append(option_string)
1372 option_strings.append(option_string)
1418 if option_string[0] in self.prefix_chars:
1373 if option_string[0] in self.prefix_chars:
1419 if option_string[1] in self.prefix_chars:
1374 if len(option_string) > 1:
1420 long_option_strings.append(option_string)
1375 if option_string[1] in self.prefix_chars:
1376 long_option_strings.append(option_string)
1421
1377
1422 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1378 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1423 dest = kwargs.pop('dest', None)
1379 dest = kwargs.pop('dest', None)
@@ -1427,6 +1383,9 b' class _ActionsContainer(object):'
1427 else:
1383 else:
1428 dest_option_string = option_strings[0]
1384 dest_option_string = option_strings[0]
1429 dest = dest_option_string.lstrip(self.prefix_chars)
1385 dest = dest_option_string.lstrip(self.prefix_chars)
1386 if not dest:
1387 msg = _('dest= is required for options like %r')
1388 raise ValueError(msg % option_string)
1430 dest = dest.replace('-', '_')
1389 dest = dest.replace('-', '_')
1431
1390
1432 # return the updated keyword arguments
1391 # return the updated keyword arguments
@@ -1542,7 +1501,6 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
1542 - usage -- A usage message (default: auto-generated from arguments)
1501 - usage -- A usage message (default: auto-generated from arguments)
1543 - description -- A description of what the program does
1502 - description -- A description of what the program does
1544 - epilog -- Text following the argument descriptions
1503 - epilog -- Text following the argument descriptions
1545 - version -- Add a -v/--version option with the given version string
1546 - parents -- Parsers whose arguments should be copied into this one
1504 - parents -- Parsers whose arguments should be copied into this one
1547 - formatter_class -- HelpFormatter class for printing help messages
1505 - formatter_class -- HelpFormatter class for printing help messages
1548 - prefix_chars -- Characters that prefix optional arguments
1506 - prefix_chars -- Characters that prefix optional arguments
@@ -1567,6 +1525,14 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
1567 conflict_handler='error',
1525 conflict_handler='error',
1568 add_help=True):
1526 add_help=True):
1569
1527
1528 if version is not None:
1529 import warnings
1530 warnings.warn(
1531 """The "version" argument to ArgumentParser is deprecated. """
1532 """Please use """
1533 """"add_argument(..., action='version', version="N", ...)" """
1534 """instead""", DeprecationWarning)
1535
1570 superinit = super(ArgumentParser, self).__init__
1536 superinit = super(ArgumentParser, self).__init__
1571 superinit(description=description,
1537 superinit(description=description,
1572 prefix_chars=prefix_chars,
1538 prefix_chars=prefix_chars,
@@ -1708,7 +1674,7 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
1708 if not hasattr(namespace, action.dest):
1674 if not hasattr(namespace, action.dest):
1709 if action.default is not SUPPRESS:
1675 if action.default is not SUPPRESS:
1710 default = action.default
1676 default = action.default
1711 if isinstance(action.default, _basestring):
1677 if isinstance(action.default, basestring):
1712 default = self._get_value(action, default)
1678 default = self._get_value(action, default)
1713 setattr(namespace, action.dest, default)
1679 setattr(namespace, action.dest, default)
1714
1680
@@ -1768,8 +1734,8 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
1768 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1734 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1769
1735
1770 # converts arg strings to the appropriate and then takes the action
1736 # converts arg strings to the appropriate and then takes the action
1771 seen_actions = _set()
1737 seen_actions = set()
1772 seen_non_default_actions = _set()
1738 seen_non_default_actions = set()
1773
1739
1774 def take_action(action, argument_strings, option_string=None):
1740 def take_action(action, argument_strings, option_string=None):
1775 seen_actions.add(action)
1741 seen_actions.add(action)
@@ -1973,7 +1939,10 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
1973 try:
1939 try:
1974 args_file = open(arg_string[1:])
1940 args_file = open(arg_string[1:])
1975 try:
1941 try:
1976 arg_strings = args_file.read().splitlines()
1942 arg_strings = []
1943 for arg_line in args_file.read().splitlines():
1944 for arg in self.convert_arg_line_to_args(arg_line):
1945 arg_strings.append(arg)
1977 arg_strings = self._read_args_from_files(arg_strings)
1946 arg_strings = self._read_args_from_files(arg_strings)
1978 new_arg_strings.extend(arg_strings)
1947 new_arg_strings.extend(arg_strings)
1979 finally:
1948 finally:
@@ -1985,6 +1954,9 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
1985 # return the modified argument list
1954 # return the modified argument list
1986 return new_arg_strings
1955 return new_arg_strings
1987
1956
1957 def convert_arg_line_to_args(self, arg_line):
1958 return [arg_line]
1959
1988 def _match_argument(self, action, arg_strings_pattern):
1960 def _match_argument(self, action, arg_strings_pattern):
1989 # match the pattern for this action to the arg strings
1961 # match the pattern for this action to the arg strings
1990 nargs_pattern = self._get_nargs_pattern(action)
1962 nargs_pattern = self._get_nargs_pattern(action)
@@ -2029,15 +2001,15 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
2029 if not arg_string[0] in self.prefix_chars:
2001 if not arg_string[0] in self.prefix_chars:
2030 return None
2002 return None
2031
2003
2032 # if it's just dashes, it was meant to be positional
2033 if not arg_string.strip('-'):
2034 return None
2035
2036 # if the option string is present in the parser, return the action
2004 # if the option string is present in the parser, return the action
2037 if arg_string in self._option_string_actions:
2005 if arg_string in self._option_string_actions:
2038 action = self._option_string_actions[arg_string]
2006 action = self._option_string_actions[arg_string]
2039 return action, arg_string, None
2007 return action, arg_string, None
2040
2008
2009 # if it's just a single character, it was meant to be positional
2010 if len(arg_string) == 1:
2011 return None
2012
2041 # if the option string before the "=" is present, return the action
2013 # if the option string before the "=" is present, return the action
2042 if '=' in arg_string:
2014 if '=' in arg_string:
2043 option_string, explicit_arg = arg_string.split('=', 1)
2015 option_string, explicit_arg = arg_string.split('=', 1)
@@ -2176,7 +2148,7 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
2176 value = action.const
2148 value = action.const
2177 else:
2149 else:
2178 value = action.default
2150 value = action.default
2179 if isinstance(value, _basestring):
2151 if isinstance(value, basestring):
2180 value = self._get_value(action, value)
2152 value = self._get_value(action, value)
2181 self._check_value(action, value)
2153 self._check_value(action, value)
2182
2154
@@ -2279,6 +2251,11 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
2279 return formatter.format_help()
2251 return formatter.format_help()
2280
2252
2281 def format_version(self):
2253 def format_version(self):
2254 import warnings
2255 warnings.warn(
2256 'The format_version method is deprecated -- the "version" '
2257 'argument to ArgumentParser is no longer supported.',
2258 DeprecationWarning)
2282 formatter = self._get_formatter()
2259 formatter = self._get_formatter()
2283 formatter.add_text(self.version)
2260 formatter.add_text(self.version)
2284 return formatter.format_help()
2261 return formatter.format_help()
@@ -2300,6 +2277,11 b' class ArgumentParser(_AttributeHolder, _ActionsContainer):'
2300 self._print_message(self.format_help(), file)
2277 self._print_message(self.format_help(), file)
2301
2278
2302 def print_version(self, file=None):
2279 def print_version(self, file=None):
2280 import warnings
2281 warnings.warn(
2282 'The print_version method is deprecated -- the "version" '
2283 'argument to ArgumentParser is no longer supported.',
2284 DeprecationWarning)
2303 self._print_message(self.format_version(), file)
2285 self._print_message(self.format_version(), file)
2304
2286
2305 def _print_message(self, message, file=None):
2287 def _print_message(self, message, file=None):
General Comments 0
You need to be logged in to leave comments. Login now