Minor fixes
[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, _exec_cmd
39 from .errors import CLIError
40 from .argument import _arguments
41 from .utils import magenta, print_dict
42 from sys import stdout
43 from .history import History
44
45 def _fix_arguments():
46         _arguments.pop('version', None)
47         _arguments.pop('options', None)
48         _arguments.pop('history', None)
49
50 class Shell(Cmd):
51         """Kamaki interactive shell"""
52         _prefix = '['
53         _suffix = ']:'
54         cmd_tree = None
55         _history = None
56
57         def greet(self, version):
58                 print('kamaki v%s - Interactive Shell\n\t(exit or ^D to exit)\n'%version)
59         def set_prompt(self, new_prompt):
60                 self.prompt = '[%s]:'%new_prompt
61
62         def do_exit(self, line):
63                 print('')
64                 return True
65
66         def do_shell(self, line):
67                 output = popen(line).read()
68                 print(output)
69         def help_shell(self):
70                 print('Execute OS shell commands')
71
72         @property 
73         def path(self):
74                 if self._cmd:
75                         return _cmd.path
76                 return ''
77
78         @classmethod
79         def _register_method(self, method, name):
80                 self.__dict__[name]=method
81
82         def _roll_command(self, cmd_path):
83                 for subname in self.cmd_tree.get_subnames(cmd_path):
84                         try:
85                                 self.__dict__.pop('do_%s'%subname)
86                                 self.__dict__.pop('complete_%s'%subname)
87                                 self.__dict__.pop('help_%s'%subname)
88                         except KeyError:
89                                 pass
90
91         @classmethod 
92         def _backup(self):
93                 return dict(self.__dict__)
94         @classmethod
95         def _restore(self, oldcontext):
96                 self.__dict__= oldcontext
97
98         def _push_in_command(self, cmd_path):
99                 cmd = self.cmd_tree.get_command(cmd_path)
100                 _cmd_tree = self.cmd_tree
101                 _history = self._history
102
103                 def do_method(self, line):
104                         """ Template for all cmd.Cmd methods of the form do_<cmd name>
105                                 Parse cmd + args and decide to execute or change context
106                                 <cmd> <term> <term> <args> is always parsed to the most specific cmd path
107                                 even if cmd_term_term is not a terminal path
108                         """
109                         if _history:
110                                 _history.add(' '.join([cmd.path.replace('_',' '), line]))
111                         subcmd, cmd_args = cmd.parse_out(line.split())
112                         active_terms = [cmd.name]+subcmd.path.split('_')[len(cmd.path.split('_')):]
113                         subname = '_'.join(active_terms)
114                         cmd_parser = ArgumentParser(subname, add_help=False)
115                         cmd_parser.description = subcmd.help
116
117                         #exec command or change context
118                         if subcmd.is_command:#exec command
119                                 cls = subcmd.get_class()
120                                 instance = cls(_arguments)
121                                 cmd_parser.prog= cmd_parser.prog.replace('_', ' ')+' '+cls.syntax
122                                 _update_parser(cmd_parser, instance.arguments)
123                                 if '-h' in cmd_args or '--help' in cmd_args:
124                                         cmd_parser.print_help()
125                                         return
126                                 parsed, unparsed = cmd_parser.parse_known_args(cmd_args)
127
128                                 for name, arg in instance.arguments.items():
129                                         arg.value = getattr(parsed, name, arg.default)
130                                 _exec_cmd(instance, unparsed, cmd_parser.print_help)
131                         elif ('-h' in cmd_args or '--help' in cmd_args) \
132                         or len(cmd_args):#print options
133                                 print('%s: %s'%(subname, subcmd.help))
134                                 options = {}
135                                 for sub in subcmd.get_subcommands():
136                                         options[sub.name] = sub.help
137                                 print_dict(options)
138                         else:#change context
139                                 new_context = self
140                                 backup_context = self._backup()
141                                 new_context._roll_command(cmd.parent_path)
142                                 old_prompt = self.prompt
143                                 new_context.set_prompt(subcmd.path.replace('_',' '))
144                                 newcmds = [subcmd for subcmd in subcmd.get_subcommands()]
145                                 for subcmd in newcmds:
146                                         new_context._push_in_command(subcmd.path)
147                                 new_context.cmdloop()
148                                 self.prompt = old_prompt
149                                 #when new context is over, roll back to the old one
150                                 self._restore(backup_context)
151                 self._register_method(do_method, 'do_%s'%cmd.name)
152
153                 def help_method(self):
154                         print('%s (%s -h for more options)'%(cmd.help, cmd.name))
155                 self._register_method(help_method, 'help_%s'%cmd.name)
156
157                 def complete_method(self, text, line, begidx, endidx):
158                         subcmd, cmd_args = cmd.parse_out(line.split()[1:])
159                         if subcmd.is_command:
160                                 cls = subcmd.get_class()
161                                 instance = cls({})
162                                 empty, sep, subname = subcmd.path.partition(cmd.path)
163                                 cmd_name = '%s %s'%(cmd.name,subname.replace('_',' '))
164                                 print('\n%s\nSyntax:\t%s %s'%(cls.description,cmd_name,cls.syntax))
165                                 cmd_args={}
166                                 for arg in instance.arguments.values():
167                                         cmd_args[','.join(arg.parsed_name)]=arg.help
168                                 print_dict(cmd_args, ident=14)
169                                 stdout.write('%s %s'%(self.prompt,line))
170                         return subcmd.get_subnames()
171                 self._register_method(complete_method, 'complete_%s'%cmd.name)
172
173         def run(self, path=''):
174                 self._history = History(_arguments['config'].get('history', 'file'))
175                 if len(path):
176                         cmd = self.cmd_tree.get_command(path)
177                         intro = cmd.path.replace('_', ' ')
178                 else:
179                         intro = self.cmd_tree.name
180
181                 for subcmd in self.cmd_tree.get_subcommands(path):
182                         self._push_in_command(subcmd.path)
183
184                 self.set_prompt(intro)
185                 self.cmdloop()