Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / history_cli.py @ 439826ec

History | View | Annotate | Download (6.9 kB)

1
#!/usr/bin/env python
2

    
3
# Copyright 2012 GRNET S.A. All rights reserved.
4
#
5
# Redistribution and use in source and binary forms, with or
6
# without modification, are permitted provided that the following
7
# conditions are met:
8
#
9
#   1. Redistributions of source code must retain the above
10
#      copyright notice, this list of conditions and the following
11
#      disclaimer.
12
#
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.
17
#
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.
30
#
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.
35

    
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
42
from kamaki.cli import exec_cmd, print_error_message
43
from kamaki.cli.errors import CLIError, CLISyntaxError, raiseCLIError
44
from kamaki.cli.utils import split_input
45
from kamaki.clients import ClientError
46

    
47

    
48
history_cmds = CommandTree('history', 'Command history')
49
_commands = [history_cmds]
50

    
51

    
52
def _get_num_list(num_str):
53
    if num_str.startswith('-'):
54
        num1, sep, num2 = num_str[1:].partition('-')
55
        num1 = '-%s' % num1
56
    else:
57
        num1, sep, num2 = num_str.partition('-')
58
    (num1, num2) = (num1.strip(), num2.strip())
59
    try:
60
        num1 = (-int(num1[1:])) if num1.startswith('-') else int(num1)
61
    except ValueError as e:
62
        raiseCLIError(e, 'Invalid id %s' % num1)
63
    if sep:
64
        try:
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)
69
    else:
70
        num2 = (1 + num1) if num1 else 0
71
    return [i for i in range(num1, num2)]
72

    
73

    
74
class _init_history(_command_init):
75
    def main(self):
76
        self.history = History(self.config.get('history', 'file'))
77

    
78

    
79
@command(history_cmds)
80
class history_show(_init_history):
81
    """Show intersession command history
82
    ---
83
    - With no parameters : pick all commands in history records
84
    - With:
85
    .   1.  <order-id> : pick the <order-id>th command
86
    .   2.  <order-id-1>-<order-id-2> : pick all commands ordered in the range
87
    .       [<order-id-1> - <order-id-2>]
88
    .   - the above can be mixed and repeated freely, separated by spaces
89
    .       e.g. pick 2 4-7 -3
90
    .   - Use negative integers to count from the end of the list, e.g.:
91
    .       -2 means : the command before the last one
92
    .       -2-5 means : last 2 commands + the first 5
93
    .       -5--2 means : the last 5 commands except the last 2
94
    """
95

    
96
    arguments = dict(
97
        limit=IntArgument('number of lines to show', '-n', default=0),
98
        match=ValueArgument('show lines that match given terms', '--match')
99
    )
100

    
101
    def main(self, *cmd_ids):
102
        super(self.__class__, self).main()
103
        ret = self.history.get(match_terms=self['match'], limit=self['limit'])
104

    
105
        if not cmd_ids:
106
            print(''.join(ret))
107
            return
108

    
109
        num_list = []
110
        for num_str in cmd_ids:
111
            num_list += _get_num_list(num_str)
112

    
113
        for cmd_id in num_list:
114
            try:
115
                cur_id = int(cmd_id)
116
                if cur_id:
117
                    print(ret[cur_id - (1 if cur_id > 0 else 0)][:-1])
118
            except IndexError as e2:
119
                print('LA %s LA' % self.__doc__)
120
                raiseCLIError(e2, 'Command id out of 1-%s range' % len(ret))
121

    
122

    
123
@command(history_cmds)
124
class history_clean(_init_history):
125
    """Clean up history (permanent)"""
126

    
127
    def main(self):
128
        super(self.__class__, self).main()
129
        self.history.clean()
130

    
131

    
132
@command(history_cmds)
133
class history_run(_init_history):
134
    """Run previously executed command(s)
135
    Use with:
136
    .   1.  <order-id> : pick the <order-id>th command
137
    .   2.  <order-id-1>-<order-id-2> : pick all commands ordered in the range
138
    .       [<order-id-1> - <order-id-2>]
139
    .   - Use negative integers to count from the end of the list, e.g.:
140
    .       -2 means : the command before the last one
141
    .       -2-5 means : last 2 commands + the first 5
142
    .       -5--2 mean
143
    .   - to find order ids for commands try   /history show.
144
    """
145

    
146
    _cmd_tree = None
147

    
148
    def __init__(self, arguments={}, cmd_tree=None):
149
        super(self.__class__, self).__init__(arguments)
150
        self._cmd_tree = cmd_tree
151

    
152
    def _run_from_line(self, line):
153
        terms = split_input(line)
154
        cmd, args = self._cmd_tree.find_best_match(terms)
155
        if not cmd.is_command:
156
            return
157
        try:
158
            instance = cmd.get_class()(self.arguments)
159
            instance.config = self.config
160
            prs = ArgumentParseManager(cmd.path.split(),
161
                dict(instance.arguments))
162
            prs.syntax = '%s %s' % (cmd.path.replace('_', ' '),
163
                cmd.get_class().syntax)
164
            prs.parse(args)
165
            exec_cmd(instance, prs.unparsed, prs.parser.print_help)
166
        except (CLIError, ClientError) as err:
167
            print_error_message(err)
168
        except Exception as e:
169
            print('Execution of [ %s ] failed' % line)
170
            print('\t%s' % e)
171

    
172
    def _get_cmd_ids(self, cmd_ids):
173
        if not cmd_ids:
174
            raise CLISyntaxError('Usage: <id1|id1-id2> [id3|id3-id4] ...',
175
                details=self.__doc__.split('\n'))
176
        cmd_id_list = []
177
        for cmd_str in cmd_ids:
178
            cmd_id_list += _get_num_list(cmd_str)
179
        return cmd_id_list
180

    
181
    def main(self, *command_ids):
182
        super(self.__class__, self).main()
183
        cmd_list = self._get_cmd_ids(command_ids)
184
        for cmd_id in cmd_list:
185
            r = self.history.retrieve(cmd_id)
186
            try:
187
                print('< %s >' % r[:-1])
188
            except (TypeError, KeyError):
189
                continue
190
            if self._cmd_tree:
191
                r = r[len('kamaki '):-1] if r.startswith('kamaki ') else r[:-1]
192
                self._run_from_line(r)