示例#1
0
 def theme(self, value):
     """
     :param value: new theme to set
     :type value: themes.NoColorTheme
     """
     assert isinstance(value, themes.NoColorTheme)
     for key in self._utils.keys():
         self._utils[key].theme = value
     log.debug(lfm(" |- theme(value) {0} | \\{0} |  |- theme switched to : '{1}'", os.linesep, value))
     self._theme = value
示例#2
0
 def theme(self, value):
     """
     :param value: new theme to set
     :type value: themes.NoColorTheme
     """
     assert (isinstance(value, themes.NoColorTheme))
     for key in self._utils.keys():
         self._utils[key].theme = value
     log.debug(
         lfm(" |- theme(value) {0} | \\{0} |  |- theme switched to : '{1}'",
             os.linesep, value))
     self._theme = value
示例#3
0
    def search_utils(self, path):
        """Load plugins from directory and return list of modules

        :rtype: []
        """

        # >oO debug output
        log.debug(lfm("{0}search_utils{0}\\", os.linesep))
        log.debug(
            lfm(
                " |- searching modules in directory:{0} |  '{1}{2}{3}'",
                os.linesep,
                self.theme.Directories,
                path,
                self.theme.Reset,
            )
        )

        # get list of files and module names
        files = os.listdir(path)
        test = re.compile(".py$", re.IGNORECASE)
        files = filter(test.search, files)
        filenameToModuleName = lambda f: os.path.splitext(f)[0]
        moduleNames = sorted(map(filenameToModuleName, files))
        log.debug(lfm(" |- found '{0}' modules.{1} |- proceed loading each module:{1}", len(moduleNames), os.linesep))

        modules = []
        for m in moduleNames:
            # skip any files starting with '__', such as __init__.py
            if m.startswith("__"):
                continue
            try:
                f, filename, desc = imp.find_module(m, [path])
                modules.append(imp.load_module(m, f, filename, desc))
            except ImportError as ex:
                log.debug(lfm(" |- error importing module: {0}", m))
                log.debug(lfm(" |\\{0} ||-{1}", os.linesep, repr(ex)))
                continue

        return modules
示例#4
0
    def search_utils(self, path):
        """Load plugins from directory and return list of modules

        :rtype: []
        """

        # >oO debug output
        log.debug(lfm("{0}search_utils{0}\\", os.linesep))
        log.debug(
            lfm(" |- searching modules in directory:{0} |  '{1}{2}{3}'",
                os.linesep, self.theme.Directories, path, self.theme.Reset))

        # get list of files and module names
        files = os.listdir(path)
        test = re.compile(".py$", re.IGNORECASE)
        files = filter(test.search, files)
        filenameToModuleName = lambda f: os.path.splitext(f)[0]
        moduleNames = sorted(map(filenameToModuleName, files))
        log.debug(
            lfm(
                " |- found '{0}' modules.{1} |- proceed loading each module:{1}",
                len(moduleNames), os.linesep))

        modules = []
        for m in moduleNames:
            # skip any files starting with '__', such as __init__.py
            if m.startswith('__'):
                continue
            try:
                f, filename, desc = imp.find_module(m, [path])
                modules.append(imp.load_module(m, f, filename, desc))
            except ImportError as ex:
                log.debug(lfm(" |- error importing module: {0}", m))
                log.debug(lfm(" |\\{0} ||-{1}", os.linesep, repr(ex)))
                continue

        return modules
示例#5
0
    def register_utilities(self, path=""):
        """ Function to auto find and register utilities"""
        path = path or os.path.join(ccdb.cmd.__path__[0], "utils")

        # search modules
        modules = self.search_utils(path)
        self._utils = {}

        # register each module
        for module in modules:
            try:
                registerFunc = getattr(module, "create_util_instance")
                util = registerFunc()
                if util:
                    self._utils[util.command] = util
                    util.context = self
                    util.theme = self.theme
                    if util.command == "ls":
                        self._ls = util

            except AttributeError as ex:
                log.debug("Error registering module : " + repr(ex))
            except Exception as ex:
                log.debug("Error registering module : " + repr(ex))

        if log.isEnabledFor(logging.DEBUG):
            log.debug(
                lfm("{0}Utils found and registered in directory '{1}' are:",
                    os.linesep, path))
            log.debug("{0:<10} {1:<15} {2}:".format("(command)", "(name)",
                                                    "(description)"))
            log.debug("\n".join([
                "{0:<10} {1:<15} {2}:".format(command, util.name,
                                              util.short_descr)
                for command, util in self._utils.items()
            ]))
示例#6
0
    def register_utilities(self, path=""):
        """ Function to auto find and register utilities"""
        path = path or os.path.join(ccdb.cmd.__path__[0], "utils")

        # search modules
        modules = self.search_utils(path)
        self._utils = {}

        # register each module
        for module in modules:
            try:
                registerFunc = getattr(module, "create_util_instance")
                util = registerFunc()
                if util:
                    self._utils[util.command] = util
                    util.context = self
                    util.theme = self.theme
                    if util.command == "ls":
                        self._ls = util

            except AttributeError as ex:
                log.debug("Error registering module : " + repr(ex))
            except Exception as ex:
                log.debug("Error registering module : " + repr(ex))

        if log.isEnabledFor(logging.DEBUG):
            log.debug(lfm("{0}Utils found and registered in directory '{1}' are:", os.linesep, path))
            log.debug("{0:<10} {1:<15} {2}:".format("(command)", "(name)", "(description)"))
            log.debug(
                "\n".join(
                    [
                        "{0:<10} {1:<15} {2}:".format(command, util.name, util.short_descr)
                        for command, util in self._utils.items()
                    ]
                )
            )
示例#7
0
    def process_command(self, command, args):
        # >oO debug
        if log.isEnabledFor(logging.DEBUG):
            log.debug(
                lfm("{0}Processing command: '{1}'{0}\\", os.linesep, command))
            log.debug(lfm(" |- arguments : '{0}'", "' '".join(args)))

        # try to find function...
        try:
            util = self._utils[command]
        except KeyError:
            log.error(
                "Command " + command +
                " is unknown! Please, use help to see available commands")
            if not self.silent_exceptions:
                raise
            else:
                return 1

        # check connection and connect if needed
        if util.uses_db and (not self.provider.is_connected):
            if not self.check_connection(util):
                return False

        # is there file redirect?
        redir_to_file = False  # should we redirect to file?
        redir_file = None  # file to redirect
        redir_stream_backup = sys.stdout
        redir_theme_backup = self.theme

        if ">" in args and args.index(">") == len(args) - 2:

            redir_fname = args[-1]
            redir_to_file = True
            args = args[:-2]
            log.debug(" |- redirecting to file : {0}".format(redir_fname))

            # open file
            try:
                redir_file = file(redir_fname, 'w')
            except Exception as ex:
                log.error("Cannot open file '{0}' {1} ".format(
                    redir_fname, ex))
                if not self.silent_exceptions:
                    raise
                else:
                    return 1

        # execute command
        try:
            if redir_to_file:
                colorama.deinit()
                sys.stdout = redir_file
                self.theme = themes.NoColorTheme()

            result = util.process(args)

        except Exception as ex:
            log.error(ex)
            if not self.silent_exceptions:
                raise
            else:
                return 1
        finally:
            if redir_to_file:
                sys.stdout = redir_stream_backup
                redir_file.close()
                self.theme = redir_theme_backup
                colorama.reinit()
        return result
示例#8
0
    def process_command(self, command, args):
        # >oO debug
        if log.isEnabledFor(logging.DEBUG):
            log.debug(lfm("{0}Processing command: '{1}'{0}\\", os.linesep, command))
            log.debug(lfm(" |- arguments : '{0}'", "' '".join(args)))

        # try to find function...
        try:
            util = self._utils[command]
        except KeyError:
            log.error("Command " + command + " is unknown! Please, use help to see available commands")
            if not self.silent_exceptions:
                raise
            else:
                return 1

        # check connection and connect if needed
        if util.uses_db and (not self.provider.is_connected):
            if not self.check_connection(util):
                return False

        # is there file redirect?
        redir_to_file = False  # should we redirect to file?
        redir_file = None  # file to redirect
        redir_stream_backup = sys.stdout
        redir_theme_backup = self.theme

        if ">" in args and args.index(">") == len(args) - 2:

            redir_fname = args[-1]
            redir_to_file = True
            args = args[:-2]
            log.debug(" |- redirecting to file : {0}".format(redir_fname))

            # open file
            try:
                redir_file = file(redir_fname, "w")
            except Exception as ex:
                log.error("Cannot open file '{0}' {1} ".format(redir_fname, ex))
                if not self.silent_exceptions:
                    raise
                else:
                    return 1

        # execute command
        try:
            if redir_to_file:
                colorama.deinit()
                sys.stdout = redir_file
                self.theme = themes.NoColorTheme()

            result = util.process(args)

        except Exception as ex:
            log.error(ex)
            if not self.silent_exceptions:
                raise
            else:
                return 1
        finally:
            if redir_to_file:
                sys.stdout = redir_stream_backup
                redir_file.close()
                self.theme = redir_theme_backup
                colorama.reinit()
        return result