diff --git a/cliff/formatters/table.py b/cliff/formatters/table.py index 12e1ac6..c07e78d 100644 --- a/cliff/formatters/table.py +++ b/cliff/formatters/table.py @@ -2,6 +2,7 @@ """ import prettytable +import six from .base import ListFormatter, SingleFormatter @@ -51,6 +52,9 @@ class TableFormatter(ListFormatter, SingleFormatter): # Now iterate over the data and add the rows. x.add_row(first_row) for row in data_iter: + row = [r.replace('\r\n', '\n').replace('\r', ' ') + if isinstance(r, six.string_types) else r + for r in row] x.add_row(row) formatted = x.get_string(fields=column_names) stdout.write(formatted) @@ -68,6 +72,8 @@ class TableFormatter(ListFormatter, SingleFormatter): x.align['Field'] = 'l' x.align['Value'] = 'l' for name, value in zip(column_names, data): + value = (value.replace('\r\n', '\n').replace('\r', ' ') if + isinstance(value, six.string_types) else value) x.add_row((name, value)) formatted = x.get_string(fields=('Field', 'Value')) stdout.write(formatted) diff --git a/cliff/tests/test_formatters_table.py b/cliff/tests/test_formatters_table.py new file mode 100644 index 0000000..6db91e4 --- /dev/null +++ b/cliff/tests/test_formatters_table.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +from six import StringIO + +from cliff.formatters import table + + +class args(object): + def __init__(self, max_width=0): + self.max_width = max_width + + +def test_table_formatter(): + sf = table.TableFormatter() + c = ('a', 'b', 'c', 'd') + d = ('A', 'B', 'C', 'test\rcarriage\r\nreturn') + expected = '''\ ++-------+---------------+ +| Field | Value | ++-------+---------------+ +| a | A | +| b | B | +| c | C | +| d | test carriage | +| | return | ++-------+---------------+ +''' + output = StringIO() + parsed_args = args() + sf.emit_one(c, d, output, parsed_args) + actual = output.getvalue() + assert expected == actual + + +def test_table_list_formatter(): + sf = table.TableFormatter() + c = ('a', 'b', 'c') + d1 = ('A', 'B', 'C') + d2 = ('D', 'E', 'test\rcarriage\r\nreturn') + data = [d1, d2] + expected = '''\ ++---+---+---------------+ +| a | b | c | ++---+---+---------------+ +| A | B | C | +| D | E | test carriage | +| | | return | ++---+---+---------------+ +''' + output = StringIO() + parsed_args = args() + sf.emit_list(c, data, output, parsed_args) + actual = output.getvalue() + assert expected == actual