1 # Copyright 2012-2013 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
11 # 2. Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following
13 # disclaimer in the documentation and/or other materials
14 # provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.command
35 from sys import argv, exit, stdout
36 from os.path import basename
37 from inspect import getargspec
39 from kamaki.cli.argument import _arguments, parse_known_args, init_parser,\
41 from kamaki.cli.history import History
42 from kamaki.cli.utils import print_dict, print_list, red, magenta, yellow
43 from kamaki.cli.errors import CLIError
51 def _construct_command_syntax(cls):
52 spec = getargspec(cls.main.im_func)
54 n = len(args) - len(spec.defaults or ())
55 required = ' '.join('<%s>' % x\
56 .replace('____', '[:')\
59 replace('_', ' ') for x in args[:n])
60 optional = ' '.join('[%s]' % x\
61 .replace('____', '[:')\
64 replace('_', ' ') for x in args[n:])
65 cls.syntax = ' '.join(x for x in [required, optional] if x)
67 cls.syntax += ' <%s ...>' % spec.varargs
70 def _get_cmd_tree_from_spec(spec, cmd_tree_list):
71 for tree in cmd_tree_list:
80 def _num_of_matching_terms(basic_list, attack_list):
82 return len(basic_list)
85 for i, term in enumerate(basic_list):
87 if term != attack_list[i]:
95 def _update_best_match(name_terms, prefix=[]):
97 pref_list = prefix if isinstance(prefix, list) else prefix.split('_')
101 num_of_matching_terms = _num_of_matching_terms(name_terms, pref_list)
104 if num_of_matching_terms and len(_best_match) <= num_of_matching_terms:
105 if len(_best_match) < num_of_matching_terms:
106 _best_match = name_terms[:num_of_matching_terms]
111 def command(cmd_tree, prefix='', descedants_depth=1):
112 """Load a class as a command
113 spec_cmd0_cmd1 will be command spec cmd0
114 @cmd_tree is initialized in cmd_spec file and is the structure
115 where commands are loaded. Var name should be _commands
116 @param prefix if given, load only commands prefixed with prefix,
117 @param descedants_depth is the depth of the tree descedants of the
118 prefix command. It is used ONLY if prefix and if prefix is not
123 cls_name = cls.__name__
127 print('Warning: command %s found but not loaded' % cls_name)
130 name_terms = cls_name.split('_')
131 if not _update_best_match(name_terms, prefix):
135 max_len = len(_best_match) + descedants_depth
136 if len(name_terms) > max_len:
137 partial = '_'.join(name_terms[:max_len])
138 if not cmd_tree.has_command(partial): # add partial path
139 cmd_tree.add_command(partial)
142 cls.description, sep, cls.long_description\
143 = cls.__doc__.partition('\n')
144 _construct_command_syntax(cls)
146 cmd_tree.add_command(cls_name, cls.description, cls)
153 return [term for term in command.func_defaults[0]\
154 if not term.startswith('-')]
156 cmd_spec_locations = [
157 'kamaki.cli.commands',
164 def _setup_logging(silent=False, debug=False, verbose=False, include=False):
165 """handle logging for clients package"""
167 def add_handler(name, level, prefix=''):
168 h = logging.StreamHandler()
169 fmt = logging.Formatter(prefix + '%(message)s')
171 logger = logging.getLogger(name)
173 logger.setLevel(level)
176 add_handler('', logging.CRITICAL)
178 add_handler('requests', logging.INFO, prefix='* ')
179 add_handler('clients.send', logging.DEBUG, prefix='> ')
180 add_handler('clients.recv', logging.DEBUG, prefix='< ')
182 add_handler('requests', logging.INFO, prefix='* ')
183 add_handler('clients.send', logging.INFO, prefix='> ')
184 add_handler('clients.recv', logging.INFO, prefix='< ')
186 add_handler('clients.recv', logging.INFO)
188 add_handler('', logging.WARNING)
191 def _init_session(arguments):
193 _help = arguments['help'].value
195 _debug = arguments['debug'].value
197 _verbose = arguments['verbose'].value
199 _colors = arguments['config'].get('global', 'colors')
200 if not (stdout.isatty() and _colors == 'on'):
201 from kamaki.cli.utils import remove_colors
203 _silent = arguments['silent'].value
204 _include = arguments['include'].value
205 _setup_logging(_silent, _debug, _verbose, _include)
208 def get_command_group(unparsed, arguments):
209 groups = arguments['config'].get_groups()
210 for term in unparsed:
211 if term.startswith('-'):
214 unparsed.remove(term)
220 def _load_spec_module(spec, arguments, module):
221 spec_name = arguments['config'].get(spec, 'cli')
222 if spec_name is None:
225 for location in cmd_spec_locations:
226 location += spec_name if location == '' else '.%s' % spec_name
228 pkg = __import__(location, fromlist=[module])
235 def _groups_help(arguments):
238 for spec in arguments['config'].get_groups():
239 pkg = _load_spec_module(spec, arguments, '_commands')
244 cmd for cmd in getattr(pkg, '_commands')\
245 if arguments['config'].get(cmd.name, 'cli')
247 except AttributeError:
249 print('Warning: No description for %s' % spec)
252 descriptions[cmd.name] = cmd.description
255 print('Warning: no cmd specs in module %s' % spec)
257 print('Warning: Loading of %s cmd spec failed' % spec)
258 print('\nOptions:\n - - - -')
259 print_dict(descriptions)
262 def _print_subcommands_help(cmd):
264 for subcmd in cmd.get_subcommands():
265 spec, sep, print_path = subcmd.path.partition('_')
266 printout[print_path.replace('_', ' ')] = subcmd.description
268 print('\nOptions:\n - - - -')
272 def _update_parser_help(parser, cmd):
274 parser.prog = parser.prog.split('<')[0]
275 parser.prog += ' '.join(_best_match)
278 cls = cmd.get_class()
279 parser.prog += ' ' + cls.syntax
280 arguments = cls().arguments
281 update_arguments(parser, arguments)
283 parser.prog += ' <...>'
284 if cmd.has_description:
285 parser.description = cmd.help
288 def _print_error_message(cli_err):
289 errmsg = '%s' % cli_err
290 if cli_err.importance == 1:
291 errmsg = magenta(errmsg)
292 elif cli_err.importance == 2:
293 errmsg = yellow(errmsg)
294 elif cli_err.importance > 2:
297 print_list(cli_err.details)
300 def _get_best_match_from_cmd_tree(cmd_tree, unparsed):
301 matched = [term for term in unparsed if not term.startswith('-')]
304 return cmd_tree.get_command('_'.join(matched))
306 matched = matched[:-1]
310 def _exec_cmd(instance, cmd_args, help_method):
312 return instance.main(*cmd_args)
313 except TypeError as err:
314 if err.args and err.args[0].startswith('main()'):
315 print(magenta('Syntax error'))
326 def set_command_param(param, value):
327 if param == 'prefix':
329 elif param == 'descedants_depth':
334 def_params = list(command.func_defaults)
335 def_params[pos] = value
336 command.func_defaults = tuple(def_params)
339 def one_cmd(parser, unparsed, arguments):
340 group = get_command_group(list(unparsed), arguments)
343 _groups_help(arguments)
348 [term for term in unparsed if not term.startswith('-')]
353 spec_module = _load_spec_module(group, arguments, '_commands')
355 cmd_tree = _get_cmd_tree_from_spec(group, spec_module._commands)
358 cmd = cmd_tree.get_command('_'.join(_best_match))
360 cmd = _get_best_match_from_cmd_tree(cmd_tree, unparsed)
361 _best_match = cmd.path.split('_')
363 if _debug or _verbose:
364 print('Unexpected error: failed to load command')
367 _update_parser_help(parser, cmd)
369 if _help or not cmd.is_command:
371 _print_subcommands_help(cmd)
374 cls = cmd.get_class()
375 executable = cls(arguments)
376 parsed, unparsed = parse_known_args(parser, executable.arguments)
377 for term in _best_match:
378 unparsed.remove(term)
379 _exec_cmd(executable, unparsed, parser.print_help)
382 def run_shell(exe_string, arguments):
383 from command_shell import _init_shell
384 shell = _init_shell(exe_string, arguments)
385 # Load all commands in shell CommandTree
386 _config = arguments['config']
387 for spec in [spec for spec in _config.get_groups()\
388 if _config.get(spec, 'cli')]:
390 spec_module = _load_spec_module(spec, arguments, '_commands')
391 spec_commands = getattr(spec_module, '_commands')
392 except AttributeError:
394 print('Warning: No valid description for %s' % spec)
396 for spec_tree in spec_commands:
397 if spec_tree.name == spec:
398 shell.cmd_tree.add_tree(spec_tree)
405 exe = basename(argv[0])
406 parser = init_parser(exe, _arguments)
407 parsed, unparsed = parse_known_args(parser, _arguments)
409 if _arguments['version'].value:
412 _init_session(_arguments)
415 _history = History(_arguments['config'].get('history', 'file'))
416 _history.add(' '.join([exe] + argv[1:]))
417 one_cmd(parser, unparsed, _arguments)
420 _groups_help(_arguments)
422 run_shell(exe, _arguments)
423 except CLIError as err:
426 _print_error_message(err)
428 except Exception as err:
431 print('Unknown Error: %s' % err)