Skip to content

Commit 41ae850

Browse files
authored
Fix calculation of folded table widths (#1251)
2 parents e7d6123 + c50844a commit 41ae850

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

src/globus_cli/termio/printers/folded_table_printer.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,22 @@ def content_rows(self) -> tuple[Row, ...]:
180180
return self.rows[1:]
181181

182182
def fits_in_width(self, width: int) -> bool:
183-
return all(x.min_rendered_width <= width for x in self.rows)
183+
return self.calculate_width() <= width
184+
185+
def calculate_width(self) -> int:
186+
"""
187+
For each column, find the row where that column is the max width.
188+
Sum those widths + the width of the separators (3 * (ncols-1))
189+
"""
190+
max_widths = []
191+
for idx in range(self.num_columns):
192+
max_widths.append(max(row.column_widths[idx] for row in self.rows))
193+
194+
decoration_length = 0
195+
if self.folded:
196+
decoration_length = 4
197+
198+
return sum(max_widths) + (3 * (self.num_columns - 1)) + decoration_length
184199

185200
def fold_rows(self, n: int) -> RowTable:
186201
"""Produce a new table with folded rows."""
@@ -247,13 +262,6 @@ def _split_level(
247262
def is_folded(self) -> bool:
248263
return len(self.grid) > 1
249264

250-
@functools.cached_property
251-
def min_rendered_width(self) -> int:
252-
decoration_length = 0
253-
if self.is_folded:
254-
decoration_length = 4
255-
return sum(self.column_widths) + (3 * (self.num_cols - 1)) + decoration_length
256-
257265
@functools.cached_property
258266
def num_cols(self) -> int:
259267
return max(0, *(len(subrow) for subrow in self.grid))

tests/unit/termio/printer/test_folded_table_printer.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from globus_cli.termio import Field
66
from globus_cli.termio.printers import FoldedTablePrinter
7-
from globus_cli.termio.printers.folded_table_printer import Row
7+
from globus_cli.termio.printers.folded_table_printer import Row, RowTable
88

99

1010
@pytest.mark.parametrize(
@@ -197,3 +197,19 @@ def test_row_folding_with_remainder():
197197
("2", "5"),
198198
("3",),
199199
)
200+
201+
202+
def test_row_table_width_computation_is_pessimal():
203+
"""
204+
Given a table with lopsided rows, such that each row could fit in a narrow width,
205+
but when column-aligned they are wider, the table should find the width based on
206+
the justification of text.
207+
"""
208+
row1 = Row((("a" * 1000, "b"),))
209+
row2 = Row((("c", "d" * 1000),))
210+
211+
table = RowTable((row1, row2))
212+
213+
# it should be the max width for each column (1000) + the width of separators (in
214+
# this case, 3 for the center divider)
215+
assert table.calculate_width() == 2003

0 commit comments

Comments
 (0)