Match more quoted text
[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 os import popen
36 from sys import stdout
37 from argparse import ArgumentParser
38 from re import compile as regex_compile
39
40 from kamaki.cli import _exec_cmd, _print_error_message
41 from kamaki.cli.argument import update_arguments
42 from kamaki.cli.utils import print_dict
43 from kamaki.cli.history import History
44 from kamaki.cli.errors import CLIError
45
46
47 def _parse_with_regex(line, regex):
48     re_parser = regex_compile(regex)
49     return (re_parser.split(line), re_parser.findall(line))
50
51
52 def _split_input(line):
53     """Use regular expressions to split a line correctly
54     """
55     line = ' %s ' % line
56     (trivial_parts, interesting_parts) = _parse_with_regex(line, ' \'.*?\' ')
57     terms = []
58     for i, ipart in enumerate(interesting_parts):
59         tpart = trivial_parts[i]
60         (sub_trivials, sub_interesting) = _parse_with_regex(tpart, ' ".*?" ')
61         for subi, subipart in enumerate(sub_interesting):
62             terms += sub_trivials[subi].split()
63             terms.append(subipart[2:-2])
64         terms += sub_trivials[-1].split()
65         terms.append(ipart[2:-2])
66     tpart = trivial_parts[-1]
67     (sub_trivials, sub_interesting) = _parse_with_regex(tpart, ' ".*?" ')
68     for subi, subipart in enumerate(sub_interesting):
69         terms += sub_trivials[subi].split()
70         terms.append(subipart[2:-2])
71     terms += sub_trivials[-1].split()
72     return terms
73
74
75 def _init_shell(exe_string, arguments):
76     arguments.pop('version', None)
77     arguments.pop('options', None)
78     arguments.pop('history', None)
79     shell = Shell()
80     shell.set_prompt(exe_string)
81     from kamaki import __version__ as version
82     shell.greet(version)
83     shell.do_EOF = shell.do_exit
84     from kamaki.cli.command_tree import CommandTree
85     shell.cmd_tree = CommandTree(
86         'kamaki', 'A command line tool for poking clouds')
87     return shell
88
89
90 class Shell(Cmd):
91     """Kamaki interactive shell"""
92     _prefix = '['
93     _suffix = ']:'
94     cmd_tree = None
95     _history = None
96     _arguments = None
97     _context_stack = []
98     _prompt_stack = []
99
100     undoc_header = 'interactive shell commands:'
101
102     def postcmd(self, post, line):
103         if self._context_stack:
104             self._roll_command()
105             self._restore(self._context_stack.pop())
106             self.set_prompt(self._prompt_stack.pop()[1:-2])
107
108         return Cmd.postcmd(self, post, line)
109
110     def precmd(self, line):
111         if line.startswith('/'):
112             cur_cmd_path = self.prompt.replace(' ', '_')[1:-2]
113             if cur_cmd_path != self.cmd_tree.name:
114                 cur_cmd = self.cmd_tree.get_command(cur_cmd_path)
115                 self._context_stack.append(self._backup())
116                 self._prompt_stack.append(self.prompt)
117                 new_context = self
118                 self._roll_command(cur_cmd.path)
119                 new_context.set_prompt(self.cmd_tree.name)
120                 for grp_cmd in self.cmd_tree.get_subcommands():
121                     self._register_command(grp_cmd.path)
122             return line[1:]
123         return line
124
125     def greet(self, version):
126         print('kamaki v%s - Interactive Shell\n\t(exit or ^D to exit)\n'\
127             % version)
128
129     def set_prompt(self, new_prompt):
130         self.prompt = '[%s]:' % new_prompt
131
132     def do_exit(self, line):
133         print('')
134         if self.prompt[1:-2] == self.cmd_tree.name:
135             exit(0)
136         return True
137
138     def do_shell(self, line):
139         output = popen(line).read()
140         print(output)
141
142     @property
143     def path(self):
144         if self._cmd:
145             return self._cmd.path
146         return ''
147
148     @classmethod
149     def _register_method(self, method, name):
150         self.__dict__[name] = method
151
152     @classmethod
153     def _unregister_method(self, name):
154         try:
155             self.__dict__.pop(name)
156         except KeyError:
157             pass
158
159     def _roll_command(self, cmd_path=None):
160         for subname in self.cmd_tree.get_subnames(cmd_path):
161             self._unregister_method('do_%s' % subname)
162             self._unregister_method('complete_%s' % subname)
163             self._unregister_method('help_%s' % subname)
164
165     @classmethod
166     def _backup(self):
167         return dict(self.__dict__)
168
169     @classmethod
170     def _restore(self, oldcontext):
171         self.__dict__ = oldcontext
172
173     def _register_command(self, cmd_path):
174         cmd = self.cmd_tree.get_command(cmd_path)
175         arguments = self._arguments
176
177         def do_method(new_context, line):
178             """ Template for all cmd.Cmd methods of the form do_<cmd name>
179                 Parse cmd + args and decide to execute or change context
180                 <cmd> <term> <term> <args> is always parsed to most specific
181                 even if cmd_term_term is not a terminal path
182             """
183             subcmd, cmd_args = cmd.parse_out(_split_input(line))
184             if self._history:
185                 self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
186             cmd_parser = ArgumentParser(cmd.name, add_help=False)
187             cmd_parser.description = subcmd.help
188
189             # exec command or change context
190             if subcmd.is_command:  # exec command
191                 cls = subcmd.get_class()
192                 instance = cls(dict(arguments))
193                 cmd_parser.prog = '%s %s' % (cmd_parser.prog.replace('_', ' '),
194                     cls.syntax)
195                 update_arguments(cmd_parser, instance.arguments)
196                 if '-h' in cmd_args or '--help' in cmd_args:
197                     cmd_parser.print_help()
198                     return
199                 parsed, unparsed = cmd_parser.parse_known_args(cmd_args)
200
201                 for name, arg in instance.arguments.items():
202                     arg.value = getattr(parsed, name, arg.default)
203                 try:
204                     _exec_cmd(instance, unparsed, cmd_parser.print_help)
205                 except CLIError as err:
206                     _print_error_message(err)
207             elif ('-h' in cmd_args or '--help' in cmd_args) \
208             or len(cmd_args):  # print options
209                 print('%s: %s' % (cmd.name, subcmd.help))
210                 options = {}
211                 for sub in subcmd.get_subcommands():
212                     options[sub.name] = sub.help
213                 print_dict(options)
214             else:  # change context
215                 #new_context = this
216                 backup_context = self._backup()
217                 old_prompt = self.prompt
218                 new_context._roll_command(cmd.parent_path)
219                 new_context.set_prompt(subcmd.path.replace('_', ' '))
220                 newcmds = [subcmd for subcmd in subcmd.get_subcommands()]
221                 for subcmd in newcmds:
222                     new_context._register_command(subcmd.path)
223                 new_context.cmdloop()
224                 self.prompt = old_prompt
225                 #when new context is over, roll back to the old one
226                 self._restore(backup_context)
227         self._register_method(do_method, 'do_%s' % cmd.name)
228
229         def help_method(self):
230             print('%s (%s -h for more options)' % (cmd.help, cmd.name))
231         self._register_method(help_method, 'help_%s' % cmd.name)
232
233         def complete_method(self, text, line, begidx, endidx):
234             subcmd, cmd_args = cmd.parse_out(_split_input(line)[1:])
235             if subcmd.is_command:
236                 cls = subcmd.get_class()
237                 instance = cls(dict(arguments))
238                 empty, sep, subname = subcmd.path.partition(cmd.path)
239                 cmd_name = '%s %s' % (cmd.name, subname.replace('_', ' '))
240                 print('\n%s\nSyntax:\t%s %s'\
241                     % (cls.description, cmd_name, cls.syntax))
242                 cmd_args = {}
243                 for arg in instance.arguments.values():
244                     cmd_args[','.join(arg.parsed_name)] = arg.help
245                 print_dict(cmd_args, ident=2)
246                 stdout.write('%s %s' % (self.prompt, line))
247             return subcmd.get_subnames()
248         self._register_method(complete_method, 'complete_%s' % cmd.name)
249
250     @property
251     def doc_header(self):
252         tmp_partition = self.prompt.partition(self._prefix)
253         tmp_partition = tmp_partition[2].partition(self._suffix)
254         hdr = tmp_partition[0].strip()
255         return '%s commands:' % hdr
256
257     def run(self, arguments, path=''):
258         self._history = History(arguments['config'].get('history', 'file'))
259         self._arguments = arguments
260         if path:
261             cmd = self.cmd_tree.get_command(path)
262             intro = cmd.path.replace('_', ' ')
263         else:
264             intro = self.cmd_tree.name
265
266         for subcmd in self.cmd_tree.get_subcommands(path):
267             self._register_command(subcmd.path)
268
269         self.set_prompt(intro)
270
271         self.cmdloop()