Commit de73876b authored by Stavros Sachtouris's avatar Stavros Sachtouris
Browse files

Attempt to pep8-fix some source files

parent 2e44e2ba
......@@ -57,16 +57,18 @@ def _construct_command_syntax(cls):
spec = getargspec(cls.main.im_func)
args = spec.args[1:]
n = len(args) - len(spec.defaults or ())
required = ' '.join('<%s>' % x\
.replace('____', '[:')\
.replace('___', ':')\
.replace('__', ']').\
replace('_', ' ') for x in args[:n])
optional = ' '.join('[%s]' % x\
.replace('____', '[:')\
.replace('___', ':')\
.replace('__', ']').\
replace('_', ' ') for x in args[n:])
required = ' '.join(
'<%s>' % x.replace(
'____', '[:').replace(
'___', ':').replace(
'__', ']').replace(
'_', ' ') for x in args[:n])
optional = ' '.join(
'[%s]' % x.replace(
'____', '[:').replace(
'___', ':').replace(
'__', ']').replace(
'_', ' ') for x in args[n:])
cls.syntax = ' '.join(x for x in [required, optional] if x)
if spec.varargs:
cls.syntax += ' <%s ...>' % spec.varargs
......@@ -144,8 +146,9 @@ def command(cmd_tree, prefix='', descedants_depth=1):
kloger.warning('%s failed max_len test' % cls_name)
return None
cls.description, sep, cls.long_description\
= cls.__doc__.partition('\n')
(
cls.description, sep, cls.long_description
) = cls.__doc__.partition('\n')
_construct_command_syntax(cls)
cmd_tree.add_command(cls_name, cls.description, cls)
......@@ -240,8 +243,8 @@ def _groups_help(arguments):
cmds = None
try:
cmds = [
cmd for cmd in getattr(pkg, '_commands')\
if arguments['config'].get(cmd.name, 'cli')
cmd for cmd in getattr(pkg, '_commands')
if arguments['config'].get(cmd.name, 'cli')
]
except AttributeError:
if _debug:
......@@ -260,8 +263,8 @@ def _groups_help(arguments):
def _load_all_commands(cmd_tree, arguments):
_config = arguments['config']
for spec in [spec for spec in _config.get_groups()\
if _config.get(spec, 'cli')]:
for spec in [spec for spec in _config.get_groups()
if _config.get(spec, 'cli')]:
try:
spec_module = _load_spec_module(spec, arguments, '_commands')
spec_commands = getattr(spec_module, '_commands')
......@@ -304,8 +307,8 @@ def update_parser_help(parser, cmd):
else:
parser.syntax += ' <...>'
if cmd.has_description:
parser.parser.description = cmd.help\
+ (('\n%s' % description) if description else '')
parser.parser.description = cmd.help + (
('\n%s' % description) if description else '')
else:
parser.parser.description = description
......
......@@ -129,8 +129,12 @@ class Argument(object):
action = 'append' if self.arity < 0\
else 'store_true' if self.arity == 0\
else 'store'
parser.add_argument(*self.parsed_name, dest=name, action=action,
default=self.default, help=self.help)
parser.add_argument(
*self.parsed_name,
dest=name,
action=action,
default=self.default,
help=self.help)
def main(self):
"""Overide this method to give functionality to your args"""
......@@ -189,7 +193,8 @@ class CmdLineConfigArgument(Argument):
for option in options:
keypath, sep, val = option.partition('=')
if not sep:
raiseCLIError(CLISyntaxError('Argument Syntax Error '),
raiseCLIError(
CLISyntaxError('Argument Syntax Error '),
details=['%s is missing a "="',
' (usage: -o section.key=val)' % option]
)
......@@ -237,7 +242,8 @@ class IntArgument(ValueArgument):
try:
self._value = int(newvalue)
except ValueError:
raiseCLIError(CLISyntaxError('IntArgument Error',
raiseCLIError(
CLISyntaxError('IntArgument Error',
details=['Value %s not an int' % newvalue]))
......@@ -248,7 +254,8 @@ class DateArgument(ValueArgument):
:value returns: same date in first of DATE_FORMATS
"""
DATE_FORMATS = ["%a %b %d %H:%M:%S %Y",
DATE_FORMATS = [
"%a %b %d %H:%M:%S %Y",
"%A, %d-%b-%y %H:%M:%S GMT",
"%a, %d %b %Y %H:%M:%S GMT"]
......@@ -272,7 +279,8 @@ class DateArgument(ValueArgument):
continue
self._value = t.strftime(self.DATE_FORMATS[0])
return
raiseCLIError(None,
raiseCLIError(
None,
'Date Argument Error',
details='%s not a valid date. correct formats:\n\t%s'\
% (datestr, self.INPUT_FORMATS))
......@@ -321,7 +329,8 @@ class KeyValueArgument(Argument):
for pair in keyvalue_pairs:
key, sep, val = pair.partition('=')
if not sep:
raiseCLIError(CLISyntaxError('Argument syntax error '),
raiseCLIError(
CLISyntaxError('Argument syntax error '),
details='%s is missing a "=" (usage: key1=val1 )\n' % pair)
self._value[key.strip()] = val.strip()
......@@ -374,15 +383,18 @@ class ProgressBarArgument(FlagArgument):
mybar.finish()
_arguments = dict(config=_config_arg,
_arguments = dict(
config=_config_arg,
help=Argument(0, 'Show help message', ('-h', '--help')),
debug=FlagArgument('Include debug output', ('-d', '--debug')),
include=FlagArgument('Include raw connection data in the output',
include=FlagArgument(
'Include raw connection data in the output',
('-i', '--include')),
silent=FlagArgument('Do not output anything', ('-s', '--silent')),
verbose=FlagArgument('More info at response', ('-v', '--verbose')),
version=VersionArgument('Print current version', ('-V', '--version')),
options=CmdLineConfigArgument(_config_arg,
options=CmdLineConfigArgument(
_config_arg,
'Override a config value',
('-o', '--options'))
)
......@@ -416,7 +428,8 @@ class ArgumentParseManager(object):
:param arguments: (dict) if given, overrides the global _argument as
the parsers arguments specification
"""
self.parser = ArgumentParser(add_help=False,
self.parser = ArgumentParser(
add_help=False,
formatter_class=RawDescriptionHelpFormatter)
self.syntax = '%s <cmd_group> [<cmd_subbroup> ...] <cmd>' % exe
if arguments:
......
......@@ -79,8 +79,8 @@ class Shell(Cmd):
def precmd(self, line):
if line.startswith('/'):
cur_cmd_path = self.prompt.replace(' ',
'_')[len(self._prefix):-len(self._suffix)]
start, end = len(self._prefix), -len(self._suffix)
cur_cmd_path = self.prompt.replace(' ', '_')[start:end]
if cur_cmd_path != self.cmd_tree.name:
cur_cmd = self.cmd_tree.get_command(cur_cmd_path)
self._context_stack.append(self._backup())
......@@ -94,8 +94,13 @@ class Shell(Cmd):
return line
def greet(self, version):
print('kamaki v%s - Interactive Shell\n\t(exit or ^D to exit)\n'\
% version)
print('kamaki v%s - Interactive Shell\n' % version)
print('\t\exit \tterminate kamaki')
print('\texit or ^D\texit context')
print('\t? or help \tavailable commands')
print('\t?command \thelp on command')
print('\t!<command>\texecute OS shell command')
print('')
def set_prompt(self, new_prompt):
self.prompt = '%s%s%s' % (self._prefix, new_prompt, self._suffix)
......@@ -111,8 +116,8 @@ class Shell(Cmd):
def do_exit(self, line):
print('')
if self.prompt[len(self._prefix):-len(self._suffix)]\
== self.cmd_tree.name:
start, end = len(self._prefix), -len(self._suffix)
if self.prompt[start:end] == self.cmd_tree.name:
exit(0)
return True
......@@ -198,7 +203,9 @@ class Shell(Cmd):
cmd_parser.parse(cmd_args)
for name, arg in instance.arguments.items():
arg.value = getattr(cmd_parser.parsed, name,
arg.value = getattr(
cmd_parser.parsed,
name,
arg.default)
exec_cmd(
......@@ -209,8 +216,8 @@ class Shell(Cmd):
# if not term.startswith('-')],
except (ClientError, CLIError) as err:
print_error_message(err)
elif ('-h' in cmd_args or '--help' in cmd_args) \
or len(cmd_args): # print options
elif ('-h' in cmd_args or '--help' in cmd_args) or len(cmd_args):
# print options
print('%s' % cmd.help)
print_subcommands_help(cmd)
else: # change context
......@@ -259,8 +266,10 @@ class Shell(Cmd):
instance = cls(dict(arguments))
empty, sep, subname = subcmd.path.partition(cmd.path)
cmd_name = '%s %s' % (cmd.name, subname.replace('_', ' '))
print('\n%s\nSyntax:\t%s %s'\
% (cls.description, cmd_name, cls.syntax))
print('\n%s\nSyntax:\t%s %s' % (
cls.description,
cmd_name,
cls.syntax))
cmd_args = {}
for arg in instance.arguments.values():
cmd_args[','.join(arg.parsed_name)] = arg.help
......
......@@ -115,8 +115,11 @@ class Command(object):
return cmd, args[index:]
def pretty_print(self, recursive=False):
print('Path: %s (Name: %s) is_cmd: %s\n\thelp: %s'\
% (self.path, self.name, self.is_command, self.help))
print('Path: %s (Name: %s) is_cmd: %s\n\thelp: %s' % (
self.path,
self.name,
self.is_command,
self.help))
for cmd in self.get_subcommands():
cmd.pretty_print(recursive)
......@@ -204,12 +207,14 @@ class CommandTree(object):
return self._all_commands[path].get_class()
def get_subnames(self, path=None):
return self.get_group_names() if path in (None, '') \
else self._all_commands[path].get_subnames()
if path in (None, ''):
return self.get_group_names()
return self._all_commands[path].get_subnames()
def get_subcommands(self, path=None):
return self.get_groups() if path in (None, '') \
else self._all_commands[path].get_subcommands()
if path in (None, ''):
return self.get_groups()
return self._all_commands[path].get_subcommands()
def get_parent(self, path):
if '_' not in path:
......
......@@ -44,14 +44,10 @@ from base64 import b64encode
from os.path import exists
server_cmds = CommandTree('server',
'Compute/Cyclades API server commands')
flavor_cmds = CommandTree('flavor',
'Compute/Cyclades API flavor commands')
image_cmds = CommandTree('image',
'Compute/Cyclades or Glance API image commands')
network_cmds = CommandTree('network',
'Compute/Cyclades API network commands')
server_cmds = CommandTree('server', 'Compute/Cyclades API server commands')
flavor_cmds = CommandTree('flavor', 'Compute/Cyclades API flavor commands')
image_cmds = CommandTree('image', 'Cyclades/Plankton API image commands')
network_cmds = CommandTree('network', 'Compute/Cyclades API network commands')
_commands = [server_cmds, flavor_cmds, image_cmds, network_cmds]
......@@ -186,12 +182,12 @@ class PersonalityArgument(KeyValueArgument):
for i, terms in enumerate(newvalue):
termlist = terms.split(',')
if len(termlist) > 5:
raiseCLIError(
CLISyntaxError('Wrong number of terms (should be 1 to 5)'),
details=howto_personality)
msg = 'Wrong number of terms (should be 1 to 5)'
raiseCLIError(CLISyntaxError(msg), details=howto_personality)
path = termlist[0]
if not exists(path):
raiseCLIError(None,
raiseCLIError(
None,
'--personality: File %s does not exist' % path,
importance=1,
details=howto_personality)
......@@ -497,8 +493,8 @@ class flavor_list(_init_cyclades):
detail=FlagArgument('show detailed output', '-l'),
limit=IntArgument('limit the number of flavors to list', '-n'),
more=FlagArgument(
'output results in pages (-n to set items per page, default 10)',
'--more')
'output results in pages (-n to set items per page, default 10)',
'--more')
)
@errors.generic.all
......@@ -580,8 +576,7 @@ class network_list(_init_cyclades):
if self['detail']:
self._make_results_pretty(networks)
if self['more']:
print_items(networks,
page_size=self['limit'] if self['limit'] else 10)
print_items(networks, page_size=self['limit'] or 10)
elif self['limit']:
print_items(networks[:self['limit']])
else:
......@@ -607,7 +602,8 @@ class network_create(_init_cyclades):
@errors.cyclades.connection
@errors.cyclades.network_max
def _run(self, name):
r = self.client.create_network(name,
r = self.client.create_network(
name,
cidr=self['cidr'],
gateway=self['gateway'],
dhcp=self['dhcp'],
......
......@@ -82,9 +82,8 @@ class generic(object):
if not client:
raise
url = getattr(client, 'base_url', '<empty>')
raiseCLIError(ce,
'Invalid service url %s' % url,
details=[
msg = 'Invalid service url %s' % url
raiseCLIError(ce, msg, details=[
'Please, check if service url is correctly set',
'* to get current url: /config get compute.url',
'* to set url: /config set compute.url <URL>'])
......@@ -112,9 +111,9 @@ class astakos(object):
kloger.warning(
'No permanent token (try: kamaki config set token <tkn>)')
if not getattr(client, 'base_url', False):
raise CLIError('Missing astakos server URL',
importance=3,
details=['Check if astakos.url is set correctly',
msg = 'Missing astakos server URL'
raise CLIError(msg, importance=3, details=[
'Check if astakos.url is set correctly',
'To get astakos url: /config get astakos.url',
'To set astakos url: /config set astakos.url <URL>'])
return r
......@@ -128,10 +127,11 @@ class astakos(object):
except ClientError as ce:
if ce.status == 401:
token = kwargs.get('custom_token', 0) or self.client.token
raiseCLIError(ce,
'Authorization failed for token %s' % token if token\
else 'No token provided',
details=[] if token else this._token_details)
msg = (
'Authorization failed for token %s' % token
) if token else 'No token provided',
details = [] if token else this._token_details
raiseCLIError(ce, msg, details=details)
self._raise = foo
return r
return _raise
......@@ -151,7 +151,8 @@ class history(object):
def _get_cmd_ids(this, foo):
def _raise(self, cmd_ids, *args, **kwargs):
if not cmd_ids:
raise CLISyntaxError('Usage: <id1|id1-id2> [id3|id3-id4] ...',
raise CLISyntaxError(
'Usage: <id1|id1-id2> [id3|id3-id4] ...',
details=self.__doc__.split('\n'))
return foo(self, cmd_ids, *args, **kwargs)
return _raise
......@@ -193,15 +194,15 @@ class cyclades(object):
network_id = int(network_id)
return foo(self, *args, **kwargs)
except ValueError as ve:
raiseCLIError(ve, 'Invalid network id %s ' % network_id,
details='network id must be a positive integer',
importance=1)
msg = 'Invalid network id %s ' % network_id
details = ['network id must be a positive integer']
raiseCLIError(ve, msg, details=details, importance=1)
except ClientError as ce:
if network_id and ce.status == 404 and\
'network' in ('%s' % ce).lower():
raiseCLIError(ce,
'No network with id %s found' % network_id,
details=this.about_network_id)
if network_id and ce.status == 404 and (
'network' in ('%s' % ce).lower()
):
msg = 'No network with id %s found' % network_id,
raiseCLIError(ce, msg, details=this.about_network_id)
raise
return _raise
......@@ -212,11 +213,11 @@ class cyclades(object):
return foo(self, *args, **kwargs)
except ClientError as ce:
if ce.status == 413:
raiseCLIError(ce,
'Cannot create another network',
details=['Maximum number of networks reached',
'* to get a list of networks: /network list',
'* to delete a network: /network delete <net id>'])
msg = 'Cannot create another network',
details = ['Maximum number of networks reached',
'* to get a list of networks: /network list',
'* to delete a network: /network delete <net id>']
raiseCLIError(ce, msg, details=details)
raise
return _raise
......@@ -228,17 +229,15 @@ class cyclades(object):
return foo(self, *args, **kwargs)
except ClientError as ce:
if network_id and ce.status == 400:
raiseCLIError(ce,
'Network with id %s does not exist' % network_id,
details=self.about_network_id)
msg = 'Network with id %s does not exist' % network_id,
raiseCLIError(ce, msg, details=self.about_network_id)
elif network_id or ce.status == 421:
raiseCLIError(ce,
'Network with id %s is in use' % network_id,
details=[
'Disconnect all nics/VMs of this network first',
'* to get nics: /network info %s' % network_id,
'. (under "attachments" section)',
'* to disconnect: /network disconnect <nic id>'])
msg = 'Network with id %s is in use' % network_id,
raiseCLIError(ce, msg, details=[
'Disconnect all nics/VMs of this network first',
'* to get nics: /network info %s' % network_id,
'. (under "attachments" section)',
'* to disconnect: /network disconnect <nic id>'])
raise
return _raise
......@@ -250,15 +249,15 @@ class cyclades(object):
flavor_id = int(flavor_id)
return foo(self, *args, **kwargs)
except ValueError as ve:
raiseCLIError(ve, 'Invalid flavor id %s ' % flavor_id,
details='Flavor id must be a positive integer',
importance=1)
msg = 'Invalid flavor id %s ' % flavor_id,
details = 'Flavor id must be a positive integer',
raiseCLIError(ve, msg, details=details, importance=1)
except ClientError as ce:
if flavor_id and ce.status == 404 and\
'flavor' in ('%s' % ce).lower():
raiseCLIError(ce,
'No flavor with id %s found' % flavor_id,
details=this.about_flavor_id)
if flavor_id and ce.status == 404 and (
'flavor' in ('%s' % ce).lower()
):
msg = 'No flavor with id %s found' % flavor_id,
raiseCLIError(ce, msg, details=this.about_flavor_id)
raise
return _raise
......@@ -270,19 +269,20 @@ class cyclades(object):
server_id = int(server_id)
return foo(self, *args, **kwargs)
except ValueError as ve:
raiseCLIError(ve,
'Invalid server(VM) id %s' % server_id,
details=['id must be a positive integer'],
importance=1)
msg = 'Invalid server(VM) id %s' % server_id,
details = ['id must be a positive integer'],
raiseCLIError(ve, msg, details=details, importance=1)
except ClientError as ce:
err_msg = ('%s' % ce).lower()
if (ce.status == 404 and 'server' in err_msg)\
or (ce.status == 400 and 'not found' in err_msg):
raiseCLIError(ce,
'server(VM) with id %s not found' % server_id,
details=[
'* to get existing VM ids: /server list',
'* to get VM details: /server info <VM id>'])
if (
ce.status == 404 and 'server' in err_msg
) or (
ce.status == 400 and 'not found' in err_msg
):
msg = 'server(VM) with id %s not found' % server_id,
raiseCLIError(ce, msg, details=[
'* to get existing VM ids: /server list',
'* to get VM details: /server info <VM id>'])
raise
return _raise
......@@ -293,14 +293,15 @@ class cyclades(object):
try:
return foo(self, *args, **kwargs)
except ClientError as ce:
if ce.status == 400 and profile\
and 'firewall' in ('%s' % ce).lower():
raiseCLIError(ce,
'%s is an invalid firewall profile term' % profile,
details=['Try one of the following:',
'* DISABLED: Shutdown firewall',
'* ENABLED: Firewall in normal mode',
'* PROTECTED: Firewall in secure mode'])
if ce.status == 400 and profile and (
'firewall' in ('%s' % ce).lower()
):
msg = '%s is an invalid firewall profile term' % profile
raiseCLIError(ce, msg, details=[
'Try one of the following:',
'* DISABLED: Shutdown firewall',
'* ENABLED: Firewall in normal mode',
'* PROTECTED: Firewall in secure mode'])
raise
return _raise
......@@ -311,8 +312,9 @@ class cyclades(object):
return foo(self, *args, **kwargs)
except ClientError as ce:
nic_id = kwargs.get('nic_id', None)
if nic_id and ce.status == 404\
and 'network interface' in ('%s' % ce).lower():
if nic_id and ce.status == 404 and (
'network interface' in ('%s' % ce).lower()
):
server_id = kwargs.get('server_id', '<no server>')
err_msg = 'No nic %s on server(VM) with id %s' % (
nic_id,
......@@ -333,13 +335,11 @@ class cyclades(object):
return foo(self, *args, **kwargs)
except IndexError as ie:
nic_id = kwargs.get('nic_id', None)
raiseCLIError(ie,
'Invalid format for network interface (nic) %s' % nic_id,
importance=1,
details=[
'nid_id format: nic-<server id>-<nic id>',
'* get nics of a network: /network info <net id>',
' (listed the "attachments" section)'])
msg = 'Invalid format for network interface (nic) %s' % nic_id
raiseCLIError(ie, msg, importance=1, details=[
'nid_id format: nic-<server id>-<nic id>',
'* get nics of a network: /network info <net id>',
' (listed the "attachments" section)'])
return _raise
@classmethod
......@@ -349,8 +349,9 @@ class cyclades(object):
try:
foo(self, *args, **kwargs)
except ClientError as ce:
if key and ce.status == 404\
and 'metadata' in ('%s' % ce).lower():
if key and ce.status == 404 and (
'metadata' in ('%s' % ce).lower()
):
raiseCLIError(ce, 'No VM metadata with key %s' % key)
raise
return _raise
......@@ -358,7 +359,8 @@ class cyclades(object):
class plankton(object):
about_image_id = ['How to pick a suitable image:',
about_image_id = [
'How to pick a suitable image:',
'* get a list of image ids: /image list',
'* details of image: /flavor info <image id>']
......@@ -373,13 +375,15 @@ class plankton(object):
try:
foo(self, *args, **kwargs)
except ClientError as ce:
if image_id and (ce.status == 404\
or (ce.status == 400 and
'image not found' in ('%s' % ce).lower())\
or ce.status == 411):
raiseCLIError(ce,
'No image with id %s found' % image_id,
details=this.about_image_id)
if image_id and (
ce.status == 404
or (
ce.status == 400
and 'image not found' in ('%s' % ce).lower())
or ce.status == 411
):
msg = 'No image with id %s found' % image_id
raiseCLIError(ce, msg, details=this.about_image_id)
raise
return _raise