Newer
Older
#!/usr/bin/env python
#coding=utf8
'''
CloudControl CLI commands module
'''
import re
import ConfigParser
import os
from cccli.exception import *
'''Command manager'''
def __init__(self, cli):
# save cli context
self.cli = cli
# build command list
self.cmds = dict()
for x in [ x for x in globals() if x.startswith("Command_") ]:
self.cmds[x[8:]] = globals()[x]
# build remote function list
try:
self.functions = set([ c["name"] for c in self.cli.rpc.call("functions") ])
except RpcError as e:
raise cliError("RPCError: Unable to retrieve remote commands: %s"%str(e))
# remove not available commands
for cname in tuple(self.cmds):
cobj = self.cmds[cname](self.cli, cname)
if isinstance(cobj, command.RemoteCommand):
try:
if len(cobj.remote_functions()) == 0:
raise NotImplementedError("No remote function")
if not cobj.remote_functions().issubset(self.functions):
del self.cmds[cname]
self.cli.printer.debug("Command %s not available"%cname)
except NotImplementedError as e:
self.cli.printer.debug("Command %s lack of remote_functions"%cname)
del self.cmds[cname]
def __len__(self):
return len(self.cmds)
def __contains__(self, item):
return item in self.cmds.keys()
def __iter__(self):
return iter(self.cmds.keys())
def __repr__(self):
return repr(self.cmds.keys())
def __call__(self, argv):
# check argv
if len(argv) == 0:
raise cmdBadName()
# find right commands to call
if argv[0] not in self:
matchlist = [ x for x in self if re.match("%s.+"%re.escape(argv[0]), x) ]
if len(matchlist) == 1:
argv[0] = matchlist[0]
else:
raise cmdBadName()
# create class and call it
cmd = self.cmds[argv[0]](self.cli, argv[0])
return cmd(argv)
def usage(self, argv0):
'''Return usage of a command'''
u = self.cmds[argv0](self.cli, argv0).usage()
return u if u is not None else ""
def help(self, argv0):
'''Return of a command'''
h = self.cmds[argv0](self.cli, argv0).help()
def load(self, filename):
'''load alias from file'''
fparser = ConfigParser.RawConfigParser()
fparser.read(filename)
if fparser.has_section("alias"):
self.clear()
self.update(fparser.items("alias"))
def save(self, filename):
'''save alias on file'''