Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / command_tree / __init__.py @ 2fde8651

History | View | Annotate | Download (7.8 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

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

    
43
    def __init__(self, path, help=' ', subcommands={}, cmd_class=None):
44
        assert path, 'Cannot initialize a command without a command path'
45
        self.path = path
46
        self.help = help or ''
47
        self.subcommands = dict(subcommands) if subcommands else {}
48
        self.cmd_class = cmd_class or None
49

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
127

    
128
class CommandTree(object):
129

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

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

    
139
    def exclude(self, groups_to_exclude=[]):
140
        for group in groups_to_exclude:
141
            self.groups.pop(group, None)
142

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

    
166
    def find_best_match(self, terms):
167
        """Find a command that best matches a given list of terms
168

169
        :param terms: (list of str) match them against paths in cmd_tree
170

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

    
183
    def add_tree(self, new_tree):
184
        tname = new_tree.name
185
        tdesc = new_tree.description
186
        self.groups.update(new_tree.groups)
187
        self._all_commands.update(new_tree._all_commands)
188
        self.set_description(tname, tdesc)
189

    
190
    def has_command(self, path):
191
        return path in self._all_commands
192

    
193
    def get_command(self, path):
194
        return self._all_commands[path]
195

    
196
    def get_groups(self):
197
        return self.groups.values()
198

    
199
    def get_group_names(self):
200
        return self.groups.keys()
201

    
202
    def set_description(self, path, description):
203
        self._all_commands[path].help = description
204

    
205
    def get_description(self, path):
206
        return self._all_commands[path].help
207

    
208
    def set_class(self, path, cmd_class):
209
        self._all_commands[path].set_class(cmd_class)
210

    
211
    def get_class(self, path):
212
        return self._all_commands[path].get_class()
213

    
214
    def get_subnames(self, path=None):
215
        if path in (None, ''):
216
            return self.get_group_names()
217
        return self._all_commands[path].get_subnames()
218

    
219
    def get_subcommands(self, path=None):
220
        if path in (None, ''):
221
            return self.get_groups()
222
        return self._all_commands[path].get_subcommands()
223

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

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

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

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