Ejemplo n.º 1
0
def ps_screen(full=False):
    screens = [p for p in psutil.process_iter()
               if p.name() in ['screen', 'tmux']]

    screens.sort(key=methodcaller('cwd'))

    columns = terminal_columns()

    table = [table_row(s, full) for s in screens]

    lines = tabulate(table, tablefmt='plain', numalign='left').split('\n')

    for screen, line in zip(screens, lines):
        stripped_length = len(strip_ansi(line))

        if columns and stripped_length > columns:
            line = line[0:-(stripped_length - columns + 6)] + '...'

        click.echo(line)

        if full:
            for c in screen.children():
                print_child(c, columns=columns)

            print
Ejemplo n.º 2
0
def _pipepager(text, cmd, color):
    """Page through text by feeding it to another program.  Invoking a
    pager through this might support colors.
    """
    import subprocess
    env = dict(os.environ)

    # If we're piping to less we might support colors under the
    # condition that
    cmd_detail = cmd.rsplit('/', 1)[-1].split()
    if color is None and cmd_detail[0] == 'less':
        less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])
        if not less_flags:
            env['LESS'] = '-R'
            color = True
        elif 'r' in less_flags or 'R' in less_flags:
            color = True

    if not color:
        text = strip_ansi(text)

    c = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, env=env)
    encoding = get_best_encoding(c.stdin)
    try:
        c.stdin.write(text.encode(encoding, 'replace'))
        c.stdin.close()
    except (IOError, KeyboardInterrupt):
        pass

    return c
Ejemplo n.º 3
0
def ps_screen(full=False):
    screens = [p for p in psutil.process_iter()
               if p.name() in ['screen', 'tmux']]

    screens.sort(key=methodcaller('cwd'))

    columns = terminal_columns()

    table = [table_row(s, full) for s in screens]

    lines = tabulate(table, tablefmt='plain', numalign='left').split('\n')

    for screen, line in zip(screens, lines):
        stripped_length = len(strip_ansi(line))

        if columns and stripped_length > columns:
            line = line[0:-(stripped_length - columns + 6)] + '...'

        click.echo(line)

        if full:
            for c in screen.children():
                print_child(c, columns=columns)

            print
Ejemplo n.º 4
0
def test_error_formatter_mixed():
    assert strip_ansi(
        format_error_data({
            "environment": [{
                "message":
                "Object with slug or primary key bluup does not exist.",
                "code": "does_not_exist"
            }],
            "non_field_errors": [
                'oh',
                'oh no',
                'that\'s bad',
                {
                    'message': 'this is fine',
                    'code': 'dog_not_on_fire'
                },
            ],
        })) == ('''
* oh
* oh no
* that's bad
* this is fine (code: dog_not_on_fire)
environment:
  * Object with slug or primary key bluup does not exist. (code: does_not_exist)
    ''').strip()
Ejemplo n.º 5
0
def test_error_formatter_simple():
    assert strip_ansi(
        format_error_data({
            "environment": [{
                "message":
                "Object with slug or primary key bluup does not exist.",
                "code": "does_not_exist"
            }]
        })
    ) == 'environment:\n  * Object with slug or primary key bluup does not exist. (code: does_not_exist)'
Ejemplo n.º 6
0
 def _compute_col_sizes(self, data):
     sizes = {}
     # prepend data with header
     data = [dict(zip(self._cols, self._cols))] + data
     for row in data:
         for name, row_data in row.iteritems():
             real_len = len(strip_ansi(row_data))
             if name not in sizes or real_len > sizes[name]:
                 sizes[name] = real_len
     # filter unknown values
     self._sizes = dict([(key, length + self.COL_PADDING) for key, length in sizes.iteritems() if key in self._cols])
Ejemplo n.º 7
0
def _tempfilepager(text, cmd, color):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    if not color:
        text = strip_ansi(text)
    encoding = get_best_encoding(sys.stdout)
    with open_stream(filename, 'wb')[0] as f:
        f.write(text.encode(encoding))
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename)
Ejemplo n.º 8
0
def print_child(p, depth=1, columns=0):
    output = (('  ' * depth) +
              click.style(str(p.pid), fg='cyan', bold=True) +
              ' ' +
              collapse_home(clean(' '.join(p.cmdline()))))

    stripped_length = len(strip_ansi(output))

    if columns and stripped_length > columns:
        output = output[0:-(stripped_length - columns + 6)] + '...'

    click.echo(output)

    depth += 1

    for c in p.children():
        print_child(c, depth, columns)
Ejemplo n.º 9
0
def print_child(p, depth=1, columns=0):
    output = (('  ' * depth) +
              click.style(str(p.pid), fg='cyan', bold=True) +
              ' ' +
              collapse_home(clean(' '.join(p.cmdline()))))

    stripped_length = len(strip_ansi(output))

    if columns and stripped_length > columns:
        output = output[0:-(stripped_length - columns + 6)] + '...'

    click.echo(output)

    depth += 1

    for c in p.children():
        print_child(c, depth, columns)
Ejemplo n.º 10
0
def add_dir_entries(backup_run, filtered_dir_entries, result):
    total_size = sum([entry.stat.st_size for entry in filtered_dir_entries])
    print(("total size:", human_filesize(total_size)))
    path_iterator = sorted(
        filtered_dir_entries,
        key=lambda x: x.stat.st_mtime, # sort by last modify time
        reverse=True # sort from newest to oldes
    )
    # FIXME: The process bar will stuck if many small/null byte files are processed
    # Maybe: Change from bytes to file count and use a second bar if a big file
    # hash will be calculated.
    with tqdm(total=total_size, unit='B', unit_scale=True) as process_bar:
        for dir_entry in path_iterator:
            try:
                add_dir_entry(backup_run, dir_entry, process_bar, result)
            except Exception as err:
                # A unexpected error occurred.
                # Print and add traceback to summary
                log.error("Can't backup %s: %s" % (dir_entry, err))
                for line in exc_plus():
                    log.error(strip_ansi(line))
Ejemplo n.º 11
0
    def display_columns(self,
                        rows: Sequence[Sequence[str]],
                        header: Optional[List[str]] = None) -> None:
        """Print rows in aligned columns.

        :param rows: a rows of data to be displayed.
        :param header: a list of header strings.
        """
        def get_aligner(align: str) -> Callable:
            if align == ">":
                return rjust
            if align == "^":
                return centerize
            else:
                return ljust

        sizes = list(
            map(
                lambda column: max(map(lambda x: len(strip_ansi(x)), column)),
                zip_longest(header or [], *rows, fillvalue=""),
            ))

        aligners = [ljust] * len(sizes)
        if header:
            aligners = []
            for i, head in enumerate(header):
                aligners.append(get_aligner(head[0]))
                if head[0] in (">", "^", "<"):
                    header[i] = head[1:]
            self.echo(" ".join(
                aligner(head, size)
                for aligner, head, size in zip(aligners, header, sizes)))
            # Print a separator
            self.echo(" ".join("-" * size for size in sizes))
        for row in rows:
            self.echo(" ".join(
                aligner(item, size)
                for aligner, item, size in zip(aligners, row, sizes)))
Ejemplo n.º 12
0
 def __call__(self, *parts, sep=" ", end="\n", flush=False):
     print(*parts, sep=sep, end=end, flush=flush)
     self.summary_file.write(sep.join([strip_ansi(str(i)) for i in parts]))
     self.summary_file.write(end)
     if flush:
         self.summary_file.flush()
Ejemplo n.º 13
0
 def _str(self, data, size):
     str_real_len = len(strip_ansi(data))
     return data + (" " * (size - str_real_len))
Ejemplo n.º 14
0
def centerize(text: str, length: int) -> str:
    """Centerize the text while ignoring ANSI controlling characters."""
    space_num = length - len(strip_ansi(text))
    left_space = space_num // 2
    return " " * left_space + text + " " * (space_num - left_space)
Ejemplo n.º 15
0
def rjust(text: str, length: int) -> str:
    """Like str.rjust() but ignore all ANSI controlling characters."""
    return " " * (length - len(strip_ansi(text))) + text
Ejemplo n.º 16
0
def _nullpager(stream, text, color):
    """Simply print unformatted text.  This is the ultimate fallback."""
    if not color:
        text = strip_ansi(text)
    stream.write(text)