Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / command_tree / __init__.py @ d252a7a8

History | View | Annotate | Download (6.3 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 len(self.subcommands) == 0 if self.cmd_class else False
75

    
76
    @property
77
    def parent_path(self):
78
        try:
79
            return self.path[:self.path.rindex('_')]
80
        except ValueError:
81
            return ''
82

    
83
    def parse_out(self, args):
84
        """Find the deepest subcommand matching a series of terms
85
        but stop the first time a term doesn't match
86

87
        :param args: (list) terms to match commands against
88

89
        :returns: (parsed out command, the rest of the arguments)
90

91
        :raises TypeError: if args is not inalterable
92
        """
93
        cmd = self
94
        index = 0
95
        for term in args:
96
            try:
97
                cmd = cmd.subcommands[term]
98
            except KeyError:
99
                break
100
            index += 1
101
        return cmd, args[index:]
102

    
103
    def pretty_print(self, recursive=False):
104
        print('%s\t\t(Name: %s is_cmd: %s help: %s)' % (
105
            self.path, self.name, self.is_command, self.help))
106
        for cmd in self.subcommands.values():
107
            cmd.pretty_print(recursive)
108

    
109

    
110
class CommandTree(object):
111

    
112
    def __init__(self, name, description=''):
113
        self.name = name
114
        self.description = description
115
        self.groups = dict()
116
        self._all_commands = dict()
117

    
118
    def exclude(self, groups_to_exclude=[]):
119
        for group in groups_to_exclude:
120
            self.groups.pop(group, None)
121

    
122
    def add_command(self, command_path, description=None, cmd_class=None):
123
        terms = command_path.split('_')
124
        try:
125
            cmd = self.groups[terms[0]]
126
        except KeyError:
127
            cmd = Command(terms[0])
128
            self.groups[terms[0]] = cmd
129
            self._all_commands[terms[0]] = cmd
130
        path = terms[0]
131
        for term in terms[1:]:
132
            path += '_' + term
133
            try:
134
                cmd = cmd.subcommands[term]
135
            except KeyError:
136
                new_cmd = Command(path)
137
                self._all_commands[path] = new_cmd
138
                cmd.add_subcmd(new_cmd)
139
                cmd = new_cmd
140
        cmd.cmd_class = cmd_class or None
141
        cmd.help = description or None
142

    
143
    def find_best_match(self, terms):
144
        """Find a command that best matches a given list of terms
145

146
        :param terms: (list of str) match against paths in cmd_tree, e.g.
147
            ['aa', 'bb', 'cc'] matches aa_bb_cc
148

149
        :returns: (Command, list) the matching command, the remaining terms or
150
            None
151
        """
152
        path = []
153
        for term in terms:
154
            check_path = path + [term]
155
            if '_'.join(check_path) not in self._all_commands:
156
                break
157
            path = check_path
158
        if path:
159
            return (self._all_commands['_'.join(path)], terms[len(path):])
160
        return (None, terms)
161

    
162
    def add_tree(self, new_tree):
163
        tname = new_tree.name
164
        tdesc = new_tree.description
165
        self.groups.update(new_tree.groups)
166
        self._all_commands.update(new_tree._all_commands)
167
        try:
168
            self._all_commands[tname].help = tdesc
169
        except KeyError:
170
            self.add_command(tname, tdesc)
171

    
172
    def has_command(self, path):
173
        return path in self._all_commands
174

    
175
    def get_command(self, path):
176
        return self._all_commands[path]
177

    
178
    def subnames(self, path=None):
179
        if path in (None, ''):
180
            return self.groups.keys()
181
        return self._all_commands[path].subcommands.keys()
182

    
183
    def get_subcommands(self, path=None):
184
        return self._all_commands[path].subcommands.values() if (
185
            path) else self.groups.values()
186

    
187
    def pretty_print(self, group=None):
188
        if group is None:
189
            for group in self.groups:
190
                self.pretty_print(group)
191
        else:
192
            self.groups[group].pretty_print(recursive=True)