Seperate shell from one-command cli
[kamaki] / kamaki / cli / command_shell.py
1 # Copyright 2012 GRNET S.A. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6 #
7 #   1. Redistributions of source code must retain the above
8 #         copyright notice, this list of conditions and the following
9 #         disclaimer.
10 #
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.
15 #
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.
28 #
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.
33
34 from cmd import Cmd
35 from new import instancemethod
36 from os import popen
37 from argparse import ArgumentParser
38 from . import _update_parser
39 from .errors import CLIError
40 from .argument import _arguments
41 from .utils import magenta
42
43 def _fix_arguments():
44         _arguments.pop('version', None)
45         _arguments.pop('options', None)
46
47 class Shell(Cmd):
48         """Kamaki interactive shell"""
49         _prefix = '['
50         _suffix = ']:'
51
52         def greet(self, version):
53                 print('kamaki v%s - Interactive Shell\n\t(exit or ^D to exit)\n'%version)
54         def set_prompt(self, new_prompt):
55                 self.prompt = '[%s]:'%new_prompt
56
57         def do_exit(self, line):
58                 print
59                 return True
60
61         def do_shell(self, line):
62                 output = popen(line).read()
63                 print output
64         def help_shell(self):
65                 print('Execute OS shell commands')
66
67         @classmethod
68         def _register_method(self, method, name):
69                 #self.__dict__[name] = method
70                 self._tmp_method = instancemethod(method, name, self)
71                 setattr(self, name, self._tmp_method)
72                 del self._tmp_method
73
74         def _register_command(self, cmd):
75                 method_name = 'do_%s'%cmd.name
76                 def do_method(self, line):
77                         subcmd, cmd_argv = cmd.parse_out(line.split())
78
79                         subname = subcmd.name if cmd == subcmd else subcmd.path
80                         cmd_parser = ArgumentParser(subname, add_help=False)
81                         if subcmd.is_command:
82                                 cls = subcmd.get_class()
83                                 instance = cls(_arguments)
84                                 _update_parser(cmd_parser, instance.arguments)
85                                 cmd_parser.prog += ' '+cls.syntax
86                         if '-h' in cmd_argv or '--help'in cmd_argv:
87                                 cmd_parser.description = subcmd.help
88                                 cmd_parser.print_help()
89                                 return
90
91                         if subcmd.is_command:
92                                 parsed, unparsed = cmd_parser.parse_known_args(cmd_argv)
93
94                                 for name, arg in instance.arguments.items():
95                                         arg.value = getattr(parsed, name, arg.default)
96                                 try:
97                                         instance.main(*unparsed)
98                                 except TypeError as e:
99                                         if e.args and e.args[0].startswith('main()'):
100                                                 print(magenta('Syntax error'))
101                                                 if instance.get_argument('verbose'):
102                                                         print(unicode(e))
103                                                 print(subcmd.description)
104                                                 cmd_parser.print_help()
105                                         else:
106                                                 raise
107                                 except CLIError as err:
108                                         _print_error_message(err)
109                         else:
110                                 newshell = Shell()
111                                 newshell.set_prompt(' '.join(cmd.path.split('_')))
112                                 newshell.do_EOF = newshell.do_exit
113                                 newshell.kamaki_loop(cmd, cmd.path)
114                 self._register_method(do_method, method_name)
115
116                 method_name = 'help_%s'%cmd.name
117                 def help_method(self):
118                         if cmd.has_description:
119                                 print(cmd.description)
120                         else:
121                                 print('(no description)')
122                 self._register_method(help_method, method_name)
123
124                 method_name = 'complete_%s'%cmd.name
125                 def complete_method(self, text, line, begidx, endidx):
126                         print('Complete 0% FAT')
127                         return cmd.get_subnames()
128                 self._register_method(complete_method, method_name)
129                 print('Registed %s as %s'%(complete_method, method_name))
130
131         def kamaki_loop(self,command,prefix=''):
132                 #setup prompt
133                 if prefix in (None, ''):
134                         self.set_prompt(command.name)
135                 else:
136                         self.set_prompt(' '.join(command.path.split()))
137
138                 for cmd in command.get_subcommands():
139                         self._register_command(cmd)
140
141                 self.cmdloop()