Пример #1
0
    def _str_vertical(self):
        output = []

        title_width = sum(self._render_column_widths) + 1  # 1 for ":"
        title_width += len(self._column_padding) * (len(self._render_column_widths) - 1)
        output = [terminal.bold()]
        output.append(self._title.center(title_width, "~"))
        output.append(terminal.reset())
        output = ["".join(output)]
        output.extend(self.genDescription(title_width, title_width - 10))

        for i, column_name in enumerate(self._render_column_names):
            row = []
            row.append(terminal.style(terminal.bg_clear, terminal.fg_clear))

            column_title = column_name
            if column_name == "NODE":
                row.append(terminal.bold())
            row.append(column_title.ljust(self._render_column_widths[0]))
            row.append(":")
            row.append(self._column_padding)
            for j, (cell_format, cell) in enumerate((raw_data[i] for raw_data in self._data), 1):
                cell = cell.ljust(self._render_column_widths[j])
                row.append("%s%s" % (cell_format(), cell))
                row.append(self._column_padding)

            if column_name == "NODE":
                row.append(terminal.reset())
            output.append("".join(row))

        return "\n".join(output) + "\n"
Пример #2
0
    def asinfo(results, line_sep, cluster, **kwargs):
        like = set(kwargs['like'])
        for node_id, value in results.iteritems():
            prefix = cluster.getPrefixes()[node_id]
            node = cluster.getNode(node_id)[0]

            print "%s%s (%s) returned%s:"%(terminal.bold()
                                           , prefix
                                           , node.ip
                                           , terminal.reset())

            if isinstance(value, Exception):
                print "%s%s%s"%(terminal.fg_red()
                                , value
                                , terminal.reset())
                print "\n"
            else:
                # most info commands return a semicolon delimited list of key=value.
                # Assuming this is the case here, later we may want to try to detect
                # the format.
                value = value.split(';')
                likes = CliView.compileLikes(like)
                value = filter(likes.search, value)

                if not line_sep:
                    value = [";".join(value)]

                for line in sorted(value):
                    print line
                print
Пример #3
0
    def asinfo(results, line_sep, cluster, **kwargs):
        like = set(kwargs['like'])
        for node_id, value in results.iteritems():
            prefix = cluster.getPrefixes()[node_id]
            node = cluster.getNode(node_id)[0]

            print "%s%s (%s) returned%s:" % (terminal.bold(), prefix, node.ip,
                                             terminal.reset())

            if isinstance(value, Exception):
                print "%s%s%s" % (terminal.fg_red(), value, terminal.reset())
                print "\n"
            else:
                # most info commands return a semicolon delimited list of key=value.
                # Assuming this is the case here, later we may want to try to detect
                # the format.
                value = value.split(';')
                likes = CliView.compileLikes(like)
                value = filter(likes.search, value)

                if not line_sep:
                    value = [";".join(value)]

                for line in sorted(value):
                    print line
                print
Пример #4
0
    def _getHorizontalHeader(self):
        width = sum(self._render_column_widths)
        width += len(self._column_padding) * (len(self._render_column_widths) - 1)

        column_name_lines = map(lambda h: h.split(" "), self._render_column_display_names)
        max_deep = max(map(len, column_name_lines))

        output = [terminal.bold()]
        output.append(self._title.center(width, "~"))
        output.append(terminal.reset())
        output = ["".join(output)]
        output.extend(self.genDescription(width, width - 10))

        for r in range(max_deep):
            row = []
            for i, c in enumerate(column_name_lines):
                try:
                    row.append(c[r].rjust(self._render_column_widths[i]))
                except IndexError:
                    row.append(".".rjust(self._render_column_widths[i]))
                row.append(self._column_padding)
            output.append(row)

        output = "\n".join(map(lambda r: "".join(r), output))
        return output
Пример #5
0
    def genDescription(self, line_width, desc_width):
        if self._description == "":
            return []

        tdesc = self._description[:].split(" ")
        lines = []
        words = []
        while tdesc != []:
            words.append(tdesc.pop(0))
            line = " ".join(words)
            if len(line) >= desc_width:
                if len(words) > 1:
                    tdesc.insert(0, words.pop())
                    line = " ".join(words)
                words = []
                lines.append(line)
        else:
            if words:
                line = " ".join(words)
                lines.append(line)

        description = ["%s%s%s" % (terminal.dim(), l.center(line_width), terminal.reset()) for l in lines]
        description = "\n".join(description)

        return [description]
Пример #6
0
    def dun(results, cluster, **kwargs):
        for node_id, command_result in results.iteritems():
            prefix = cluster.getPrefixes()[node_id]
            node = cluster.getNode(node_id)[0]

            print "%s%s (%s) returned%s:" % (terminal.bold(), prefix, node.ip,
                                             terminal.reset())

            if isinstance(command_result, Exception):
                print "%s%s%s" % (terminal.fg_red(), command_result,
                                  terminal.reset())
                print "\n"
            else:
                command, result = command_result
                print "asinfo -v '%s'" % (command)
                print result
Пример #7
0
    def executeHelp(self, line, indent=0):
        self._init()

        method = self._findMethod(line)
        if method:
            try:
                try:
                    method_name = method.__name__
                except:
                    #method_name = method.__class__.__name__
                    method_name = None

                if method_name == DEFAULT: # Print controller help
                    CommandHelp.display(self, indent=indent)
                    if self.modifiers:
                        CommandHelp.printText(
                            "%sModifiers%s: %s"%(terminal.underline()
                                                 , terminal.reset()
                                                 , ", ".join(
                                                     sorted(self.modifiers)))
                            , indent=indent)
                    if CommandHelp.hasHelp(method):
                        CommandHelp.display(method, indent=indent)

                    indent += 2
                    for command in sorted(self.commands.keys()):
                        CommandHelp.printText("- %s%s%s:"%(terminal.bold()
                                                           , command
                                                           , terminal.reset())
                                              , indent=indent-1)
                        self.executeHelp([command], indent=indent)
                    return
                elif isinstance(method, ShellException):
                    # Method not implemented
                    pass
                elif method_name is None: # Nothing to print yet
                    method.executeHelp(line, indent=indent)
                else: # Print help for a command
                    CommandHelp.display(method, indent=indent)
                    return
            except IOError as e: 
                raise ShellException(str(e))
        else:
            raise ShellException(
                "Method was not set? %s"%(line))
Пример #8
0
    def executeHelp(self, line, indent=0):
        self._init()

        method = self._findMethod(line)
        if method:
            try:
                try:
                    method_name = method.__name__
                except:
                    #method_name = method.__class__.__name__
                    method_name = None

                if method_name == DEFAULT:  # Print controller help
                    CommandHelp.display(self, indent=indent)
                    if self.modifiers:
                        CommandHelp.printText(
                            "%sModifiers%s: %s" %
                            (terminal.underline(), terminal.reset(), ", ".join(
                                sorted(self.modifiers))),
                            indent=indent)
                    if CommandHelp.hasHelp(method):
                        CommandHelp.display(method, indent=indent)

                    indent += 2
                    for command in sorted(self.commands.keys()):
                        CommandHelp.printText(
                            "- %s%s%s:" %
                            (terminal.bold(), command, terminal.reset()),
                            indent=indent - 1)
                        self.executeHelp([command], indent=indent)
                    return
                elif isinstance(method, ShellException):
                    # Method not implemented
                    pass
                elif method_name is None:  # Nothing to print yet
                    method.executeHelp(line, indent=indent)
                else:  # Print help for a command
                    CommandHelp.display(method, indent=indent)
                    return
            except IOError as e:
                raise ShellException(str(e))
        else:
            raise ShellException("Method was not set? %s" % (line))
Пример #9
0
    def dun(results, cluster, **kwargs):
        for node_id, command_result in results.iteritems():
            prefix = cluster.getPrefixes()[node_id]
            node = cluster.getNode(node_id)[0]

            print "%s%s (%s) returned%s:"%(terminal.bold()
                                           , prefix
                                           , node.ip
                                           , terminal.reset())

            if isinstance(command_result, Exception):
                print "%s%s%s"%(terminal.fg_red()
                                , command_result
                                , terminal.reset())
                print "\n"
            else:
                command, result = command_result
                print "asinfo -v '%s'"%(command)
                print result
Пример #10
0
    def __call__(self, func):
        try:
            if func.__name__ == DEFAULT:
                self.message[0] = "%sDefault%s: %s" % (terminal.underline(), terminal.reset(), self.message[0])
        except:
            pass

        func._command_help = self.message

        return func
Пример #11
0
    def __call__(self, func):
        try:
            if func.__name__ == DEFAULT:
                self.message[0] = "%sDefault%s: %s" % (
                    terminal.underline(), terminal.reset(), self.message[0])
        except:
            pass

        func._command_help = self.message

        return func
Пример #12
0
    def precmd(self, line):
        lines = self.cleanLine(line)

        if not lines:  # allow empty lines
            return ""

        for line in lines:
            if line[0] in self.commands:
                return " ".join(line)

            if len(lines) > 1:
                print "~~~ %s%s%s ~~~" % (terminal.bold(), " ".join(line[1:]), terminal.reset())

            sys.stdout.write(terminal.reset())
            try:
                response = self.ctrl.execute(line)
                if response == "EXIT":
                    return "exit"
            except ShellException as e:
                print "%sERR: %s%s" % (terminal.fg_red(), e, terminal.fg_clear())
        return ""  # line was handled by execute
Пример #13
0
    def do_cake(self, line):
        msg = """
                           *             *
                                                     *
      *                                                               *
               *               (             )
                              (*)           (*)
                       )       |             |       (
              *       (*)     |~|           |~|     (*)
                       |      |S|           |A|      |          *
                      |~|     |P|           |D|     |~|
                      |A|     |I|           |M|     |U|
                     ,|E|a@@@@|K|@@@@@@@@@@@|I|@@@@a|T|.
                .,a@@@|R|@@@@@|E|@@@@@@@@@@@|N|@@@@@|I|@@@@a,.
              ,a@@@@@@|O|@@@@@@@@@@@@.@@@@@@@@@@@@@@|L|@@@@@@@a,
             a@@@@@@@@@@@@@@@@@@@@@\' . `@@@@@@@@@@@@@@@@@@@@@@@@a
             ;`@@@@@@@@@@@@@@@@@@\'   .   `@@@@@@@@@@@@@@@@@@@@@\';
             ;@@@`@@@@@@@@@@@@@\'     .     `@@@@@@@@@@@@@@@@\'@@@;
             ;@@@;,.aaaaaaaaaa       .       aaaaa,,aaaaaaa,;@@@;
             ;;@;;;;@@@@@@@@;@      @.@      ;@@@;;;@@@@@@;;;;@@;
             ;;;;;;;@@@@;@@;;@    @@ . @@    ;;@;;;;@@;@@@;;;;;;;
             ;;;;;;;;@@;;;;;;;  @@   .   @@  ;;;;;;;;;;;@@;;;;@;;
             ;;;;;;;;;;;;;;;;;@@     .     @@;;;;;;;;;;;;;;;;@@@;
         ,%%%;;;;;;;;@;;;;;;;;       .       ;;;;;;;;;;;;;;;;@@;;%%%,
      .%%%%%%;;;;;;;@@;;;;;;;;     ,%%%,     ;;;;;;;;;;;;;;;;;;;;%%%%%%,
     .%%%%%%%;;;;;;;@@;;;;;;;;   ,%%%%%%%,   ;;;;;;;;;;;;;;;;;;;;%%%%%%%,
     %%%%%%%%`;;;;;;;;;;;;;;;;  %%%%%%%%%%%  ;;;;;;;;;;;;;;;;;;;\'%%%%%%%%
     %%%%%%%%%%%%`;;;;;;;;;;;;,%%%%%%%%%%%%%,;;;;;;;;;;;;;;;\'%%%%%%%%%%%%
     `%%%%%%%%%%%%%%%%%,,,,,,,%%%%%%%%%%%%%%%,,,,,,,%%%%%%%%%%%%%%%%%%%%\'
       `%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\'
           `%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\'
"""
        from time import sleep
        s = 0.5
        for line in msg.split('\n'):
            print line
            sleep(s)
            s = s / 1.2
        print terminal.bold() + \
            "Let there be CAKE!".center(80) + \
            terminal.reset()
Пример #14
0
    def watch(ctrl, line):
        diff_highlight = True
        sleep = 2.0
        num_iterations = False

        try:
            sleep = float(line[0])
            line.pop(0)
        except:
            pass
        else:
            try:
                num_iterations = int(line[0])
                line.pop(0)
            except:
                pass

        if "".join(line[0:2]) == "--no-diff":
            diff_highlight = False
            line.pop(0)
            line.pop(0)

        if not terminal.color_enabled:
            diff_highlight = False

        try:
            real_stdout = sys.stdout
            sys.stdout = mystdout = StringIO()
            previous = None
            highlight = False
            count = 1
            while True:
                ctrl.execute(line[:])
                output = mystdout.getvalue()
                mystdout.reset()
                if previous and diff_highlight:
                    result = []
                    for (prev_char, cur_char) in itertools.izip(previous, output):
                        if cur_char == prev_char:
                            if highlight:
                                result += terminal.bg_clear()
                                highlight = False
                            result += cur_char
                        else:
                            if not highlight:
                                result += terminal.bg_blue()
                                highlight = True
                            result += cur_char
                    if highlight:
                        result += terminal.reset()
                    result = "".join(result)
                    previous = output
                else:
                    result = output
                    previous = output

                ts = time.time()
                st = datetime.datetime.fromtimestamp(ts).strftime(' %Y-%m-%d %H:%M:%S')
                command = " ".join(line)
                print >> real_stdout, "[%s '%s' sleep: %ss iteration: %s"%(st
                                                                           , command
                                                                           , sleep
                                                                           , count),
                if num_iterations:
                    print >> real_stdout, " of %s"%(num_iterations),
                print >> real_stdout, "]"
                print >> real_stdout, result

                if num_iterations and num_iterations <= count:
                    break

                count += 1
                time.sleep(sleep)

        except (KeyboardInterrupt, SystemExit):
            return
        finally:
            sys.stdout = real_stdout
            print ''
Пример #15
0
    def watch(ctrl, line):
        diff_highlight = True
        sleep = 2.0
        num_iterations = False

        try:
            sleep = float(line[0])
            line.pop(0)
        except:
            pass
        else:
            try:
                num_iterations = int(line[0])
                line.pop(0)
            except:
                pass

        if "".join(line[0:2]) == "--no-diff":
            diff_highlight = False
            line.pop(0)
            line.pop(0)

        if not terminal.color_enabled:
            diff_highlight = False

        try:
            real_stdout = sys.stdout
            sys.stdout = mystdout = StringIO()
            previous = None
            count = 1
            while True:
                highlight = False
                ctrl.execute(line[:])
                output = mystdout.getvalue()
                mystdout.truncate(0)
                mystdout.seek(0)

                if previous and diff_highlight:
                    result = []
                    prev_iterator = CliView.group_output(previous)
                    next_peeked = []
                    next_iterator = CliView.group_output(output)
                    next_iterator = CliView.peekable(next_peeked, next_iterator)

                    for prev_group in prev_iterator:
                        if '\033' in prev_group:
                            # skip prev escape seq
                            continue

                        for next_group in next_iterator:
                            if '\033' in next_group:
                                # add current escape seq
                                result += next_group
                                continue
                            elif next_group == '\n':
                                if prev_group != '\n':
                                    next_peeked.append(next_group)
                                    break
                                if highlight:
                                    result += terminal.bg_clear()
                                    highlight = False
                            elif prev_group == next_group:
                                if highlight:
                                    result += terminal.bg_clear()
                                    highlight = False
                            else:
                                if not highlight:
                                    result += terminal.bg_blue()
                                    highlight = True

                            result += next_group

                            if '\n' == prev_group and '\n' != next_group:
                                continue
                            break

                    for next_group in next_iterator:
                        if next_group == ' ' or next_group == '\n':
                            if highlight:
                                result += terminal.bg_clear()
                                highlight = False
                        else:
                            if not highlight:
                                result += terminal.bg_blue()
                                highlight = True

                        result += next_group

                    if highlight:
                        result += terminal.reset()
                        highlight = False

                    result = "".join(result)
                    previous = output
                else:
                    result = output
                    previous = output

                ts = time.time()
                st = datetime.datetime.fromtimestamp(ts).strftime(' %Y-%m-%d %H:%M:%S')
                command = " ".join(line)
                print >> real_stdout, "[%s '%s' sleep: %ss iteration: %s"%(st
                                                                           , command
                                                                           , sleep
                                                                           , count),
                if num_iterations:
                    print >> real_stdout, " of %s"%(num_iterations),
                print >> real_stdout, "]"
                print >> real_stdout, result

                if num_iterations and num_iterations <= count:
                    break

                count += 1
                time.sleep(sleep)

        except (KeyboardInterrupt, SystemExit):
            return
        finally:
            sys.stdout = real_stdout
            print ''
Пример #16
0
    def watch(ctrl, line):
        diff_highlight = True
        sleep = 2.0
        num_iterations = False

        try:
            sleep = float(line[0])
            line.pop(0)
        except:
            pass
        else:
            try:
                num_iterations = int(line[0])
                line.pop(0)
            except:
                pass

        if "".join(line[0:2]) == "--no-diff":
            diff_highlight = False
            line.pop(0)
            line.pop(0)

        if not terminal.color_enabled:
            diff_highlight = False

        try:
            real_stdout = sys.stdout
            sys.stdout = mystdout = StringIO()
            previous = None
            count = 1
            while True:
                highlight = False
                ctrl.execute(line[:])
                output = mystdout.getvalue()
                mystdout.truncate(0)
                mystdout.seek(0)

                if previous and diff_highlight:
                    result = []
                    prev_iterator = CliView.group_output(previous)
                    next_peeked = []
                    next_iterator = CliView.group_output(output)
                    next_iterator = CliView.peekable(next_peeked,
                                                     next_iterator)

                    for prev_group in prev_iterator:
                        if '\033' in prev_group:
                            # skip prev escape seq
                            continue

                        for next_group in next_iterator:
                            if '\033' in next_group:
                                # add current escape seq
                                result += next_group
                                continue
                            elif next_group == '\n':
                                if prev_group != '\n':
                                    next_peeked.append(next_group)
                                    break
                                if highlight:
                                    result += terminal.bg_clear()
                                    highlight = False
                            elif prev_group == next_group:
                                if highlight:
                                    result += terminal.bg_clear()
                                    highlight = False
                            else:
                                if not highlight:
                                    result += terminal.bg_blue()
                                    highlight = True

                            result += next_group

                            if '\n' == prev_group and '\n' != next_group:
                                continue
                            break

                    for next_group in next_iterator:
                        if next_group == ' ' or next_group == '\n':
                            if highlight:
                                result += terminal.bg_clear()
                                highlight = False
                        else:
                            if not highlight:
                                result += terminal.bg_blue()
                                highlight = True

                        result += next_group

                    if highlight:
                        result += terminal.reset()
                        highlight = False

                    result = "".join(result)
                    previous = output
                else:
                    result = output
                    previous = output

                ts = time.time()
                st = datetime.datetime.fromtimestamp(ts).strftime(
                    ' %Y-%m-%d %H:%M:%S')
                command = " ".join(line)
                print >> real_stdout, "[%s '%s' sleep: %ss iteration: %s" % (
                    st, command, sleep, count),
                if num_iterations:
                    print >> real_stdout, " of %s" % (num_iterations),
                print >> real_stdout, "]"
                print >> real_stdout, result

                if num_iterations and num_iterations <= count:
                    break

                count += 1
                time.sleep(sleep)

        except (KeyboardInterrupt, SystemExit):
            return
        finally:
            sys.stdout = real_stdout
            print ''