Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / __init__.py @ a71bb904

History | View | Annotate | Download (12.3 kB)

1 d486baec Stavros Sachtouris
# Copyright 2012-2013 GRNET S.A. All rights reserved.
2 7493ccb6 Stavros Sachtouris
#
3 7493ccb6 Stavros Sachtouris
# Redistribution and use in source and binary forms, with or
4 7493ccb6 Stavros Sachtouris
# without modification, are permitted provided that the following
5 7493ccb6 Stavros Sachtouris
# conditions are met:
6 7493ccb6 Stavros Sachtouris
#
7 7493ccb6 Stavros Sachtouris
#   1. Redistributions of source code must retain the above
8 fd5db045 Stavros Sachtouris
#      copyright notice, this list of conditions and the following
9 fd5db045 Stavros Sachtouris
#      disclaimer.
10 7493ccb6 Stavros Sachtouris
#
11 7493ccb6 Stavros Sachtouris
#   2. Redistributions in binary form must reproduce the above
12 fd5db045 Stavros Sachtouris
#      copyright notice, this list of conditions and the following
13 fd5db045 Stavros Sachtouris
#      disclaimer in the documentation and/or other materials
14 fd5db045 Stavros Sachtouris
#      provided with the distribution.
15 7493ccb6 Stavros Sachtouris
#
16 7493ccb6 Stavros Sachtouris
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 7493ccb6 Stavros Sachtouris
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 7493ccb6 Stavros Sachtouris
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 7493ccb6 Stavros Sachtouris
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 7493ccb6 Stavros Sachtouris
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 7493ccb6 Stavros Sachtouris
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 7493ccb6 Stavros Sachtouris
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 7493ccb6 Stavros Sachtouris
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 7493ccb6 Stavros Sachtouris
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 7493ccb6 Stavros Sachtouris
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 7493ccb6 Stavros Sachtouris
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 7493ccb6 Stavros Sachtouris
# POSSIBILITY OF SUCH DAMAGE.
28 7493ccb6 Stavros Sachtouris
#
29 7493ccb6 Stavros Sachtouris
# The views and conclusions contained in the software and
30 7493ccb6 Stavros Sachtouris
# documentation are those of the authors and should not be
31 7493ccb6 Stavros Sachtouris
# interpreted as representing official policies, either expressed
32 d486baec Stavros Sachtouris
# or implied, of GRNET S.A.command
33 7493ccb6 Stavros Sachtouris
34 7493ccb6 Stavros Sachtouris
import logging
35 d486baec Stavros Sachtouris
from sys import argv, exit, stdout
36 f3e94e06 Stavros Sachtouris
from os.path import basename
37 d486baec Stavros Sachtouris
from inspect import getargspec
38 3dabe5d2 Stavros Sachtouris
39 ee4c47d7 Stavros Sachtouris
from kamaki.cli.argument import ArgumentParseManager
40 fd5db045 Stavros Sachtouris
from kamaki.cli.history import History
41 d486baec Stavros Sachtouris
from kamaki.cli.utils import print_dict, print_list, red, magenta, yellow
42 d486baec Stavros Sachtouris
from kamaki.cli.errors import CLIError
43 7493ccb6 Stavros Sachtouris
44 d486baec Stavros Sachtouris
_help = False
45 d486baec Stavros Sachtouris
_debug = False
46 d486baec Stavros Sachtouris
_verbose = False
47 d486baec Stavros Sachtouris
_colors = False
48 aa5c0458 Stavros Sachtouris
kloger = None
49 fd5db045 Stavros Sachtouris
50 b6a99832 Stavros Sachtouris
#  command auxiliary methods
51 b6a99832 Stavros Sachtouris
52 b6a99832 Stavros Sachtouris
_best_match = []
53 b6a99832 Stavros Sachtouris
54 fd5db045 Stavros Sachtouris
55 d486baec Stavros Sachtouris
def _construct_command_syntax(cls):
56 fd5db045 Stavros Sachtouris
        spec = getargspec(cls.main.im_func)
57 fd5db045 Stavros Sachtouris
        args = spec.args[1:]
58 fd5db045 Stavros Sachtouris
        n = len(args) - len(spec.defaults or ())
59 fd5db045 Stavros Sachtouris
        required = ' '.join('<%s>' % x\
60 fd5db045 Stavros Sachtouris
            .replace('____', '[:')\
61 fd5db045 Stavros Sachtouris
            .replace('___', ':')\
62 fd5db045 Stavros Sachtouris
            .replace('__', ']').\
63 fd5db045 Stavros Sachtouris
            replace('_', ' ') for x in args[:n])
64 fd5db045 Stavros Sachtouris
        optional = ' '.join('[%s]' % x\
65 fd5db045 Stavros Sachtouris
            .replace('____', '[:')\
66 fd5db045 Stavros Sachtouris
            .replace('___', ':')\
67 fd5db045 Stavros Sachtouris
            .replace('__', ']').\
68 fd5db045 Stavros Sachtouris
            replace('_', ' ') for x in args[n:])
69 fd5db045 Stavros Sachtouris
        cls.syntax = ' '.join(x for x in [required, optional] if x)
70 fd5db045 Stavros Sachtouris
        if spec.varargs:
71 fd5db045 Stavros Sachtouris
            cls.syntax += ' <%s ...>' % spec.varargs
72 fd5db045 Stavros Sachtouris
73 fd5db045 Stavros Sachtouris
74 d486baec Stavros Sachtouris
def _num_of_matching_terms(basic_list, attack_list):
75 d486baec Stavros Sachtouris
    if not attack_list:
76 75c3fc42 Stavros Sachtouris
        return len(basic_list)
77 fd5db045 Stavros Sachtouris
78 d486baec Stavros Sachtouris
    matching_terms = 0
79 d486baec Stavros Sachtouris
    for i, term in enumerate(basic_list):
80 d486baec Stavros Sachtouris
        try:
81 d486baec Stavros Sachtouris
            if term != attack_list[i]:
82 d486baec Stavros Sachtouris
                break
83 d486baec Stavros Sachtouris
        except IndexError:
84 d486baec Stavros Sachtouris
            break
85 d486baec Stavros Sachtouris
        matching_terms += 1
86 d486baec Stavros Sachtouris
    return matching_terms
87 dfee2caf Stavros Sachtouris
88 fd5db045 Stavros Sachtouris
89 d486baec Stavros Sachtouris
def _update_best_match(name_terms, prefix=[]):
90 d486baec Stavros Sachtouris
    if prefix:
91 d486baec Stavros Sachtouris
        pref_list = prefix if isinstance(prefix, list) else prefix.split('_')
92 d486baec Stavros Sachtouris
    else:
93 d486baec Stavros Sachtouris
        pref_list = []
94 dfee2caf Stavros Sachtouris
95 d486baec Stavros Sachtouris
    num_of_matching_terms = _num_of_matching_terms(name_terms, pref_list)
96 d486baec Stavros Sachtouris
    global _best_match
97 e9533b0c Stavros Sachtouris
    if not prefix:
98 e9533b0c Stavros Sachtouris
        _best_match = []
99 fd5db045 Stavros Sachtouris
100 d486baec Stavros Sachtouris
    if num_of_matching_terms and len(_best_match) <= num_of_matching_terms:
101 d486baec Stavros Sachtouris
        if len(_best_match) < num_of_matching_terms:
102 d486baec Stavros Sachtouris
            _best_match = name_terms[:num_of_matching_terms]
103 d486baec Stavros Sachtouris
        return True
104 d486baec Stavros Sachtouris
    return False
105 d486baec Stavros Sachtouris
106 d486baec Stavros Sachtouris
107 d486baec Stavros Sachtouris
def command(cmd_tree, prefix='', descedants_depth=1):
108 d486baec Stavros Sachtouris
    """Load a class as a command
109 451a7992 Stavros Sachtouris
        e.g. spec_cmd0_cmd1 will be command spec cmd0
110 451a7992 Stavros Sachtouris

111 451a7992 Stavros Sachtouris
        :param cmd_tree: is initialized in cmd_spec file and is the structure
112 d486baec Stavros Sachtouris
            where commands are loaded. Var name should be _commands
113 451a7992 Stavros Sachtouris
        :param prefix: if given, load only commands prefixed with prefix,
114 451a7992 Stavros Sachtouris
        :param descedants_depth: is the depth of the tree descedants of the
115 d486baec Stavros Sachtouris
            prefix command. It is used ONLY if prefix and if prefix is not
116 d486baec Stavros Sachtouris
            a terminal command
117 451a7992 Stavros Sachtouris

118 451a7992 Stavros Sachtouris
        :returns: the specified class object
119 d486baec Stavros Sachtouris
    """
120 d486baec Stavros Sachtouris
121 d486baec Stavros Sachtouris
    def wrap(cls):
122 451a7992 Stavros Sachtouris
        global kloger
123 d486baec Stavros Sachtouris
        cls_name = cls.__name__
124 d486baec Stavros Sachtouris
125 d486baec Stavros Sachtouris
        if not cmd_tree:
126 d486baec Stavros Sachtouris
            if _debug:
127 451a7992 Stavros Sachtouris
                kloger.warning('command %s found but not loaded' % cls_name)
128 d486baec Stavros Sachtouris
            return cls
129 0b368c8c Stavros Sachtouris
130 d486baec Stavros Sachtouris
        name_terms = cls_name.split('_')
131 d486baec Stavros Sachtouris
        if not _update_best_match(name_terms, prefix):
132 e9533b0c Stavros Sachtouris
            if _debug:
133 451a7992 Stavros Sachtouris
                kloger.warning('%s failed to update_best_match' % cls_name)
134 d486baec Stavros Sachtouris
            return None
135 fd5db045 Stavros Sachtouris
136 d486baec Stavros Sachtouris
        global _best_match
137 d486baec Stavros Sachtouris
        max_len = len(_best_match) + descedants_depth
138 d486baec Stavros Sachtouris
        if len(name_terms) > max_len:
139 d486baec Stavros Sachtouris
            partial = '_'.join(name_terms[:max_len])
140 d486baec Stavros Sachtouris
            if not cmd_tree.has_command(partial):  # add partial path
141 d486baec Stavros Sachtouris
                cmd_tree.add_command(partial)
142 e9533b0c Stavros Sachtouris
            if _debug:
143 451a7992 Stavros Sachtouris
                kloger.warning('%s failed max_len test' % cls_name)
144 d486baec Stavros Sachtouris
            return None
145 fd5db045 Stavros Sachtouris
146 d486baec Stavros Sachtouris
        cls.description, sep, cls.long_description\
147 d486baec Stavros Sachtouris
        = cls.__doc__.partition('\n')
148 d486baec Stavros Sachtouris
        _construct_command_syntax(cls)
149 0b368c8c Stavros Sachtouris
150 d486baec Stavros Sachtouris
        cmd_tree.add_command(cls_name, cls.description, cls)
151 d486baec Stavros Sachtouris
        return cls
152 d486baec Stavros Sachtouris
    return wrap
153 fd5db045 Stavros Sachtouris
154 0b368c8c Stavros Sachtouris
155 d486baec Stavros Sachtouris
cmd_spec_locations = [
156 d486baec Stavros Sachtouris
    'kamaki.cli.commands',
157 d486baec Stavros Sachtouris
    'kamaki.commands',
158 d486baec Stavros Sachtouris
    'kamaki.cli',
159 d486baec Stavros Sachtouris
    'kamaki',
160 d486baec Stavros Sachtouris
    '']
161 fd5db045 Stavros Sachtouris
162 0b368c8c Stavros Sachtouris
163 b6a99832 Stavros Sachtouris
#  Generic init auxiliary functions
164 b6a99832 Stavros Sachtouris
165 b6a99832 Stavros Sachtouris
166 d486baec Stavros Sachtouris
def _setup_logging(silent=False, debug=False, verbose=False, include=False):
167 fd5db045 Stavros Sachtouris
    """handle logging for clients package"""
168 fd5db045 Stavros Sachtouris
169 fd5db045 Stavros Sachtouris
    def add_handler(name, level, prefix=''):
170 fd5db045 Stavros Sachtouris
        h = logging.StreamHandler()
171 fd5db045 Stavros Sachtouris
        fmt = logging.Formatter(prefix + '%(message)s')
172 fd5db045 Stavros Sachtouris
        h.setFormatter(fmt)
173 fd5db045 Stavros Sachtouris
        logger = logging.getLogger(name)
174 fd5db045 Stavros Sachtouris
        logger.addHandler(h)
175 fd5db045 Stavros Sachtouris
        logger.setLevel(level)
176 fd5db045 Stavros Sachtouris
177 fd5db045 Stavros Sachtouris
    if silent:
178 fd5db045 Stavros Sachtouris
        add_handler('', logging.CRITICAL)
179 db8d1766 Stavros Sachtouris
        return
180 db8d1766 Stavros Sachtouris
181 db8d1766 Stavros Sachtouris
    if debug:
182 fd5db045 Stavros Sachtouris
        add_handler('requests', logging.INFO, prefix='* ')
183 fd5db045 Stavros Sachtouris
        add_handler('clients.send', logging.DEBUG, prefix='> ')
184 fd5db045 Stavros Sachtouris
        add_handler('clients.recv', logging.DEBUG, prefix='< ')
185 b6a99832 Stavros Sachtouris
        add_handler('kamaki', logging.DEBUG, prefix='(debug): ')
186 fd5db045 Stavros Sachtouris
    elif verbose:
187 fd5db045 Stavros Sachtouris
        add_handler('requests', logging.INFO, prefix='* ')
188 fd5db045 Stavros Sachtouris
        add_handler('clients.send', logging.INFO, prefix='> ')
189 fd5db045 Stavros Sachtouris
        add_handler('clients.recv', logging.INFO, prefix='< ')
190 b6a99832 Stavros Sachtouris
        add_handler('kamaki', logging.INFO, prefix='(i): ')
191 fd5db045 Stavros Sachtouris
    elif include:
192 fd5db045 Stavros Sachtouris
        add_handler('clients.recv', logging.INFO)
193 b6a99832 Stavros Sachtouris
    add_handler('kamaki', logging.WARNING, prefix='(warning): ')
194 aa5c0458 Stavros Sachtouris
    global kloger
195 b6a99832 Stavros Sachtouris
    kloger = logging.getLogger('kamaki')
196 fd5db045 Stavros Sachtouris
197 ce48608f Stavros Sachtouris
198 d486baec Stavros Sachtouris
def _init_session(arguments):
199 d486baec Stavros Sachtouris
    global _help
200 d486baec Stavros Sachtouris
    _help = arguments['help'].value
201 d486baec Stavros Sachtouris
    global _debug
202 d486baec Stavros Sachtouris
    _debug = arguments['debug'].value
203 d486baec Stavros Sachtouris
    global _verbose
204 d486baec Stavros Sachtouris
    _verbose = arguments['verbose'].value
205 d486baec Stavros Sachtouris
    global _colors
206 d486baec Stavros Sachtouris
    _colors = arguments['config'].get('global', 'colors')
207 87565d2c Stavros Sachtouris
    if not (stdout.isatty() and _colors == 'on'):
208 4f6a21f6 Stavros Sachtouris
        from kamaki.cli.utils import remove_colors
209 4f6a21f6 Stavros Sachtouris
        remove_colors()
210 d486baec Stavros Sachtouris
    _silent = arguments['silent'].value
211 d486baec Stavros Sachtouris
    _include = arguments['include'].value
212 d486baec Stavros Sachtouris
    _setup_logging(_silent, _debug, _verbose, _include)
213 d486baec Stavros Sachtouris
214 d486baec Stavros Sachtouris
215 d486baec Stavros Sachtouris
def _load_spec_module(spec, arguments, module):
216 d486baec Stavros Sachtouris
    spec_name = arguments['config'].get(spec, 'cli')
217 d486baec Stavros Sachtouris
    if spec_name is None:
218 d486baec Stavros Sachtouris
        return None
219 d486baec Stavros Sachtouris
    pkg = None
220 d486baec Stavros Sachtouris
    for location in cmd_spec_locations:
221 d486baec Stavros Sachtouris
        location += spec_name if location == '' else '.%s' % spec_name
222 d486baec Stavros Sachtouris
        try:
223 d486baec Stavros Sachtouris
            pkg = __import__(location, fromlist=[module])
224 d486baec Stavros Sachtouris
            return pkg
225 d486baec Stavros Sachtouris
        except ImportError:
226 d486baec Stavros Sachtouris
            continue
227 d486baec Stavros Sachtouris
    return pkg
228 d486baec Stavros Sachtouris
229 d486baec Stavros Sachtouris
230 d486baec Stavros Sachtouris
def _groups_help(arguments):
231 d486baec Stavros Sachtouris
    global _debug
232 aa5c0458 Stavros Sachtouris
    global kloger
233 d486baec Stavros Sachtouris
    descriptions = {}
234 d486baec Stavros Sachtouris
    for spec in arguments['config'].get_groups():
235 d486baec Stavros Sachtouris
        pkg = _load_spec_module(spec, arguments, '_commands')
236 d486baec Stavros Sachtouris
        if pkg:
237 d486baec Stavros Sachtouris
            cmds = None
238 d486baec Stavros Sachtouris
            try:
239 d486baec Stavros Sachtouris
                cmds = [
240 d486baec Stavros Sachtouris
                    cmd for cmd in getattr(pkg, '_commands')\
241 d486baec Stavros Sachtouris
                    if arguments['config'].get(cmd.name, 'cli')
242 d486baec Stavros Sachtouris
                ]
243 d486baec Stavros Sachtouris
            except AttributeError:
244 d486baec Stavros Sachtouris
                if _debug:
245 aa5c0458 Stavros Sachtouris
                    kloger.warning('No description for %s' % spec)
246 d486baec Stavros Sachtouris
            try:
247 d486baec Stavros Sachtouris
                for cmd in cmds:
248 d486baec Stavros Sachtouris
                    descriptions[cmd.name] = cmd.description
249 d486baec Stavros Sachtouris
            except TypeError:
250 d486baec Stavros Sachtouris
                if _debug:
251 aa5c0458 Stavros Sachtouris
                    kloger.warning('no cmd specs in module %s' % spec)
252 d486baec Stavros Sachtouris
        elif _debug:
253 aa5c0458 Stavros Sachtouris
            kloger.warning('Loading of %s cmd spec failed' % spec)
254 d486baec Stavros Sachtouris
    print('\nOptions:\n - - - -')
255 d486baec Stavros Sachtouris
    print_dict(descriptions)
256 d486baec Stavros Sachtouris
257 d486baec Stavros Sachtouris
258 b6a99832 Stavros Sachtouris
def _load_all_commands(cmd_tree, arguments):
259 b6a99832 Stavros Sachtouris
    _config = arguments['config']
260 b6a99832 Stavros Sachtouris
    for spec in [spec for spec in _config.get_groups()\
261 b6a99832 Stavros Sachtouris
            if _config.get(spec, 'cli')]:
262 b6a99832 Stavros Sachtouris
        try:
263 b6a99832 Stavros Sachtouris
            spec_module = _load_spec_module(spec, arguments, '_commands')
264 b6a99832 Stavros Sachtouris
            spec_commands = getattr(spec_module, '_commands')
265 b6a99832 Stavros Sachtouris
        except AttributeError:
266 b6a99832 Stavros Sachtouris
            if _debug:
267 b6a99832 Stavros Sachtouris
                global kloger
268 b6a99832 Stavros Sachtouris
                kloger.warning('No valid description for %s' % spec)
269 b6a99832 Stavros Sachtouris
            continue
270 b6a99832 Stavros Sachtouris
        for spec_tree in spec_commands:
271 b6a99832 Stavros Sachtouris
            if spec_tree.name == spec:
272 b6a99832 Stavros Sachtouris
                cmd_tree.add_tree(spec_tree)
273 b6a99832 Stavros Sachtouris
                break
274 b6a99832 Stavros Sachtouris
275 b6a99832 Stavros Sachtouris
276 b6a99832 Stavros Sachtouris
#  Methods to be used by CLI implementations
277 b6a99832 Stavros Sachtouris
278 b6a99832 Stavros Sachtouris
279 b6a99832 Stavros Sachtouris
def print_subcommands_help(cmd):
280 d486baec Stavros Sachtouris
    printout = {}
281 d486baec Stavros Sachtouris
    for subcmd in cmd.get_subcommands():
282 4f6a21f6 Stavros Sachtouris
        spec, sep, print_path = subcmd.path.partition('_')
283 4f6a21f6 Stavros Sachtouris
        printout[print_path.replace('_', ' ')] = subcmd.description
284 d486baec Stavros Sachtouris
    if printout:
285 d486baec Stavros Sachtouris
        print('\nOptions:\n - - - -')
286 d486baec Stavros Sachtouris
        print_dict(printout)
287 d486baec Stavros Sachtouris
288 d486baec Stavros Sachtouris
289 b6a99832 Stavros Sachtouris
def update_parser_help(parser, cmd):
290 d486baec Stavros Sachtouris
    global _best_match
291 7c2247a0 Stavros Sachtouris
    parser.syntax = parser.syntax.split('<')[0]
292 7c2247a0 Stavros Sachtouris
    parser.syntax += ' '.join(_best_match)
293 d486baec Stavros Sachtouris
294 a71bb904 Stavros Sachtouris
    description = ''
295 d486baec Stavros Sachtouris
    if cmd.is_command:
296 d486baec Stavros Sachtouris
        cls = cmd.get_class()
297 7c2247a0 Stavros Sachtouris
        parser.syntax += ' ' + cls.syntax
298 7c2247a0 Stavros Sachtouris
        parser.update_arguments(cls().arguments)
299 a71bb904 Stavros Sachtouris
        description = getattr(cls, 'long_description', '')
300 a71bb904 Stavros Sachtouris
        description = description.strip()
301 d486baec Stavros Sachtouris
    else:
302 7c2247a0 Stavros Sachtouris
        parser.syntax += ' <...>'
303 d486baec Stavros Sachtouris
    if cmd.has_description:
304 a71bb904 Stavros Sachtouris
        parser.parser.description = cmd.help\
305 a71bb904 Stavros Sachtouris
        + ((' . . . %s' % description) if description else '')
306 d486baec Stavros Sachtouris
307 d486baec Stavros Sachtouris
308 b6a99832 Stavros Sachtouris
def print_error_message(cli_err):
309 d486baec Stavros Sachtouris
    errmsg = '%s' % cli_err
310 d486baec Stavros Sachtouris
    if cli_err.importance == 1:
311 d486baec Stavros Sachtouris
        errmsg = magenta(errmsg)
312 d486baec Stavros Sachtouris
    elif cli_err.importance == 2:
313 d486baec Stavros Sachtouris
        errmsg = yellow(errmsg)
314 d486baec Stavros Sachtouris
    elif cli_err.importance > 2:
315 d486baec Stavros Sachtouris
        errmsg = red(errmsg)
316 d486baec Stavros Sachtouris
    stdout.write(errmsg)
317 d486baec Stavros Sachtouris
    print_list(cli_err.details)
318 d486baec Stavros Sachtouris
319 d486baec Stavros Sachtouris
320 b6a99832 Stavros Sachtouris
def exec_cmd(instance, cmd_args, help_method):
321 fd5db045 Stavros Sachtouris
    try:
322 fd5db045 Stavros Sachtouris
        return instance.main(*cmd_args)
323 fd5db045 Stavros Sachtouris
    except TypeError as err:
324 fd5db045 Stavros Sachtouris
        if err.args and err.args[0].startswith('main()'):
325 fd5db045 Stavros Sachtouris
            print(magenta('Syntax error'))
326 d486baec Stavros Sachtouris
            if _debug:
327 d486baec Stavros Sachtouris
                raise err
328 d486baec Stavros Sachtouris
            if _verbose:
329 fd5db045 Stavros Sachtouris
                print(unicode(err))
330 fd5db045 Stavros Sachtouris
            help_method()
331 fd5db045 Stavros Sachtouris
        else:
332 fd5db045 Stavros Sachtouris
            raise
333 fd5db045 Stavros Sachtouris
    return 1
334 fd5db045 Stavros Sachtouris
335 f247bcb4 Stavros Sachtouris
336 b6a99832 Stavros Sachtouris
def get_command_group(unparsed, arguments):
337 b6a99832 Stavros Sachtouris
    groups = arguments['config'].get_groups()
338 b6a99832 Stavros Sachtouris
    for term in unparsed:
339 b6a99832 Stavros Sachtouris
        if term.startswith('-'):
340 b6a99832 Stavros Sachtouris
            continue
341 b6a99832 Stavros Sachtouris
        if term in groups:
342 b6a99832 Stavros Sachtouris
            unparsed.remove(term)
343 b6a99832 Stavros Sachtouris
            return term
344 b6a99832 Stavros Sachtouris
        return None
345 b6a99832 Stavros Sachtouris
    return None
346 b6a99832 Stavros Sachtouris
347 b6a99832 Stavros Sachtouris
348 7c2247a0 Stavros Sachtouris
def set_command_params(parameters):
349 7c2247a0 Stavros Sachtouris
    """Add a parameters list to a command
350 7c2247a0 Stavros Sachtouris

351 7c2247a0 Stavros Sachtouris
    :param paramters: (list of str) a list of parameters
352 7c2247a0 Stavros Sachtouris
    """
353 d486baec Stavros Sachtouris
    global command
354 d486baec Stavros Sachtouris
    def_params = list(command.func_defaults)
355 7c2247a0 Stavros Sachtouris
    def_params[0] = parameters
356 d486baec Stavros Sachtouris
    command.func_defaults = tuple(def_params)
357 d486baec Stavros Sachtouris
358 d486baec Stavros Sachtouris
359 b6a99832 Stavros Sachtouris
#  CLI Choice:
360 d486baec Stavros Sachtouris
361 b6a99832 Stavros Sachtouris
def run_one_cmd(exe_string, parser):
362 b6a99832 Stavros Sachtouris
    global _history
363 b6a99832 Stavros Sachtouris
    _history = History(
364 b6a99832 Stavros Sachtouris
        parser.arguments['config'].get('history', 'file'))
365 b6a99832 Stavros Sachtouris
    _history.add(' '.join([exe_string] + argv[1:]))
366 b6a99832 Stavros Sachtouris
    from kamaki.cli import one_command
367 b6a99832 Stavros Sachtouris
    one_command.run(parser, _help)
368 d53062bd Stavros Sachtouris
369 d53062bd Stavros Sachtouris
370 074f5027 Stavros Sachtouris
def run_shell(exe_string, parser):
371 d53062bd Stavros Sachtouris
    from command_shell import _init_shell
372 074f5027 Stavros Sachtouris
    shell = _init_shell(exe_string, parser)
373 074f5027 Stavros Sachtouris
    _load_all_commands(shell.cmd_tree, parser.arguments)
374 074f5027 Stavros Sachtouris
    shell.run(parser)
375 fd5db045 Stavros Sachtouris
376 1c1fd2fa Stavros Sachtouris
377 1c1fd2fa Stavros Sachtouris
def main():
378 71882bca Stavros Sachtouris
    try:
379 71882bca Stavros Sachtouris
        exe = basename(argv[0])
380 e0da0f90 Stavros Sachtouris
        parser = ArgumentParseManager(exe)
381 7c2247a0 Stavros Sachtouris
382 074f5027 Stavros Sachtouris
        if parser.arguments['version'].value:
383 71882bca Stavros Sachtouris
            exit(0)
384 71882bca Stavros Sachtouris
385 074f5027 Stavros Sachtouris
        _init_session(parser.arguments)
386 71882bca Stavros Sachtouris
387 b3dd8f4b Stavros Sachtouris
        if parser.unparsed:
388 b6a99832 Stavros Sachtouris
            run_one_cmd(exe, parser)
389 71882bca Stavros Sachtouris
        elif _help:
390 e0da0f90 Stavros Sachtouris
            parser.parser.print_help()
391 074f5027 Stavros Sachtouris
            _groups_help(parser.arguments)
392 71882bca Stavros Sachtouris
        else:
393 074f5027 Stavros Sachtouris
            run_shell(exe, parser)
394 71882bca Stavros Sachtouris
    except CLIError as err:
395 b6a99832 Stavros Sachtouris
        print_error_message(err)
396 71882bca Stavros Sachtouris
        if _debug:
397 71882bca Stavros Sachtouris
            raise err
398 71882bca Stavros Sachtouris
        exit(1)
399 6069b53b Stavros Sachtouris
    except Exception as er:
400 6069b53b Stavros Sachtouris
        print('Unknown Error: %s' % er)
401 71882bca Stavros Sachtouris
        if _debug:
402 6069b53b Stavros Sachtouris
            raise
403 6069b53b Stavros Sachtouris
        exit(1)