Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/88.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix `Table.set_column_max_width()` having no effect on rendered tables
8 changes: 5 additions & 3 deletions src/cleo/ui/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def set_column_widths(self, widths: list[int]) -> Table:
return self

def set_column_max_width(self, column_index: int, width: int) -> Table:
self._column_widths[column_index] = width
self._column_max_widths[column_index] = width

return self

Expand Down Expand Up @@ -426,8 +426,10 @@ def _build_table_rows(self, rows: Rows) -> Iterator[Row | TableSeparator]:
if column in self._column_max_widths and self._column_max_widths[
column
] < len(self._io.remove_format(cell)):
assert isinstance(self._io, Output)
cell = self._io.formatter.format_and_wrap(
output = (
self._io if isinstance(self._io, Output) else self._io.output
)
cell = output.formatter.format_and_wrap(
cell, self._column_max_widths[column] * colspan
)

Expand Down
43 changes: 43 additions & 0 deletions tests/ui/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,46 @@ def test_style_for_side_effects(io: BufferedIO) -> None:
output2 = io.fetch_output()

assert output1 != output2


def test_column_max_width_wraps_long_cells(io: BufferedIO) -> None:
table = Table(io)
table.set_headers(["ISBN", "Description"])
table.set_rows(
[["99921-58-10-7", "A long description that has to be wrapped to fit"]]
)
table.set_column_max_width(1, 12)

table.render()

expected = """\
+---------------+--------------+
| ISBN | Description |
+---------------+--------------+
| 99921-58-10-7 | A long descr |
| | iption that |
| | has to be wr |
| | apped to fit |
+---------------+--------------+
"""

assert io.fetch_output() == expected


def test_column_max_width_does_not_widen_short_cells(io: BufferedIO) -> None:
table = Table(io)
table.set_headers(["ISBN", "Title"])
table.set_rows([["99921-58-10-7", "Divine Comedy"]])
table.set_column_max_width(1, 40)

table.render()

expected = """\
+---------------+---------------+
| ISBN | Title |
+---------------+---------------+
| 99921-58-10-7 | Divine Comedy |
+---------------+---------------+
"""

assert io.fetch_output() == expected