def get_subcommand(self, command, args): missing_is_error = False traceme = '' the_store = self.subcommands while True: traceme = '%s_%s' % (traceme, command) if len(traceme) else command # first level generates KeyError if the command is not found # other levels generate RuntimeError try: subcommands = the_store[command] except KeyError as exc: if missing_is_error: raise RuntimeError( _("Command <%s> is not defined") % traceme) else: raise exc # subcommands is a dict of commands names # if this is a nested list # of a function name if isinstance(subcommands, str): return subcommands, args the_store = subcommands if len(args) == 0: raise RuntimeError( _("Command <%s> needs a subcommand") % traceme) command, args, line = self.parseline(args)
def helps_set_loglevel(self): self.info( _("""Change logging verbosity. Arguments --------- level: new level; can be one of `d[ebug]` , `i[nfo]`, `w[arning]` or `e[rror]` to: this is just syntactic sugar so the sentence looks nice; can be omitted; adapter: the adapter(s) that should receive the words. Description ----------- The program logs data to a file and to console. The user can control the verbosity by using this command. Please note that there are two notification systems: - the logging system is mostly used by the library and low level commands; - the command system uses a separate way of printing errors only to the screen. This command controls the low level logging facility. Example ------- $: set loglevel debug to console $: set loglevel debug console $: set loglevel d c $: set loglevel debug $: set loglevel info to file $: set loglevel i f """))
def sdo_list_macros(self, arg): """ Lists available macros. Options ------- content : bool (optional, default: False) Show the content of the macros. arg : dict Other arguments """ if len(arg['args']) > 1: self.error(_('Too many arguments for command'), _('The format is `list macros [content]`\n' ' The `content` optional parameter can be \n' ' true of false (default).')) return show_content = False if len(arg['args']) == 1: show_content = arg['args'][0].lower() if show_content in ('true', 'yes', 'on'): show_content = True elif show_content in ('false', 'no', 'off'): pass else: self.error(_('Invalid argument for command'), _('The format is `list macros [content]`\n' ' The `content` optional parameter can be \n' ' true of false (default).')) return self.info_start(_("MACROS\n======\n")) if len(self.macros) == 0: self.info_line("No macros have been defined. " "Use 'new macro <name>' to start " "recording one and " "'end macro' to save it.") else: for mmm in self.macros: self.info_line(" %s" % mmm) if show_content: for line in self.macros[mmm]: self.info_line(" %s" % line) self.info_end("")
def sdo_drop_macro(self, arg, name): """ Removes a macro. Parameters ---------- name : string The name of the macro to delete. """ try: del self.macros[name] except KeyError: self.error(_('Macro `%s` does not exist') % name, _('Use <list macros> command to ' 'find out available macros'))
def sdo_run_macro(self, arg, name): """ Executes a previously recorded macro Parameters ---------- name : string The name of the macro to run. """ try: commands = self.macros[name] except KeyError: self.error(_('Macro `%s` does not exist') % name, _('Use <list macros> command to ' 'find out available macros')) return self.run_commands(commands)
def get_kind(value): kind = value.lower() if kind in ('c', 'con', 'console'): target = (console_handler, 'console') elif kind in ('f', 'file'): target = (file_handler, 'file') else: self.error( _("Invalid target argument: %s") % kind, command_format) target = (None, None) return target
def warning(self, message, description=''): """Print an warning message.""" self.warning_count = self.warning_count + 1 self.print_message(_('Warning! ')) self.print_message(message) self.print_message("\n") if len(description): if isinstance(description, str): description = description.split("\n") for ddd in description: self.print_message(ddd) self.print_message("\n")
def helps_list_macros(self): self.info(_(""" Lists existing macro. Description ----------- Macros are stored at instance level and are available to all agents. Example ------- $: list macros """))
def error(self, message, description=''): """Print an error message.""" self.error_count = self.error_count + 1 self.print_message(_('ERROR!!! ')) self.print_message(message) self.print_message("\n") if len(description): if isinstance(description, str): description = description.split("\n") for ddd in description: self.print_message(' ') self.print_message(ddd) self.print_message("\n")
def parse(args, args_template=None): """Interprets arguments based on input""" # lang is not initialized by the time this module is imported. args = shlex.split(args) if args_template is None: return OrderedDict((k, None) for k in args) result = OrderedDict() has_args = 'args' in args_template i = 0 missing = '' for templ in args_template: if templ == 'args': continue try: result[templ] = args[i] i = i + 1 except IndexError: missing = missing + \ (_('Required argument %s is missing\n') % templ) if len(missing): raise ValueError(missing) # + 'Required arguments: ' + ' '.join((k if k != 'args' # else '<other arguments>' for k in args_template))) # optional arguments if i < len(args): if has_args: result['args'] = args[i:] else: raise ValueError( _('Unrecognized arguments: ') + ', '.join(args[i:])) elif has_args: result['args'] = [] return result
def sdo_end_macro(self, arg): """ Ends recording a new macro. Parameters ---------- """ if not self.is_macro_recording: raise RuntimeError( _("Not recording a macro")) # First command is `new macro XXX` so we drop that self.macros[self.macro_rec_name] = self.macro_recording[1:] self.macro_rec_name = None self.macro_recording = None
def helps_end_macro(self): self.info(_(""" Stops recording and saves the macro. Preconditions ------------- A record MUST be in the recording stage. Description ----------- Macros are stored at instance level and are available to all agents. Example ------- $: end macro """))
def helps_new_macro(self): self.info(_(""" Creates a new macro and starts recording. Arguments --------- name: the unique identifier of the macro. Description ----------- Macros are stored at instance level and are available to all agents. Example ------- $: new macro cmd1 """))
def sdo_new_macro(self, arg, name): """ Starts recording a new macro. Parameters ---------- name : string A name for the macro. You will use this to later recall the macro. """ if self.is_macro_recording: raise RuntimeError( _("Already recording macro %s") % repr(self.macro_rec_name)) self.macro_rec_name = name self.macro_recording = []
def helps_run_macro(self): self.info(_(""" Executes a macro. Preconditions ------------- The macro MUST exist. Description ----------- Macros are stored at instance level and are available to all agents. Example ------- $: run macro cmd1 """))
def helps_drop_macro(self): self.info(_(""" Removes a macro. Arguments --------- name: the unique identifier of the macro. Preconditions ------------- The macro MUST exist. Description ----------- Macros are stored at instance level and are available to all agents. Example ------- $: drop macro cmd1 """))
def sdo_set_loglevel(self, arg): command_format = _( "The format of the command is `set loglevel LEVEL [[to] TARGET]`\n" "Where LEVEL is `d[ebug]` , `i[nfo]`, `w[arning]` and `e[rror]` \n" "TARGET is one of `c[onsole]` or `f[ile]` (default is console)") console_handler = None file_handler = None for handler in logging.getLogger().handlers: if isinstance(handler, logging.FileHandler): file_handler = handler elif isinstance(handler, logging.StreamHandler): console_handler = handler def get_kind(value): kind = value.lower() if kind in ('c', 'con', 'console'): target = (console_handler, 'console') elif kind in ('f', 'file'): target = (file_handler, 'file') else: self.error( _("Invalid target argument: %s") % kind, command_format) target = (None, None) return target target = None target_str = '' log_level = None level_str = arg['level'].lower() args = arg['args'] if len(args) == 0: target = console_handler target_str = 'console' elif len(args) == 1: target, target_str = get_kind(args[0]) elif len(args) == 2: sugar = args[0].lower() if not sugar in ('2', 'to'): self.error(_("Invalid list of arguments"), command_format) else: target, target_str = get_kind(args[1]) else: self.error(_("Invalid list of arguments"), command_format) if level_str in ('d', 'debug'): log_level = logging.DEBUG elif level_str in ('w', 'warn', 'warning'): log_level = logging.WARNING elif level_str in ('i', 'info', 'information'): log_level = logging.INFO elif level_str in ('e', 'err', 'error'): log_level = logging.ERROR elif level_str in ('c', 'crit', 'critical'): log_level = logging.CRITICAL else: try: log_level = int(level_str) except ValueError: self.error(_("Invalid level"), command_format) if not (log_level is None or target is None): target.setLevel(log_level) top_log = logging.getLogger() if top_log.level > log_level: top_log.setLevel(log_level) logger.debug('New log level %s set to %s', level_str, target_str)
def cmd_with_result(self, line): """ Interpret the argument as if it had been typed in response to the prompt. """ prefix = 'do_' cmd, arg, line = self.parseline(str(line)) if not line: return self.emptyline(), False if cmd is None: return self.default(line), False self.lastcmd = line if line == 'EOF': self.lastcmd = '' if cmd == '': return self.default(line), False else: # Examine shortcuts try: shortcut = self.shortcuts[cmd] cmd = shortcut[0] arg = '%s %s' % (shortcut[1], arg) except KeyError: pass # see if this is a subcommand try: cmd, arg = self.get_subcommand(cmd, arg) prefix = 'sdo_' except KeyError: pass except RuntimeError as exc: self.error(str(exc)) return False, False try: func = getattr(self, prefix + cmd) except AttributeError: return self.default(line), False if cmd == 'help': return self.do_help(arg), False try: args_template = getattr(self, 'args_' + cmd) except AttributeError: args_template = ['args'] try: parsed = parse(arg, args_template) except ValueError as exc: self.error(_('Arguments could not be parsed:'), str(exc)) return False, False try: return func(parsed), True except Exception as exc: self.error( _('Exception while executing do_%s') % cmd, str(exc)) traceback.print_exc(file=self.stdout) # traceback.print_stack(file=self.stdout) return False, False