Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / command_tree.py @ 60c42f9f

History | View | Annotate | Download (7.6 kB)

1
# Copyright 2012-2013 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 kamaki.clients import Client
35

    
36

    
37
class Command(object):
38
    """Store a command and the next-level (2 levels)"""
39
    _name = None
40
    path = None
41
    cmd_class = None
42
    subcommands = {}
43
    help = ' '
44

    
45
    def __init__(self, path, help=' ', subcommands={}, cmd_class=None):
46
        self.path = path
47
        self.help = help
48
        self.subcommands = dict(subcommands)
49
        self.cmd_class = cmd_class
50

    
51
    @property
52
    def name(self):
53
        if self._name is None:
54
            self._name = self.path.split('_')[-1]
55
        return str(self._name)
56

    
57
    def add_subcmd(self, subcmd):
58
        if subcmd.path == '%s_%s' % (self.path, subcmd.name):
59
            self.subcommands[subcmd.name] = subcmd
60
            return True
61
        return False
62

    
63
    def get_subcmd(self, name):
64
        try:
65
            return self.subcommands[name]
66
        except KeyError:
67
            return None
68

    
69
    def contains(self, name):
70
        """Check if a name is a direct child of self"""
71
        return name in self.subcommands
72

    
73
    @property
74
    def is_command(self):
75
        return self.cmd_class is not None and len(self.subcommands) == 0
76

    
77
    @property
78
    def has_description(self):
79
        return len(self.help.strip()) > 0
80

    
81
    @property
82
    def description(self):
83
        return self.help
84

    
85
    @property
86
    def parent_path(self):
87
        parentpath, sep, name = self.path.rpartition('_')
88
        return parentpath
89

    
90
    def set_class(self, cmd_class):
91
        self.cmd_class = cmd_class
92

    
93
    def get_class(self):
94
        return self.cmd_class
95

    
96
    def has_subname(self, subname):
97
        return subname in self.subcommands
98

    
99
    def get_subnames(self):
100
        return self.subcommands.keys()
101

    
102
    def get_subcommands(self):
103
        return self.subcommands.values()
104

    
105
    def sublen(self):
106
        return len(self.subcommands)
107

    
108
    def parse_out(self, args):
109
        cmd = self
110
        index = 0
111
        for term in args:
112
            try:
113
                cmd = cmd.subcommands[term]
114
            except KeyError:
115
                break
116
            index += 1
117
        return cmd, args[index:]
118

    
119
    def pretty_print(self, recursive=False):
120
        print('Path: %s (Name: %s) is_cmd: %s\n\thelp: %s' % (
121
            self.path,
122
            self.name,
123
            self.is_command,
124
            self.help))
125
        for cmd in self.get_subcommands():
126
            cmd.pretty_print(recursive)
127

    
128

    
129
class CommandTree(object):
130

    
131
    groups = {}
132
    _all_commands = {}
133
    name = None
134
    description = None
135

    
136
    def __init__(self, name, description=''):
137
        self.name = name
138
        self.description = description
139

    
140
    def add_command(self, command_path, description=None, cmd_class=None):
141
        terms = command_path.split('_')
142
        try:
143
            cmd = self.groups[terms[0]]
144
        except KeyError:
145
            cmd = Command(terms[0])
146
            self.groups[terms[0]] = cmd
147
            self._all_commands[terms[0]] = cmd
148
        path = terms[0]
149
        for term in terms[1:]:
150
            path += '_' + term
151
            try:
152
                cmd = cmd.subcommands[term]
153
            except KeyError:
154
                new_cmd = Command(path)
155
                self._all_commands[path] = new_cmd
156
                cmd.add_subcmd(new_cmd)
157
                cmd = new_cmd
158
        if cmd_class:
159
            cmd.set_class(cmd_class)
160
        if description is not None:
161
            cmd.help = description
162

    
163
    def find_best_match(self, terms):
164
        """Find a command that best matches a given list of terms
165

166
        :param terms: (list of str) match them against paths in cmd_tree
167

168
        :returns: (Command, list) the matching command, the remaining terms
169
        """
170
        path = []
171
        for term in terms:
172
            check_path = path + [term]
173
            if '_'.join(check_path) not in self._all_commands:
174
                break
175
            path = check_path
176
        if path:
177
            return (self._all_commands['_'.join(path)], terms[len(path):])
178
        return (None, terms)
179

    
180
    def add_tree(self, new_tree):
181
        tname = new_tree.name
182
        tdesc = new_tree.description
183
        self.groups.update(new_tree.groups)
184
        self._all_commands.update(new_tree._all_commands)
185
        self.set_description(tname, tdesc)
186

    
187
    def has_command(self, path):
188
        return path in self._all_commands
189

    
190
    def get_command(self, path):
191
        return self._all_commands[path]
192

    
193
    def get_groups(self):
194
        return self.groups.values()
195

    
196
    def get_group_names(self):
197
        return self.groups.keys()
198

    
199
    def set_description(self, path, description):
200
        self._all_commands[path].help = description
201

    
202
    def get_description(self, path):
203
        return self._all_commands[path].help
204

    
205
    def set_class(self, path, cmd_class):
206
        self._all_commands[path].set_class(cmd_class)
207

    
208
    def get_class(self, path):
209
        return self._all_commands[path].get_class()
210

    
211
    def get_subnames(self, path=None):
212
        if path in (None, ''):
213
            return self.get_group_names()
214
        return self._all_commands[path].get_subnames()
215

    
216
    def get_subcommands(self, path=None):
217
        if path in (None, ''):
218
            return self.get_groups()
219
        return self._all_commands[path].get_subcommands()
220

    
221
    def get_parent(self, path):
222
        if '_' not in path:
223
            return None
224
        terms = path.split('_')
225
        parent_path = '_'.join(terms[:-1])
226
        return self._all_commands[parent_path]
227

    
228
    def get_closest_ancestor_command(self, path):
229
        path, sep, name = path.rpartition('_')
230
        while len(path) > 0:
231
            cmd = self._all_commands[path]
232
            if cmd.is_command:
233
                return cmd
234
            path, sep, name = path.rpartition('_')
235
        return None
236

    
237
        if '_' not in path:
238
            return None
239
        terms = path.split()[:-1]
240
        while len(terms) > 0:
241
            tmp_path = '_'.join(terms)
242
            cmd = self._all_commands[tmp_path]
243
            if cmd.is_command:
244
                return cmd
245
            terms = terms[:-1]
246
        raise KeyError('No ancestor commands')
247

    
248
    def pretty_print(self, group=None):
249
        if group is None:
250
            for group in self.groups:
251
                self.pretty_print(group)
252
        else:
253
            self.groups[group].pretty_print(recursive=True)