Update copyright dates for changes files
[kamaki] / kamaki / cli / command_shell.py
index 7ebbbfd..b9391bc 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright 2012 GRNET S.A. All rights reserved.
+# Copyright 2012-2014 GRNET S.A. All rights reserved.
 #
 # Redistribution and use in source and binary forms, with or
 # without modification, are permitted provided that the following
@@ -37,7 +37,7 @@ from sys import stdout
 
 from kamaki.cli import exec_cmd, print_error_message, print_subcommands_help
 from kamaki.cli.argument import ArgumentParseManager
-from kamaki.cli.utils import print_dict, split_input
+from kamaki.cli.utils import print_dict, split_input, pref_enc
 from kamaki.cli.history import History
 from kamaki.cli.errors import CLIError
 from kamaki.clients import ClientError
@@ -46,12 +46,12 @@ from kamaki.cli.logger import add_file_logger
 log = add_file_logger(__name__)
 
 
-def _init_shell(exe_string, parser):
+def _init_shell(exe_string, parser, username='', userid=''):
     parser.arguments.pop('version', None)
     shell = Shell()
     shell.set_prompt(exe_string)
     from kamaki import __version__ as version
-    shell.greet(version)
+    shell.greet(version, username, userid)
     shell.do_EOF = shell.do_exit
     from kamaki.cli.command_tree import CommandTree
     shell.cmd_tree = CommandTree(
@@ -73,6 +73,9 @@ class Shell(Cmd):
 
     undoc_header = 'interactive shell commands:'
 
+    def emptyline(self):
+        self.lastcmd = ''
+
     def postcmd(self, post, line):
         if self._context_stack:
             self._roll_command()
@@ -98,7 +101,7 @@ class Shell(Cmd):
             return line[1:]
         return line
 
-    def greet(self, version):
+    def greet(self, version, username='', userid=''):
         print('kamaki v%s - Interactive Shell\n' % version)
         print('\t/exit     \tterminate kamaki')
         print('\texit or ^D\texit context')
@@ -106,6 +109,8 @@ class Shell(Cmd):
         print('\t?command  \thelp on command')
         print('\t!<command>\texecute OS shell command')
         print('')
+        if username or userid:
+            print('Session user is %s (uuid: %s)' % (username, userid))
 
     def set_prompt(self, new_prompt):
         self.prompt = '%s%s%s' % (self._prefix, new_prompt, self._suffix)
@@ -148,7 +153,7 @@ class Shell(Cmd):
             pass
 
     def _roll_command(self, cmd_path=None):
-        for subname in self.cmd_tree.get_subnames(cmd_path):
+        for subname in self.cmd_tree.subnames(cmd_path):
             self._unregister_method('do_%s' % subname)
             self._unregister_method('complete_%s' % subname)
             self._unregister_method('help_%s' % subname)
@@ -162,19 +167,18 @@ class Shell(Cmd):
         self.__dict__ = oldcontext
 
     @staticmethod
-    def _create_help_method(cmd_name, args, descr, syntax):
+    def _create_help_method(cmd_name, args, required, descr, syntax):
         tmp_args = dict(args)
-        tmp_args.pop('options', None)
+        #tmp_args.pop('options', None)
         tmp_args.pop('cloud', None)
         tmp_args.pop('debug', None)
         tmp_args.pop('verbose', None)
-        tmp_args.pop('include', None)
         tmp_args.pop('silent', None)
         tmp_args.pop('config', None)
-        help_parser = ArgumentParseManager(cmd_name, tmp_args)
-        help_parser.parser.description = descr
-        help_parser.syntax = syntax
-        return help_parser.parser.print_help
+        help_parser = ArgumentParseManager(
+            cmd_name, tmp_args, required,
+            syntax=syntax, description=descr, check_required=False)
+        return help_parser.print_help
 
     def _register_command(self, cmd_path):
         cmd = self.cmd_tree.get_command(cmd_path)
@@ -186,6 +190,7 @@ class Shell(Cmd):
                 <cmd> <term> <term> <args> is always parsed to most specific
                 even if cmd_term_term is not a terminal path
             """
+            line = line.decode(pref_enc)
             subcmd, cmd_args = cmd.parse_out(split_input(line))
             self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
             cmd_parser = ArgumentParseManager(
@@ -195,7 +200,8 @@ class Shell(Cmd):
             # exec command or change context
             if subcmd.is_command:  # exec command
                 try:
-                    cls = subcmd.get_class()
+                    cls = subcmd.cmd_class
+                    cmd_parser.required = getattr(cls, 'required', None)
                     ldescr = getattr(cls, 'long_description', '')
                     if subcmd.path == 'history_run':
                         instance = cls(
@@ -207,11 +213,13 @@ class Shell(Cmd):
                             self.auth_base, self.cloud)
                     cmd_parser.update_arguments(instance.arguments)
                     cmd_parser.arguments = instance.arguments
+                    subpath = subcmd.path.split('_')[
+                        (len(cmd.path.split('_')) - 1):]
                     cmd_parser.syntax = '%s %s' % (
-                        subcmd.path.replace('_', ' '), cls.syntax)
+                        ' '.join(subpath), instance.syntax)
                     help_method = self._create_help_method(
                         cmd.name, cmd_parser.arguments,
-                        subcmd.help, cmd_parser.syntax)
+                        cmd_parser.required, subcmd.help, cmd_parser.syntax)
                     if '-h' in cmd_args or '--help' in cmd_args:
                         help_method()
                         if ldescr.strip():
@@ -239,7 +247,7 @@ class Shell(Cmd):
                 old_prompt = self.prompt
                 new_context._roll_command(cmd.parent_path)
                 new_context.set_prompt(subcmd.path.replace('_', ' '))
-                newcmds = [subcmd for subcmd in subcmd.get_subcommands()]
+                newcmds = [subcmd for subcmd in subcmd.subcommands.values()]
                 for subcmd in newcmds:
                     new_context._register_command(subcmd.path)
                 new_context.cmdloop()
@@ -251,7 +259,7 @@ class Shell(Cmd):
         def help_method(self):
             print('%s (%s -h for more options)' % (cmd.help, cmd.name))
             if cmd.is_command:
-                cls = cmd.get_class()
+                cls = cmd.cmd_class
                 ldescr = getattr(cls, 'long_description', '')
                 #_construct_command_syntax(cls)
                 plist = self.prompt[len(self._prefix):-len(self._suffix)]
@@ -275,18 +283,18 @@ class Shell(Cmd):
         def complete_method(self, text, line, begidx, endidx):
             subcmd, cmd_args = cmd.parse_out(split_input(line)[1:])
             if subcmd.is_command:
-                cls = subcmd.get_class()
+                cls = subcmd.cmd_class
                 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))
+                    cls.help, cmd_name, cls.syntax))
                 cmd_args = {}
                 for arg in instance.arguments.values():
                     cmd_args[','.join(arg.parsed_name)] = arg.help
-                print_dict(cmd_args, ident=2)
+                print_dict(cmd_args, indent=2)
                 stdout.write('%s %s' % (self.prompt, line))
-            return subcmd.get_subnames()
+            return subcmd.subnames()
         self._register_method(complete_method, 'complete_%s' % cmd.name)
 
     @property
@@ -300,14 +308,19 @@ class Shell(Cmd):
         self.auth_base = auth_base
         self.cloud = cloud
         self._parser = parser
-        self._history = History(
-            parser.arguments['config'].get_global('history_file'))
+        cnf = parser.arguments['config']
+        self._history = History(cnf.get('global', 'history_file'))
+        self._history.limit = cnf.get('global', 'history_limit')
         if path:
             cmd = self.cmd_tree.get_command(path)
             intro = cmd.path.replace('_', ' ')
         else:
             intro = self.cmd_tree.name
 
+        acceptable = parser.arguments['config'].groups
+        total = self.cmd_tree.groups.keys()
+        self.cmd_tree.exclude(set(total).difference(acceptable))
+
         for subcmd in self.cmd_tree.get_subcommands(path):
             self._register_command(subcmd.path)