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