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