3 # Copyright 2012-2013 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
13 # 2. Redistributions in binary form must reproduce the above
14 # copyright notice, this list of conditions and the following
15 # disclaimer in the documentation and/or other materials
16 # provided with the distribution.
18 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
31 # The views and conclusions contained in the software and
32 # documentation are those of the authors and should not be
33 # interpreted as representing official policies, either expressed
34 # or implied, of GRNET S.A.
36 from kamaki.cli.command_tree import CommandTree
37 from kamaki.cli.argument import IntArgument, ValueArgument
38 from kamaki.cli.argument import ArgumentParseManager
39 from kamaki.cli.history import History
40 from kamaki.cli import command
41 from kamaki.cli.commands import _command_init, errors
42 from kamaki.cli import exec_cmd, print_error_message
43 from kamaki.cli.errors import CLIError, raiseCLIError
44 from kamaki.cli.utils import split_input
45 from kamaki.clients import ClientError
48 history_cmds = CommandTree('history', 'Kamaki command history')
49 _commands = [history_cmds]
52 def _get_num_list(num_str):
53 if num_str.startswith('-'):
54 num1, sep, num2 = num_str[1:].partition('-')
57 num1, sep, num2 = num_str.partition('-')
58 (num1, num2) = (num1.strip(), num2.strip())
60 num1 = (-int(num1[1:])) if num1.startswith('-') else int(num1)
61 except ValueError as e:
62 raiseCLIError(e, 'Invalid id %s' % num1)
65 num2 = (-int(num2[1:])) if num2.startswith('-') else int(num2)
66 num2 += 1 if num2 > 0 else 0
67 except ValueError as e:
68 raiseCLIError(e, 'Invalid id %s' % num2)
70 num2 = (1 + num1) if num1 else 0
71 return [i for i in range(num1, num2)]
74 class _init_history(_command_init):
78 self.history = History(self.config.get_global('history_file'))
84 @command(history_cmds)
85 class history_show(_init_history):
86 """Show intersession command history
88 - With no parameters : pick all commands in history records
90 . 1. <order-id> : pick the <order-id>th command
91 . 2. <order-id-1>-<order-id-2> : pick all commands ordered in the range
92 . [<order-id-1> - <order-id-2>]
93 . - the above can be mixed and repeated freely, separated by spaces
95 . - Use negative integers to count from the end of the list, e.g.:
96 . -2 means : the command before the last one
97 . -2-5 means : last 2 commands + the first 5
98 . -5--2 means : the last 5 commands except the last 2
103 'number of lines to show',
106 match=ValueArgument('show lines that match given terms', '--match')
110 def _run(self, *cmd_ids):
111 ret = self.history.get(match_terms=self['match'], limit=self['limit'])
118 for num_str in cmd_ids:
119 num_list += _get_num_list(num_str)
121 for cmd_id in num_list:
125 print(ret[cur_id - (1 if cur_id > 0 else 0)][:-1])
126 except IndexError as e2:
127 raiseCLIError(e2, 'Command id out of 1-%s range' % len(ret))
129 def main(self, *cmd_ids):
130 super(self.__class__, self)._run()
134 @command(history_cmds)
135 class history_clean(_init_history):
136 """Clean up history (permanent)"""
143 super(self.__class__, self)._run()
147 @command(history_cmds)
148 class history_run(_init_history):
149 """Run previously executed command(s)
151 . 1. <order-id> : pick the <order-id>th command
152 . 2. <order-id-1>-<order-id-2> : pick all commands ordered in the range
153 . [<order-id-1> - <order-id-2>]
154 . - Use negative integers to count from the end of the list, e.g.:
155 . -2 means : the command before the last one
156 . -2-5 means : last 2 commands + the first 5
158 . - to find order ids for commands try /history show.
163 def __init__(self, arguments={}, auth_base=None, cmd_tree=None):
164 super(self.__class__, self).__init__(arguments, auth_base=auth_base)
165 self._cmd_tree = cmd_tree
168 def _run_from_line(self, line):
169 terms = split_input(line)
170 cmd, args = self._cmd_tree.find_best_match(terms)
171 if not cmd.is_command:
174 instance = cmd.get_class()(
176 auth_base=getattr(self, 'auth_base', None))
177 instance.config = self.config
178 prs = ArgumentParseManager(
180 dict(instance.arguments))
181 prs.syntax = '%s %s' % (
182 cmd.path.replace('_', ' '),
183 cmd.get_class().syntax)
185 exec_cmd(instance, prs.unparsed, prs.parser.print_help)
186 except (CLIError, ClientError) as err:
187 print_error_message(err)
188 except Exception as e:
189 print('Execution of [ %s ] failed' % line)
193 @errors.history._get_cmd_ids
194 def _get_cmd_ids(self, cmd_ids):
196 for cmd_str in cmd_ids:
197 cmd_id_list += _get_num_list(cmd_str)
201 def _run(self, *command_ids):
202 cmd_list = self._get_cmd_ids(command_ids)
203 for cmd_id in cmd_list:
204 r = self.history.retrieve(cmd_id)
206 print('< %s >' % r[:-1])
207 except (TypeError, KeyError):
210 r = r[len('kamaki '):-1] if r.startswith('kamaki ') else r[:-1]
211 self._run_from_line(r)
213 def main(self, *command_ids):
214 super(self.__class__, self)._run()
215 self._run(*command_ids)