command_shell.py 6.38 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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
#	  copyright notice, this list of conditions and the following
#	  disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#	  copyright notice, this list of conditions and the following
#	  disclaimer in the documentation and/or other materials
#	  provided with the distribution.
#
# 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 new import instancemethod
from os import popen
from argparse import ArgumentParser
38
from kamaki.cli import _update_parser, _exec_cmd
39
40
from .errors import CLIError
from .argument import _arguments
41
42
from .utils import magenta, print_dict
from sys import stdout
Stavros Sachtouris's avatar
Stavros Sachtouris committed
43
from .history import History
44
45
46
47

def _fix_arguments():
	_arguments.pop('version', None)
	_arguments.pop('options', None)
48
	_arguments.pop('history', None)
49
50
51
52
53

class Shell(Cmd):
	"""Kamaki interactive shell"""
	_prefix = '['
	_suffix = ']:'
54
	cmd_tree = None
Stavros Sachtouris's avatar
Stavros Sachtouris committed
55
	_history = None
56
	undoc_header='interactive shell commands:'
57
58
59
60
61
62
63

	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):
64
		print('')
65
66
67
		return True

	def do_shell(self, line):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
68
		output = popen(line).read()
69
		print(output)
70

71
72
73
74
75
76
	@property 
	def path(self):
		if self._cmd:
			return _cmd.path
		return ''

77
78
	@classmethod
	def _register_method(self, method, name):
79
		self.__dict__[name]=method
80
81
82
83
84
85
	@classmethod
	def _unregister_method(self, name):
		try:
			self.__dict__.pop(name)
		except KeyError:
			pass
Stavros Sachtouris's avatar
Stavros Sachtouris committed
86
87
	def _roll_command(self, cmd_path):
		for subname in self.cmd_tree.get_subnames(cmd_path):
88
89
90
			self._unregister_method('do_%s'%subname)
			self._unregister_method('complete_%s'%subname)
			self._unregister_method('help_%s'%subname)
Stavros Sachtouris's avatar
Stavros Sachtouris committed
91

92
93
94
95
96
97
	@classmethod 
	def _backup(self):
		return dict(self.__dict__)
	@classmethod
	def _restore(self, oldcontext):
		self.__dict__= oldcontext
98

99
100
101
	def _push_in_command(self, cmd_path):
		cmd = self.cmd_tree.get_command(cmd_path)
		_cmd_tree = self.cmd_tree
Stavros Sachtouris's avatar
Stavros Sachtouris committed
102
		_history = self._history
103
104
105
106
107
108
109

		def do_method(self, line):
			""" 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 the most specific cmd path
				even if cmd_term_term is not a terminal path
			"""
Stavros Sachtouris's avatar
Stavros Sachtouris committed
110
111
			if _history:
				_history.add(' '.join([cmd.path.replace('_',' '), line]))
112
113
114
			subcmd, cmd_args = cmd.parse_out(line.split())
			active_terms = [cmd.name]+subcmd.path.split('_')[len(cmd.path.split('_')):]
			subname = '_'.join(active_terms)
115
			cmd_parser = ArgumentParser(subname, add_help=False)
116
117
118
119
			cmd_parser.description = subcmd.help

			#exec command or change context
			if subcmd.is_command:#exec command
120
				cls = subcmd.get_class()
121
				instance = cls(dict(_arguments))
122
				cmd_parser.prog= cmd_parser.prog.replace('_', ' ')+' '+cls.syntax
123
				_update_parser(cmd_parser, instance.arguments)
124
125
126
127
				if '-h' in cmd_args or '--help' in cmd_args:
					cmd_parser.print_help()
					return
				parsed, unparsed = cmd_parser.parse_known_args(cmd_args)
128
129
130

				for name, arg in instance.arguments.items():
					arg.value = getattr(parsed, name, arg.default)
131
132
133
134
135
136
137
138
139
140
141
142
				_exec_cmd(instance, unparsed, cmd_parser.print_help)
			elif ('-h' in cmd_args or '--help' in cmd_args) \
			or len(cmd_args):#print options
				print('%s: %s'%(subname, subcmd.help))
				options = {}
				for sub in subcmd.get_subcommands():
					options[sub.name] = sub.help
				print_dict(options)
			else:#change context
				new_context = self
				backup_context = self._backup()
				old_prompt = self.prompt
143
				new_context._roll_command(cmd.parent_path)
144
145
146
147
148
149
150
151
152
153
				new_context.set_prompt(subcmd.path.replace('_',' '))
				newcmds = [subcmd for subcmd in subcmd.get_subcommands()]
				for subcmd in newcmds:
					new_context._push_in_command(subcmd.path)
				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)

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

		def complete_method(self, text, line, begidx, endidx):
159
160
161
			subcmd, cmd_args = cmd.parse_out(line.split()[1:])
			if subcmd.is_command:
				cls = subcmd.get_class()
162
				instance = cls(dict(_arguments))
163
164
165
166
167
168
169
170
171
172
173
				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
				print_dict(cmd_args, ident=14)
				stdout.write('%s %s'%(self.prompt,line))
			return subcmd.get_subnames()
		self._register_method(complete_method, 'complete_%s'%cmd.name)

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

179
	def run(self, path=''):
Stavros Sachtouris's avatar
Stavros Sachtouris committed
180
		self._history = History(_arguments['config'].get('history', 'file'))
181
182
183
		if len(path):
			cmd = self.cmd_tree.get_command(path)
			intro = cmd.path.replace('_', ' ')
184
		else:
185
			intro = self.cmd_tree.name
186

187
188
		for subcmd in self.cmd_tree.get_subcommands(path):
			self._push_in_command(subcmd.path)
189

190
191
		self.set_prompt(intro)
		self.cmdloop()