Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / __init__.py @ 9986e569

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 af569ab9 Stavros Sachtouris
from kamaki.cli.utils import print_dict, red, magenta, yellow
42 d486baec Stavros Sachtouris
from kamaki.cli.errors import CLIError
43 9986e569 Stavros Sachtouris
from kamaki.logger import add_stream_logger, get_logger
44 7493ccb6 Stavros Sachtouris
45 d486baec Stavros Sachtouris
_help = False
46 d486baec Stavros Sachtouris
_debug = False
47 1a3c18fd Stavros Sachtouris
_include = False
48 d486baec Stavros Sachtouris
_verbose = False
49 d486baec Stavros Sachtouris
_colors = False
50 aa5c0458 Stavros Sachtouris
kloger = None
51 fd5db045 Stavros Sachtouris
52 b6a99832 Stavros Sachtouris
#  command auxiliary methods
53 b6a99832 Stavros Sachtouris
54 b6a99832 Stavros Sachtouris
_best_match = []
55 b6a99832 Stavros Sachtouris
56 fd5db045 Stavros Sachtouris
57 24ff0a35 Stavros Sachtouris
def _arg2syntax(arg):
58 24ff0a35 Stavros Sachtouris
    return arg.replace(
59 24ff0a35 Stavros Sachtouris
        '____', '[:').replace(
60 2005b18e Stavros Sachtouris
            '___', ':').replace(
61 2005b18e Stavros Sachtouris
                '__', ']').replace(
62 2005b18e Stavros Sachtouris
                    '_', ' ')
63 24ff0a35 Stavros Sachtouris
64 24ff0a35 Stavros Sachtouris
65 d486baec Stavros Sachtouris
def _construct_command_syntax(cls):
66 fd5db045 Stavros Sachtouris
        spec = getargspec(cls.main.im_func)
67 fd5db045 Stavros Sachtouris
        args = spec.args[1:]
68 fd5db045 Stavros Sachtouris
        n = len(args) - len(spec.defaults or ())
69 24ff0a35 Stavros Sachtouris
        required = ' '.join(['<%s>' % _arg2syntax(x) for x in args[:n]])
70 24ff0a35 Stavros Sachtouris
        optional = ' '.join(['[%s]' % _arg2syntax(x) for x in args[n:]])
71 fd5db045 Stavros Sachtouris
        cls.syntax = ' '.join(x for x in [required, optional] if x)
72 fd5db045 Stavros Sachtouris
        if spec.varargs:
73 fd5db045 Stavros Sachtouris
            cls.syntax += ' <%s ...>' % spec.varargs
74 fd5db045 Stavros Sachtouris
75 fd5db045 Stavros Sachtouris
76 d486baec Stavros Sachtouris
def _num_of_matching_terms(basic_list, attack_list):
77 d486baec Stavros Sachtouris
    if not attack_list:
78 75c3fc42 Stavros Sachtouris
        return len(basic_list)
79 fd5db045 Stavros Sachtouris
80 d486baec Stavros Sachtouris
    matching_terms = 0
81 d486baec Stavros Sachtouris
    for i, term in enumerate(basic_list):
82 d486baec Stavros Sachtouris
        try:
83 d486baec Stavros Sachtouris
            if term != attack_list[i]:
84 d486baec Stavros Sachtouris
                break
85 d486baec Stavros Sachtouris
        except IndexError:
86 d486baec Stavros Sachtouris
            break
87 d486baec Stavros Sachtouris
        matching_terms += 1
88 d486baec Stavros Sachtouris
    return matching_terms
89 dfee2caf Stavros Sachtouris
90 fd5db045 Stavros Sachtouris
91 d486baec Stavros Sachtouris
def _update_best_match(name_terms, prefix=[]):
92 d486baec Stavros Sachtouris
    if prefix:
93 d486baec Stavros Sachtouris
        pref_list = prefix if isinstance(prefix, list) else prefix.split('_')
94 d486baec Stavros Sachtouris
    else:
95 d486baec Stavros Sachtouris
        pref_list = []
96 dfee2caf Stavros Sachtouris
97 d486baec Stavros Sachtouris
    num_of_matching_terms = _num_of_matching_terms(name_terms, pref_list)
98 d486baec Stavros Sachtouris
    global _best_match
99 e9533b0c Stavros Sachtouris
    if not prefix:
100 e9533b0c Stavros Sachtouris
        _best_match = []
101 fd5db045 Stavros Sachtouris
102 d486baec Stavros Sachtouris
    if num_of_matching_terms and len(_best_match) <= num_of_matching_terms:
103 d486baec Stavros Sachtouris
        if len(_best_match) < num_of_matching_terms:
104 d486baec Stavros Sachtouris
            _best_match = name_terms[:num_of_matching_terms]
105 d486baec Stavros Sachtouris
        return True
106 d486baec Stavros Sachtouris
    return False
107 d486baec Stavros Sachtouris
108 d486baec Stavros Sachtouris
109 d486baec Stavros Sachtouris
def command(cmd_tree, prefix='', descedants_depth=1):
110 d486baec Stavros Sachtouris
    """Load a class as a command
111 451a7992 Stavros Sachtouris
        e.g. spec_cmd0_cmd1 will be command spec cmd0
112 451a7992 Stavros Sachtouris

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

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

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