From 38a9b638145c531ef9c41ac00f16b72763783407 Mon Sep 17 00:00:00 2001 From: Seth Kingsley Date: Thu, 5 Nov 2020 21:26:04 -0700 Subject: [PATCH] Handle embedded newlines in print_table() #749 --- agate/table/print_table.py | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/agate/table/print_table.py b/agate/table/print_table.py index 7158511b..7e57d30e 100644 --- a/agate/table/print_table.py +++ b/agate/table/print_table.py @@ -68,6 +68,7 @@ def print_table(self, max_rows=20, max_columns=6, output=sys.stdout, max_column_ widths = [len(n) for n in column_names] number_formatters = [] formatted_data = [] + multi_line_rows = False # Determine correct number of decimal places for each Number column for i, c in enumerate(self._columns): @@ -89,7 +90,7 @@ def print_table(self, max_rows=20, max_columns=6, output=sys.stdout, max_column_ if i >= max_rows: break - formatted_row = [] + formatted_row = [[]] for j, v in enumerate(row): if j >= max_columns: @@ -104,6 +105,25 @@ def print_table(self, max_rows=20, max_columns=6, output=sys.stdout, max_column_ ) else: v = six.text_type(v) + vs = v.splitlines() + if len(vs) > 1: + multi_line_rows = True + + v = vs[0] + for k, xv in enumerate(vs): + if k == 0: + v = xv + continue + + if max_column_width is not None and len(xv) > max_column_width: + xv = '%s...' % xv[:max_column_width - 3] + + if len(xv) > widths[j]: + widths[j] = len(xv) + + if k == len(formatted_row): + formatted_row.append([''] * max_columns) + formatted_row[k][j] = xv if max_column_width is not None and len(v) > max_column_width: v = '%s...' % v[:max_column_width - 3] @@ -111,7 +131,7 @@ def print_table(self, max_rows=20, max_columns=6, output=sys.stdout, max_column_ if len(v) > widths[j]: widths[j] = len(v) - formatted_row.append(v) + formatted_row[0].append(v) if j >= max_columns: break @@ -140,7 +160,6 @@ def write_row(formatted_row): write('%s%s%s' % (v_line, text, v_line)) - # Dashes span each width with '+' character at intersection of # horizontal and vertical dividers. divider = '%(v_line)s %(columns)s %(v_line)s' % { 'h_line': h_line, @@ -154,7 +173,10 @@ def write_row(formatted_row): # Rows for formatted_row in formatted_data: - write_row(formatted_row) + for row_line in formatted_row: + write_row(row_line) + if multi_line_rows: + write(divider) # Row indicating data was truncated if rows_truncated: