Skip to content

Commit

Permalink
Handle embedded newlines in print_table() wireservice#749
Browse files Browse the repository at this point in the history
  • Loading branch information
sethk committed Nov 6, 2020
1 parent 6152fea commit 38a9b63
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions agate/table/print_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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:
Expand All @@ -104,14 +105,33 @@ 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]

if len(v) > widths[j]:
widths[j] = len(v)

formatted_row.append(v)
formatted_row[0].append(v)

if j >= max_columns:
break
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down

0 comments on commit 38a9b63

Please sign in to comment.