__init__.py 5.36 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python

# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

from __future__ import print_function

import gevent.monkey
#Monkey-patch everything for gevent early on
gevent.monkey.patch_all()

import logging

44
from inspect import getargspec
45
46
47
from argparse import ArgumentParser
from base64 import b64encode
from os.path import abspath, basename, exists
48
from sys import exit, stdout, stderr, argv
49
50
51
52
53
54

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

55
#from kamaki import clients
56
from .errors import CLIError, CLISyntaxError, CLICmdIncompleteError
57
from .config import Config #TO BE REMOVED
58
from .utils import bold, magenta, red, yellow, CommandTree, print_list
59
from argument import _arguments, parse_known_args
60

61
_commands = CommandTree()
62

63
#basic command groups
64

65
66
def command():
    """Class decorator that registers a class as a CLI command"""
67
68

    def decorator(cls):
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        """Any class with name of the form cmd1_cmd2_cmd3_... is accepted"""
        cls.description, sep, cls.long_description = cls.__doc__.partition('\n')

        # Generate a syntax string based on main's arguments
        spec = getargspec(cls.main.im_func)
        args = spec.args[1:]
        n = len(args) - len(spec.defaults or ())
        required = ' '.join('<%s>' % x.replace('____', '[:').replace('___', ':').replace('__',']').\
            replace('_', ' ') for x in args[:n])
        optional = ' '.join('[%s]' % x.replace('____', '[:').replace('___', ':').replace('__', ']').\
            replace('_', ' ') for x in args[n:])
        cls.syntax = ' '.join(x for x in [required, optional] if x)
        if spec.varargs:
            cls.syntax += ' <%s ...>' % spec.varargs

        _commands.add(cls.__name__, cls)
85
86
87
88
89
90
91
92
        return cls
    return decorator

def set_api_description(api, description):
    """Method to be called by api CLIs
    Each CLI can set more than one api descriptions"""
    GROUPS[api] = description

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def _init_parser(exe):
    parser = ArgumentParser(add_help=True)
    parser.prog='%s <cmd_group> [<cmd_subbroup> ...] <cmd>'%exe
    for name, argument in _arguments.items():
        argument.update_parser(parser, name)
    return parser

def _print_error_message(cli_err):
    errmsg = '%s'%unicode(cli_err) +' (%s)'%cli_err.status if cli_err.status else ' '
    if cli_err.importance == 1:
        errmsg = magenta(errmsg)
    elif cli_err.importance == 2:
        errmsg = yellow(errmsg)
    elif cli_err.importance > 2:
        errmsg = red(errmsg)
    stdout.write(errmsg)
    if cli_err.details is not None and len(cli_err.details) > 0:
        print(': %s'%cli_err.details)
    else:
        print

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def _expand_cmd(cmd_prefix, unparsed):
    if len(unparsed) == 0:
        return None
    prefix = (cmd_prefix+'_') if len(cmd_prefix) > 0 else ''
    for term in _commands.list(cmd_prefix):
        try:
            unparsed.remove(term)
        except ValueError:
            continue
        return prefix+term
    return None

def _retrieve_cmd(unparsed):
    cmd_str = None
    cur_cmd = _expand_cmd('', unparsed)
    while cur_cmd is not None:
        cmd_str = cur_cmd
        cur_cmd = _expand_cmd(cur_cmd, unparsed)
    if cmd_str is None:
        print(bold('Command groups:'))
        print_list(_commands.get_groups(), ident=14)
        print
        return None
    try:
        return _commands.get_class(cmd_str)
    except CLICmdIncompleteError:
        print(bold('%s:'%cmd_str))
        print_list(_commands.list(cmd_str))
    return None

144
def one_command():
145
    try:
146
147
148
149
150
        exe = basename(argv[0])
        parser = _init_parser(exe)
        parsed, unparsed = parse_known_args(parser)
        if _arguments['version'].value:
            exit(0)
151
152
153
154
155
156
157
        _commands.set_groups(_arguments['config'].get_groups())
        cmd = _retrieve_cmd(unparsed)

        if cmd is None:
            parser.print_help()
            exit(0)

158
    except CLIError as err:
159
        _print_error_message(err)
160
        exit(1)