command_shell.py 8.95 KB
Newer Older
1
2
3
4
5
6
7
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
8
9
#      copyright notice, this list of conditions and the following
#      disclaimer.
10
11
#
#   2. Redistributions in binary form must reproduce the above
12
13
14
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

from cmd import Cmd
from os import popen
36
from sys import stdout
37
38
from argparse import ArgumentParser

Stavros Sachtouris's avatar
Stavros Sachtouris committed
39
from kamaki.cli import _exec_cmd, _print_error_message
40
41
42
from kamaki.cli.argument import _arguments, update_arguments
from kamaki.cli.utils import print_dict
from kamaki.cli.history import History
Stavros Sachtouris's avatar
Stavros Sachtouris committed
43
from kamaki.cli.errors import CLIError
44

45

46
47
48
49
50
51
52
53
54
55
56
57
58
def _init_shell(exe_string, arguments):
    arguments.pop('version', None)
    arguments.pop('options', None)
    arguments.pop('history', None)
    shell = Shell()
    shell.set_prompt(exe_string)
    from kamaki import __version__ as version
    shell.greet(version)
    shell.do_EOF = shell.do_exit
    from kamaki.cli.command_tree import CommandTree
    shell.cmd_tree = CommandTree(
        'kamaki', 'A command line tool for poking clouds')
    return shell
59

60
61

class Shell(Cmd):
62
63
64
65
66
    """Kamaki interactive shell"""
    _prefix = '['
    _suffix = ']:'
    cmd_tree = None
    _history = None
67
68
69
70
    _arguments = None
    _context_stack = []
    _prompt_stack = []

71
72
    undoc_header = 'interactive shell commands:'

73
74
75
76
77
78
79
80
    def postcmd(self, post, line):
        if self._context_stack:
            self._roll_command()
            self.set_prompt(self._prompt_stack.pop()[1:-2])
            self._restore(self._context_stack.pop())

        return Cmd.postcmd(self, post, line)

81
    def precmd(self, line):
82
        if line.startswith('/'):
83
84
            cur_cmd_path = self.prompt.replace(' ', '_')[1:-2]
            if cur_cmd_path != self.cmd_tree.name:
85
86
87
88
                cur_cmd = self.cmd_tree.get_command(cur_cmd_path)
                self._context_stack.append(self._backup())
                self._prompt_stack.append(self.prompt)
                new_context = self
89
                new_context._roll_command(cur_cmd.parent_path)
90
91
92
93
                new_context.set_prompt(self.cmd_tree.name)
                for grp_cmd in self.cmd_tree.get_subcommands():
                    self._register_command(grp_cmd.path)
            return line[1:]
94
95
        return line

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    def greet(self, version):
        print('kamaki v%s - Interactive Shell\n\t(exit or ^D to exit)\n'\
            % version)

    def set_prompt(self, new_prompt):
        self.prompt = '[%s]:' % new_prompt

    def do_exit(self, line):
        print('')
        return True

    def do_shell(self, line):
        output = popen(line).read()
        print(output)

    @property
    def path(self):
        if self._cmd:
114
            return self._cmd.path
115
116
117
118
119
120
121
122
123
124
125
126
127
        return ''

    @classmethod
    def _register_method(self, method, name):
        self.__dict__[name] = method

    @classmethod
    def _unregister_method(self, name):
        try:
            self.__dict__.pop(name)
        except KeyError:
            pass

128
    def _roll_command(self, cmd_path=None):
129
130
131
132
133
        for subname in self.cmd_tree.get_subnames(cmd_path):
            self._unregister_method('do_%s' % subname)
            self._unregister_method('complete_%s' % subname)
            self._unregister_method('help_%s' % subname)

134

135
136
137
138
139
140
141
142
    @classmethod
    def _backup(self):
        return dict(self.__dict__)

    @classmethod
    def _restore(self, oldcontext):
        self.__dict__ = oldcontext

Stavros Sachtouris's avatar
Stavros Sachtouris committed
143
    def _register_command(self, cmd_path):
144
        cmd = self.cmd_tree.get_command(cmd_path)
145
        arguments = self._arguments
146

147
        def do_method(new_context, line):
148
149
150
151
152
153
            """ Template for all cmd.Cmd methods of the form do_<cmd name>
                Parse cmd + args and decide to execute or change context
                <cmd> <term> <term> <args> is always parsed to most specific
                even if cmd_term_term is not a terminal path
            """
            subcmd, cmd_args = cmd.parse_out(line.split())
154
155
156
            if self._history:
                self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
            cmd_parser = ArgumentParser(cmd.name, add_help=False)
157
158
159
160
161
            cmd_parser.description = subcmd.help

            # exec command or change context
            if subcmd.is_command:  # exec command
                cls = subcmd.get_class()
162
                instance = cls(dict(arguments))
163
164
                cmd_parser.prog = '%s %s' % (cmd_parser.prog.replace('_', ' '),
                    cls.syntax)
165
                update_arguments(cmd_parser, instance.arguments)
166
167
168
169
170
171
172
                if '-h' in cmd_args or '--help' in cmd_args:
                    cmd_parser.print_help()
                    return
                parsed, unparsed = cmd_parser.parse_known_args(cmd_args)

                for name, arg in instance.arguments.items():
                    arg.value = getattr(parsed, name, arg.default)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
173
174
175
176
                try:
                    _exec_cmd(instance, unparsed, cmd_parser.print_help)
                except CLIError as err:
                    _print_error_message(err)
177
178
            elif ('-h' in cmd_args or '--help' in cmd_args) \
            or len(cmd_args):  # print options
179
                print('%s: %s' % (cmd.name, subcmd.help))
180
181
182
183
184
                options = {}
                for sub in subcmd.get_subcommands():
                    options[sub.name] = sub.help
                print_dict(options)
            else:  # change context
185
                #new_context = this
186
187
188
189
190
191
                backup_context = self._backup()
                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()]
                for subcmd in newcmds:
Stavros Sachtouris's avatar
Stavros Sachtouris committed
192
                    new_context._register_command(subcmd.path)
193
194
195
196
197
198
199
200
201
202
203
204
205
206
                new_context.cmdloop()
                self.prompt = old_prompt
                #when new context is over, roll back to the old one
                self._restore(backup_context)
        self._register_method(do_method, 'do_%s' % cmd.name)

        def help_method(self):
            print('%s (%s -h for more options)' % (cmd.help, cmd.name))
        self._register_method(help_method, 'help_%s' % cmd.name)

        def complete_method(self, text, line, begidx, endidx):
            subcmd, cmd_args = cmd.parse_out(line.split()[1:])
            if subcmd.is_command:
                cls = subcmd.get_class()
207
                instance = cls(dict(arguments))
208
209
210
211
212
213
214
                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))
                cmd_args = {}
                for arg in instance.arguments.values():
                    cmd_args[','.join(arg.parsed_name)] = arg.help
Stavros Sachtouris's avatar
Stavros Sachtouris committed
215
                print_dict(cmd_args, ident=2)
216
217
218
219
220
221
222
223
224
225
226
                stdout.write('%s %s' % (self.prompt, line))
            return subcmd.get_subnames()
        self._register_method(complete_method, 'complete_%s' % cmd.name)

    @property
    def doc_header(self):
        tmp_partition = self.prompt.partition(self._prefix)
        tmp_partition = tmp_partition[2].partition(self._suffix)
        hdr = tmp_partition[0].strip()
        return '%s commands:' % hdr

227
228
229
    def run(self, arguments, path=''):
        self._history = History(arguments['config'].get('history', 'file'))
        self._arguments = arguments
Stavros Sachtouris's avatar
Stavros Sachtouris committed
230
        if path:
231
232
233
234
235
236
            cmd = self.cmd_tree.get_command(path)
            intro = cmd.path.replace('_', ' ')
        else:
            intro = self.cmd_tree.name

        for subcmd in self.cmd_tree.get_subcommands(path):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
237
            self._register_command(subcmd.path)
238
239

        self.set_prompt(intro)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
240

241
        self.cmdloop()