Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run ruff check on awscli directory #9158

Draft
wants to merge 6 commits into
base: v2
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 12 additions & 14 deletions awscli/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class InvalidAliasException(Exception):
pass


class AliasLoader(object):
class AliasLoader:
def __init__(self,
alias_filename=os.path.expanduser(
os.path.join('~', '.aws', 'cli', 'alias'))):
Expand Down Expand Up @@ -94,7 +94,7 @@ def get_aliases(self, command=None):
return self._aliases.get(key, {})


class BaseAliasCommandInjector(object):
class BaseAliasCommandInjector:
def __init__(self, alias_loader):
self._alias_loader = alias_loader

Expand All @@ -119,7 +119,7 @@ def __init__(self, session, alias_loader):
:type alias_loader: awscli.alias.AliasLoader
:param alias_loader: The alias loader to use
"""
super(AliasCommandInjector, self).__init__(alias_loader)
super().__init__(alias_loader)
self._session = session

def inject_aliases(self, command_table, parser):
Expand All @@ -145,7 +145,7 @@ def inject_aliases(self, command_table, parser):

class AliasSubCommandInjector(BaseAliasCommandInjector):
def __init__(self, alias_loader):
super(AliasSubCommandInjector, self).__init__(alias_loader)
super().__init__(alias_loader)
self._global_cmd_driver = None
self._global_args_parser = None

Expand Down Expand Up @@ -239,17 +239,16 @@ class BaseInternalAliasCommand(BaseAliasCommand):
]

def __init__(self, alias_name, alias_value, session):
super(BaseInternalAliasCommand, self).__init__(alias_name, alias_value)
super().__init__(alias_name, alias_value)
self._session = session

def _get_alias_args(self):
try:
alias_args = shlex.split(self._alias_value)
except ValueError as e:
raise InvalidAliasException(
'Value of alias "%s" could not be parsed. '
'Received error: %s when parsing:\n%s' % (
self._alias_name, e, self._alias_value)
f'Value of alias "{self._alias_name}" could not be parsed. '
f'Received error: {e} when parsing:\n{self._alias_value}'
)

alias_args = [arg.strip(os.linesep) for arg in alias_args]
Expand Down Expand Up @@ -287,9 +286,8 @@ def _get_global_parameters_to_update(self, arg_parser, parsed_alias_args):
if arg_parser.get_default(parsed_param) != value:
if parsed_param in self.UNSUPPORTED_GLOBAL_PARAMETERS:
raise InvalidAliasException(
'Global parameter "--%s" detected in alias "%s" '
'which is not support in subcommand aliases.' % (
parsed_param, self._alias_name))
f'Global parameter "--{parsed_param}" detected in alias "{self._alias_name}" '
'which is not support in subcommand aliases.')
else:
global_params_to_update.append(parsed_param)
return global_params_to_update
Expand Down Expand Up @@ -328,7 +326,7 @@ def __init__(self, alias_name, alias_value, session, command_table,
to this command as opposed to proxy to itself in the command
table
"""
super(ServiceAliasCommand, self).__init__(
super().__init__(
alias_name, alias_value, session)
self._command_table = command_table
self._parser = parser
Expand Down Expand Up @@ -382,7 +380,7 @@ def __init__(self, alias_name, alias_value, invoker=subprocess.call):
:param invoker: Callable to run arguments of external alias. The
signature should match that of ``subprocess.call``
"""
super(ExternalAliasCommand, self).__init__(alias_name, alias_value)
super().__init__(alias_name, alias_value)
self._invoker = invoker

def __call__(self, args, parsed_globals):
Expand All @@ -402,7 +400,7 @@ class InternalAliasSubCommand(BaseInternalAliasCommand):
def __init__(self, alias_name, alias_value, command_object,
global_args_parser, session,
proxied_sub_command=None):
super(InternalAliasSubCommand, self).__init__(
super().__init__(
alias_name, alias_value, session)
self._command_object = command_object
self._global_args_parser = global_args_parser
Expand Down
25 changes: 12 additions & 13 deletions awscli/argparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
)
USAGE = (
"aws [options] <command> <subcommand> [<subcommand> ...] [parameters]\n"
"%s" % HELP_BLURB
f"{HELP_BLURB}"
)


Expand All @@ -42,7 +42,7 @@ class CommandAction(argparse.Action):
"""
def __init__(self, option_strings, dest, command_table, **kwargs):
self.command_table = command_table
super(CommandAction, self).__init__(
super().__init__(
option_strings, dest, choices=self.choices, **kwargs
)

Expand Down Expand Up @@ -81,18 +81,18 @@ def _check_value(self, action, value):
for i in range(len(action.choices))[::self.ChoicesPerLine]:
current = []
for choice in action.choices[i:i+self.ChoicesPerLine]:
current.append('%-40s' % choice)
current.append(f'{choice:<40s}')
msg.append(' | '.join(current))
possible = get_close_matches(value, action.choices, cutoff=0.8)
if possible:
extra = ['\n\nInvalid choice: %r, maybe you meant:\n' % value]
extra = [f'\n\nInvalid choice: {value!r}, maybe you meant:\n']
for word in possible:
extra.append(' * %s' % word)
extra.append(f' * {word}')
msg.extend(extra)
raise argparse.ArgumentError(action, '\n'.join(msg))

def parse_known_args(self, args, namespace=None):
parsed, remaining = super(CLIArgParser, self).parse_known_args(args, namespace)
parsed, remaining = super().parse_known_args(args, namespace)
terminal_encoding = getattr(sys.stdin, 'encoding', 'utf-8')
if terminal_encoding is None:
# In some cases, sys.stdin won't have an encoding set,
Expand Down Expand Up @@ -133,7 +133,7 @@ class MainArgParser(CLIArgParser):

def __init__(self, command_table, version_string,
description, argument_table, prog=None):
super(MainArgParser, self).__init__(
super().__init__(
formatter_class=self.Formatter,
add_help=False,
conflict_handler='resolve',
Expand All @@ -145,7 +145,7 @@ def __init__(self, command_table, version_string,
def _create_choice_help(self, choices):
help_str = ''
for choice in sorted(choices):
help_str += '* %s\n' % choice
help_str += f'* {choice}\n'
return help_str

def _build(self, command_table, version_string, argument_table):
Expand All @@ -162,7 +162,7 @@ def _build(self, command_table, version_string, argument_table):
class ServiceArgParser(CLIArgParser):

def __init__(self, operations_table, service_name):
super(ServiceArgParser, self).__init__(
super().__init__(
formatter_class=argparse.RawTextHelpFormatter,
add_help=False,
conflict_handler='resolve',
Expand All @@ -182,7 +182,7 @@ def __init__(self, argument_table, command_table=None):
# command_table is an optional subcommand_table. If it's passed
# in, then we'll update the argparse to parse a 'subcommand' argument
# and populate the choices field with the command table keys.
super(ArgTableArgParser, self).__init__(
super().__init__(
formatter_class=self.Formatter,
add_help=False,
usage=USAGE,
Expand All @@ -205,7 +205,7 @@ def parse_known_args(self, args, namespace=None):
namespace.help = 'help'
return namespace, []
else:
return super(ArgTableArgParser, self).parse_known_args(
return super().parse_known_args(
args, namespace)


Expand All @@ -219,8 +219,7 @@ class SubCommandArgParser(ArgTableArgParser):
"""

def parse_known_args(self, args, namespace=None):
parsed_args, remaining = super(
SubCommandArgParser, self).parse_known_args(args, namespace)
parsed_args, remaining = super().parse_known_args(args, namespace)
if getattr(parsed_args, 'subcommand', None) is not None:
new_args = self._remove_subcommand(args, parsed_args)
return new_args, parsed_args.subcommand
Expand Down
49 changes: 22 additions & 27 deletions awscli/argprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ def __init__(self, cli_name, message):
:param message: The error message to display to the user.

"""
full_message = ("Error parsing parameter '%s': %s" %
(cli_name, message))
super(ParamError, self).__init__(full_message)
full_message = (f"Error parsing parameter '{cli_name}': {message}")
super().__init__(full_message)
self.cli_name = cli_name
self.message = message

Expand All @@ -55,9 +54,9 @@ class ParamUnknownKeyError(Exception):
def __init__(self, key, valid_keys):
valid_keys = ', '.join(valid_keys)
full_message = (
"Unknown key '%s', valid choices "
"are: %s" % (key, valid_keys))
super(ParamUnknownKeyError, self).__init__(full_message)
f"Unknown key '{key}', valid choices "
f"are: {valid_keys}")
super().__init__(full_message)


class TooComplexError(Exception):
Expand All @@ -76,9 +75,7 @@ def unpack_argument(session, service_name, operation_name, cli_argument, value):
param_name = getattr(cli_argument, 'name', 'anonymous')

value_override = session.emit_first_non_none_response(
'load-cli-arg.%s.%s.%s' % (service_name,
operation_name,
param_name),
f'load-cli-arg.{service_name}.{operation_name}.{param_name}',
param=cli_argument, value=value, service_name=service_name,
operation_name=operation_name)

Expand Down Expand Up @@ -113,14 +110,14 @@ def _detect_shape_structure(param, stack):
elif len(sub_types) > 1 and all(p == 'scalar' for p in sub_types):
return 'structure(scalars)'
else:
return 'structure(%s)' % ', '.join(sorted(set(sub_types)))
return 'structure({})'.format(', '.join(sorted(set(sub_types))))
elif param.type_name == 'list':
return 'list-%s' % _detect_shape_structure(param.member, stack)
return f'list-{_detect_shape_structure(param.member, stack)}'
elif param.type_name == 'map':
if param.value.type_name in SCALAR_TYPES:
return 'map-scalar'
else:
return 'map-%s' % _detect_shape_structure(param.value, stack)
return f'map-{_detect_shape_structure(param.value, stack)}'
finally:
stack.pop()

Expand Down Expand Up @@ -173,16 +170,15 @@ def _unpack_json_cli_arg(argument_model, value, cli_name):
return json.loads(value, object_pairs_hook=OrderedDict)
except ValueError as e:
raise ParamError(
cli_name, "Invalid JSON: %s\nJSON received: %s"
% (e, value))
cli_name, f"Invalid JSON: {e}\nJSON received: {value}")


def _unpack_complex_cli_arg(argument_model, value, cli_name):
type_name = argument_model.type_name
if type_name == 'structure' or type_name == 'map':
if value.lstrip()[0] == '{':
return _unpack_json_cli_arg(argument_model, value, cli_name)
raise ParamError(cli_name, "Invalid JSON:\n%s" % value)
raise ParamError(cli_name, f"Invalid JSON:\n{value}")
elif type_name == 'list':
if isinstance(value, str):
if value.lstrip()[0] == '[':
Expand All @@ -200,7 +196,7 @@ def _unpack_complex_cli_arg(argument_model, value, cli_name):
member_shape_model = argument_model.member
return [_unpack_cli_arg(member_shape_model, v, cli_name)
for v in value]
except (ValueError, TypeError) as e:
except (ValueError, TypeError):
# The list params don't have a name/cli_name attached to them
# so they will have bad error messages. We're going to
# attach the parent parameter to this error message to provide
Expand Down Expand Up @@ -256,7 +252,7 @@ def _is_complex_shape(model):
return True


class ParamShorthand(object):
class ParamShorthand:

def _uses_old_list_case(self, command_name, operation_name, argument_name):
"""
Expand Down Expand Up @@ -466,9 +462,8 @@ def _handle_special_cases(self, cli_argument, command_name, operation_name):
# Handle special case where the min/max is exactly one.
metadata = model.metadata
if metadata.get('min') == 1 and metadata.get('max') == 1:
return '%s %s1' % (cli_argument.cli_name, member_name)
return '%s %s1 %s2 %s3' % (cli_argument.cli_name, member_name,
member_name, member_name)
return f'{cli_argument.cli_name} {member_name}1'
return f'{cli_argument.cli_name} {member_name}1 {member_name}2 {member_name}3'
elif model.type_name == 'structure' and \
len(model.members) == 1 and \
'Value' in model.members and \
Expand Down Expand Up @@ -496,20 +491,20 @@ def _list_docs(self, argument_model, stack):
finally:
stack.pop()
if list_member.type_name in COMPLEX_TYPES or len(stack) > 1:
return '[%s,%s]' % (element_docs, element_docs)
return f'[{element_docs},{element_docs}]'
else:
return '%s,%s' % (element_docs, element_docs)
return f'{element_docs},{element_docs}'

def _map_docs(self, argument_model, stack):
k = argument_model.key
value_docs = self._shorthand_docs(argument_model.value, stack)
start = 'KeyName1=%s,KeyName2=%s' % (value_docs, value_docs)
start = f'KeyName1={value_docs},KeyName2={value_docs}'
if k.enum and not stack:
start += '\n\nWhere valid key names are:\n'
for enum in k.enum:
start += ' %s\n' % enum
start += f' {enum}\n'
elif stack:
start = '{%s}' % start
start = f'{{{start}}}'
return start

def _structure_docs(self, argument_model, stack):
Expand All @@ -521,7 +516,7 @@ def _structure_docs(self, argument_model, stack):
inner_part = ','.join(parts)
if not stack:
return inner_part
return '{%s}' % inner_part
return f'{{{inner_part}}}'

def _member_docs(self, name, shape, stack):
if stack.count(shape.name) > 0:
Expand All @@ -531,4 +526,4 @@ def _member_docs(self, name, shape, stack):
value_doc = self._shorthand_docs(shape, stack)
finally:
stack.pop()
return '%s=%s' % (name, value_doc)
return f'{name}={value_doc}'
9 changes: 4 additions & 5 deletions awscli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def create_argument_model_from_schema(schema):
return arg_shape


class BaseCLIArgument(object):
class BaseCLIArgument:
"""Interface for CLI argument.

This class represents the interface used for representing CLI
Expand Down Expand Up @@ -458,8 +458,7 @@ def add_to_params(self, parameters, value):
def _unpack_argument(self, value):
service_name = self._operation_model.service_model.service_name
operation_name = xform_name(self._operation_model.name, '-')
override = self._emit_first_response('process-cli-arg.%s.%s' % (
service_name, operation_name), param=self.argument_model,
override = self._emit_first_response(f'process-cli-arg.{service_name}.{operation_name}', param=self.argument_model,
cli_argument=self, value=value)
if override is not None:
# A plugin supplied an alternate conversion,
Expand Down Expand Up @@ -513,7 +512,7 @@ def __init__(self, name, argument_model, operation_model,
is_required=False, action='store_true', dest=None,
group_name=None, default=None,
serialized_name=None):
super(BooleanArgument, self).__init__(name,
super().__init__(name,
argument_model,
operation_model,
event_emitter,
Expand Down Expand Up @@ -547,7 +546,7 @@ def add_to_arg_table(self, argument_table):
# ourselves for the negative service. We then insert both into the
# arg table.
argument_table[self.name] = self
negative_name = 'no-%s' % self.name
negative_name = f'no-{self.name}'
negative_version = self.__class__(
negative_name, self.argument_model,
self._operation_model, self._event_emitter,
Expand Down
Loading
Loading