Skip to content

Commit f94d78a

Browse files
committed
feat: Add logic to truncate long cells in tables
#6 Branch: ConciseTables-6 Signed-off-by: Gabe Goodhart <ghart@us.ibm.com>
1 parent 97ddcb1 commit f94d78a

1 file changed

Lines changed: 35 additions & 2 deletions

File tree

cforge/common.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616
# Third-Party
1717
from pydantic import BaseModel
1818
from pydantic_core import PydanticUndefined
19-
from rich.console import Console
19+
from rich.console import Console, ConsoleOptions, RenderResult, RenderableType
20+
from rich.segment import Segment
21+
from rich.measure import Measurement
2022
from rich.table import Table
2123
from rich.panel import Panel
2224
from rich.syntax import Syntax
@@ -212,6 +214,37 @@ def make_authenticated_request(
212214
# ------------------------------------------------------------------------------
213215

214216

217+
class LineLimit:
218+
"""A renderable that limits the number of lines after rich's wrapping."""
219+
220+
def __init__(self, renderable: RenderableType, max_lines: int):
221+
"""Implement with the wrapped renderable and the max lines to render"""
222+
self.renderable = renderable
223+
self.max_lines = max_lines
224+
225+
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
226+
"""Hook the actual rendering to perform the per-line truncation"""
227+
228+
# Let rich render the content with proper wrapping
229+
lines = console.render_lines(self.renderable, options, pad=False)
230+
231+
# Limit to max_lines
232+
for i, line in enumerate(lines):
233+
if i >= self.max_lines:
234+
# Optionally add an ellipsis indicator
235+
yield Segment("...")
236+
break
237+
yield from line
238+
yield Segment.line()
239+
240+
def __rich_measure__(self, console: Console, options: ConsoleOptions) -> Measurement:
241+
"""Hook the measurement of this entry to pass through to the wrapped
242+
renderable
243+
"""
244+
245+
return Measurement.get(console, options, self.renderable)
246+
247+
215248
def print_json(data: Any, title: Optional[str] = None) -> None:
216249
"""Pretty print JSON data with Rich.
217250
@@ -250,7 +283,7 @@ def print_table(
250283
table.add_column(col_name_map.get(column, column), style="cyan")
251284

252285
for item in data:
253-
row = [str(item.get(col, "")) for col in columns]
286+
row = [LineLimit(str(item.get(col, "")), max_lines=4) for col in columns]
254287
table.add_row(*row)
255288

256289
console.print(table)

0 commit comments

Comments
 (0)