diff options
author | shadchin <shadchin@yandex-team.ru> | 2022-02-10 16:44:39 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:44:39 +0300 |
commit | e9656aae26e0358d5378e5b63dcac5c8dbe0e4d0 (patch) | |
tree | 64175d5cadab313b3e7039ebaa06c5bc3295e274 /contrib/tools/python3/src/Lib/argparse.py | |
parent | 2598ef1d0aee359b4b6d5fdd1758916d5907d04f (diff) | |
download | ydb-e9656aae26e0358d5378e5b63dcac5c8dbe0e4d0.tar.gz |
Restoring authorship annotation for <shadchin@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'contrib/tools/python3/src/Lib/argparse.py')
-rw-r--r-- | contrib/tools/python3/src/Lib/argparse.py | 298 |
1 files changed, 149 insertions, 149 deletions
diff --git a/contrib/tools/python3/src/Lib/argparse.py b/contrib/tools/python3/src/Lib/argparse.py index f9b0dd4aa4..40569437ac 100644 --- a/contrib/tools/python3/src/Lib/argparse.py +++ b/contrib/tools/python3/src/Lib/argparse.py @@ -1,5 +1,5 @@ # Author: Steven J. Bethard <steven.bethard@gmail.com>. -# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com> +# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com> """Command-line parsing library @@ -67,7 +67,7 @@ __all__ = [ 'ArgumentParser', 'ArgumentError', 'ArgumentTypeError', - 'BooleanOptionalAction', + 'BooleanOptionalAction', 'FileType', 'HelpFormatter', 'ArgumentDefaultsHelpFormatter', @@ -129,7 +129,7 @@ class _AttributeHolder(object): return '%s(%s)' % (type_name, ', '.join(arg_strings)) def _get_kwargs(self): - return list(self.__dict__.items()) + return list(self.__dict__.items()) def _get_args(self): return [] @@ -166,8 +166,8 @@ class HelpFormatter(object): # default setting for width if width is None: - import shutil - width = shutil.get_terminal_size().columns + import shutil + width = shutil.get_terminal_size().columns width -= 2 self._prog = prog @@ -264,7 +264,7 @@ class HelpFormatter(object): invocations.append(get_invocation(subaction)) # update the maximum item length - invocation_length = max(map(len, invocations)) + invocation_length = max(map(len, invocations)) action_length = invocation_length + self._current_indent self._action_max_length = max(self._action_max_length, action_length) @@ -392,9 +392,9 @@ class HelpFormatter(object): group_actions = set() inserts = {} for group in groups: - if not group._group_actions: - raise ValueError(f'empty group {group}') - + if not group._group_actions: + raise ValueError(f'empty group {group}') + try: start = actions.index(group._group_actions[0]) except ValueError: @@ -409,19 +409,19 @@ class HelpFormatter(object): inserts[start] += ' [' else: inserts[start] = '[' - if end in inserts: - inserts[end] += ']' - else: - inserts[end] = ']' + if end in inserts: + inserts[end] += ']' + else: + inserts[end] = ']' else: if start in inserts: inserts[start] += ' (' else: inserts[start] = '(' - if end in inserts: - inserts[end] += ')' - else: - inserts[end] = ')' + if end in inserts: + inserts[end] += ')' + else: + inserts[end] = ')' for i in range(start + 1, end): inserts[i] = '|' @@ -458,7 +458,7 @@ class HelpFormatter(object): # if the Optional doesn't take a value, format is: # -s or --long if action.nargs == 0: - part = action.format_usage() + part = action.format_usage() # if the Optional takes a value, format is: # -s ARGS or --long ARGS @@ -529,13 +529,13 @@ class HelpFormatter(object): parts = [action_header] # if there was help for the action, add lines of help text - if action.help and action.help.strip(): + if action.help and action.help.strip(): help_text = self._expand_help(action) - if help_text: - help_lines = self._split_lines(help_text, help_width) - parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) - for line in help_lines[1:]: - parts.append('%*s%s\n' % (help_position, '', line)) + if help_text: + help_lines = self._split_lines(help_text, help_width) + parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) + for line in help_lines[1:]: + parts.append('%*s%s\n' % (help_position, '', line)) # or add a newline if the description doesn't end with one elif not action_header.endswith('\n'): @@ -595,11 +595,11 @@ class HelpFormatter(object): elif action.nargs == OPTIONAL: result = '[%s]' % get_metavar(1) elif action.nargs == ZERO_OR_MORE: - metavar = get_metavar(1) - if len(metavar) == 2: - result = '[%s [%s ...]]' % metavar - else: - result = '[%s ...]' % metavar + metavar = get_metavar(1) + if len(metavar) == 2: + result = '[%s [%s ...]]' % metavar + else: + result = '[%s ...]' % metavar elif action.nargs == ONE_OR_MORE: result = '%s [%s ...]' % get_metavar(2) elif action.nargs == REMAINDER: @@ -609,10 +609,10 @@ class HelpFormatter(object): elif action.nargs == SUPPRESS: result = '' else: - try: - formats = ['%s' for _ in range(action.nargs)] - except TypeError: - raise ValueError("invalid nargs value") from None + try: + formats = ['%s' for _ in range(action.nargs)] + except TypeError: + raise ValueError("invalid nargs value") from None result = ' '.join(formats) % get_metavar(action.nargs) return result @@ -731,8 +731,8 @@ def _get_action_name(argument): return argument.metavar elif argument.dest not in (None, SUPPRESS): return argument.dest - elif argument.choices: - return '{' + ','.join(argument.choices) + '}' + elif argument.choices: + return '{' + ','.join(argument.choices) + '}' else: return None @@ -853,53 +853,53 @@ class Action(_AttributeHolder): ] return [(name, getattr(self, name)) for name in names] - def format_usage(self): - return self.option_strings[0] - + def format_usage(self): + return self.option_strings[0] + def __call__(self, parser, namespace, values, option_string=None): raise NotImplementedError(_('.__call__() not defined')) -class BooleanOptionalAction(Action): - def __init__(self, - option_strings, - dest, - default=None, - type=None, - choices=None, - required=False, - help=None, - metavar=None): - - _option_strings = [] - for option_string in option_strings: - _option_strings.append(option_string) - - if option_string.startswith('--'): - option_string = '--no-' + option_string[2:] - _option_strings.append(option_string) - - if help is not None and default is not None: - help += " (default: %(default)s)" - - super().__init__( - option_strings=_option_strings, - dest=dest, - nargs=0, - default=default, - type=type, - choices=choices, - required=required, - help=help, - metavar=metavar) - - def __call__(self, parser, namespace, values, option_string=None): - if option_string in self.option_strings: - setattr(namespace, self.dest, not option_string.startswith('--no-')) - - def format_usage(self): - return ' | '.join(self.option_strings) - - +class BooleanOptionalAction(Action): + def __init__(self, + option_strings, + dest, + default=None, + type=None, + choices=None, + required=False, + help=None, + metavar=None): + + _option_strings = [] + for option_string in option_strings: + _option_strings.append(option_string) + + if option_string.startswith('--'): + option_string = '--no-' + option_string[2:] + _option_strings.append(option_string) + + if help is not None and default is not None: + help += " (default: %(default)s)" + + super().__init__( + option_strings=_option_strings, + dest=dest, + nargs=0, + default=default, + type=type, + choices=choices, + required=required, + help=help, + metavar=metavar) + + def __call__(self, parser, namespace, values, option_string=None): + if option_string in self.option_strings: + setattr(namespace, self.dest, not option_string.startswith('--no-')) + + def format_usage(self): + return ' | '.join(self.option_strings) + + class _StoreAction(Action): def __init__(self, @@ -914,7 +914,7 @@ class _StoreAction(Action): help=None, metavar=None): if nargs == 0: - raise ValueError('nargs for store actions must be != 0; if you ' + raise ValueError('nargs for store actions must be != 0; if you ' 'have nothing to store, actions such as store ' 'true or store const may be more appropriate') if const is not None and nargs != OPTIONAL: @@ -1006,7 +1006,7 @@ class _AppendAction(Action): help=None, metavar=None): if nargs == 0: - raise ValueError('nargs for append actions must be != 0; if arg ' + raise ValueError('nargs for append actions must be != 0; if arg ' 'strings are not supplying the value to append, ' 'the append const action may be more appropriate') if const is not None and nargs != OPTIONAL: @@ -1212,18 +1212,18 @@ class _SubParsersAction(Action): # namespace for the relevant parts. subnamespace, arg_strings = parser.parse_known_args(arg_strings, None) for key, value in vars(subnamespace).items(): - setattr(namespace, key, value) + setattr(namespace, key, value) if arg_strings: vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) -class _ExtendAction(_AppendAction): - def __call__(self, parser, namespace, values, option_string=None): - items = getattr(namespace, self.dest, None) - items = _copy_items(items) - items.extend(values) - setattr(namespace, self.dest, items) +class _ExtendAction(_AppendAction): + def __call__(self, parser, namespace, values, option_string=None): + items = getattr(namespace, self.dest, None) + items = _copy_items(items) + items.extend(values) + setattr(namespace, self.dest, items) # ============== # Type classes @@ -1268,9 +1268,9 @@ class FileType(object): return open(string, self._mode, self._bufsize, self._encoding, self._errors) except OSError as e: - args = {'filename': string, 'error': e} - message = _("can't open '%(filename)s': %(error)s") - raise ArgumentTypeError(message % args) + args = {'filename': string, 'error': e} + message = _("can't open '%(filename)s': %(error)s") + raise ArgumentTypeError(message % args) def __repr__(self): args = self._mode, self._bufsize @@ -1333,7 +1333,7 @@ class _ActionsContainer(object): self.register('action', 'help', _HelpAction) self.register('action', 'version', _VersionAction) self.register('action', 'parsers', _SubParsersAction) - self.register('action', 'extend', _ExtendAction) + self.register('action', 'extend', _ExtendAction) # raise an exception if the conflict handler is invalid self._get_handler() @@ -1426,10 +1426,10 @@ class _ActionsContainer(object): if not callable(type_func): raise ValueError('%r is not callable' % (type_func,)) - if type_func is FileType: - raise ValueError('%r is a FileType class object, instance of it' - ' must be passed' % (type_func,)) - + if type_func is FileType: + raise ValueError('%r is a FileType class object, instance of it' + ' must be passed' % (type_func,)) + # raise an error if the metavar does not match the type if hasattr(self, "_get_formatter"): try: @@ -1544,8 +1544,8 @@ class _ActionsContainer(object): # strings starting with two prefix characters are long options option_strings.append(option_string) - if len(option_string) > 1 and option_string[1] in self.prefix_chars: - long_option_strings.append(option_string) + if len(option_string) > 1 and option_string[1] in self.prefix_chars: + long_option_strings.append(option_string) # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' dest = kwargs.pop('dest', None) @@ -1685,8 +1685,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): - conflict_handler -- String indicating how to handle conflicts - add_help -- Add a -h/-help option - allow_abbrev -- Allow long options to be abbreviated unambiguously - - exit_on_error -- Determines whether or not ArgumentParser exits with - error info when an error occurs + - exit_on_error -- Determines whether or not ArgumentParser exits with + error info when an error occurs """ def __init__(self, @@ -1701,8 +1701,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): argument_default=None, conflict_handler='error', add_help=True, - allow_abbrev=True, - exit_on_error=True): + allow_abbrev=True, + exit_on_error=True): superinit = super(ArgumentParser, self).__init__ superinit(description=description, @@ -1721,7 +1721,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): self.fromfile_prefix_chars = fromfile_prefix_chars self.add_help = add_help self.allow_abbrev = allow_abbrev - self.exit_on_error = exit_on_error + self.exit_on_error = exit_on_error add_group = self.add_argument_group self._positionals = add_group(_('positional arguments')) @@ -1846,26 +1846,26 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): if action.default is not SUPPRESS: setattr(namespace, action.dest, action.default) - # add any parser defaults that aren't present - for dest in self._defaults: - if not hasattr(namespace, dest): - setattr(namespace, dest, self._defaults[dest]) - + # add any parser defaults that aren't present + for dest in self._defaults: + if not hasattr(namespace, dest): + setattr(namespace, dest, self._defaults[dest]) + # parse the arguments and exit if there are any errors - if self.exit_on_error: - try: - namespace, args = self._parse_known_args(args, namespace) - except ArgumentError: - err = _sys.exc_info()[1] - self.error(str(err)) - else: + if self.exit_on_error: + try: + namespace, args = self._parse_known_args(args, namespace) + except ArgumentError: + err = _sys.exc_info()[1] + self.error(str(err)) + else: namespace, args = self._parse_known_args(args, namespace) - if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): - args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) - delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) - return namespace, args - + if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): + args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) + delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) + return namespace, args + def _parse_known_args(self, arg_strings, namespace): # replace arg strings that are file references if self.fromfile_prefix_chars is not None: @@ -2153,9 +2153,9 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): OPTIONAL: _('expected at most one argument'), ONE_OR_MORE: _('expected at least one argument'), } - msg = nargs_errors.get(action.nargs) - if msg is None: - msg = ngettext('expected %s argument', + msg = nargs_errors.get(action.nargs) + if msg is None: + msg = ngettext('expected %s argument', 'expected %s arguments', action.nargs) % action.nargs raise ArgumentError(action, msg) @@ -2204,23 +2204,23 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): action = self._option_string_actions[option_string] return action, option_string, explicit_arg - # search through all possible prefixes of the option string - # and all actions in the parser for possible interpretations - option_tuples = self._get_option_tuples(arg_string) + # search through all possible prefixes of the option string + # and all actions in the parser for possible interpretations + option_tuples = self._get_option_tuples(arg_string) - # if multiple actions match, the option string was ambiguous - if len(option_tuples) > 1: - options = ', '.join([option_string - for action, option_string, explicit_arg in option_tuples]) - args = {'option': arg_string, 'matches': options} - msg = _('ambiguous option: %(option)s could match %(matches)s') - self.error(msg % args) + # if multiple actions match, the option string was ambiguous + if len(option_tuples) > 1: + options = ', '.join([option_string + for action, option_string, explicit_arg in option_tuples]) + args = {'option': arg_string, 'matches': options} + msg = _('ambiguous option: %(option)s could match %(matches)s') + self.error(msg % args) - # if exactly one action matched, this segmentation is good, - # so return the parsed action - elif len(option_tuples) == 1: - option_tuple, = option_tuples - return option_tuple + # if exactly one action matched, this segmentation is good, + # so return the parsed action + elif len(option_tuples) == 1: + option_tuple, = option_tuples + return option_tuple # if it was not found as an option, but it looks like a negative # number, it was meant to be positional @@ -2244,17 +2244,17 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): # split at the '=' chars = self.prefix_chars if option_string[0] in chars and option_string[1] in chars: - if self.allow_abbrev: - if '=' in option_string: - option_prefix, explicit_arg = option_string.split('=', 1) - else: - option_prefix = option_string - explicit_arg = None - for option_string in self._option_string_actions: - if option_string.startswith(option_prefix): - action = self._option_string_actions[option_string] - tup = action, option_string, explicit_arg - result.append(tup) + if self.allow_abbrev: + if '=' in option_string: + option_prefix, explicit_arg = option_string.split('=', 1) + else: + option_prefix = option_string + explicit_arg = None + for option_string in self._option_string_actions: + if option_string.startswith(option_prefix): + action = self._option_string_actions[option_string] + tup = action, option_string, explicit_arg + result.append(tup) # single character options can be concatenated with their arguments # but multiple character options always have to have their argument |