#!/usr/bin/env python #coding=utf8 ''' CloudControl CLI commands module ''' import re import ConfigParser import os from cccli.exception import * from cccli.command import * class Commands(object): '''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] 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() return h if h is not None else "" class Alias(dict): ''' Alias wrapper''' def load(self, filename): '''load alias from file''' if os.access(filename, os.R_OK): 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''' if os.access(filename, os.R_OK or os.W_OK): fparser = ConfigParser.RawConfigParser() fparser.read(filename) fparser.remove_section("alias") fparser.add_section("alias") for n,v in self.items(): fparser.set("alias", n, v) fparser.write(open(filename, "w"))