|
16 | 16 | # Third-Party |
17 | 17 | from pydantic import BaseModel |
18 | 18 | 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 |
20 | 22 | from rich.table import Table |
21 | 23 | from rich.panel import Panel |
22 | 24 | from rich.syntax import Syntax |
@@ -212,6 +214,37 @@ def make_authenticated_request( |
212 | 214 | # ------------------------------------------------------------------------------ |
213 | 215 |
|
214 | 216 |
|
| 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 | + |
215 | 248 | def print_json(data: Any, title: Optional[str] = None) -> None: |
216 | 249 | """Pretty print JSON data with Rich. |
217 | 250 |
|
@@ -250,7 +283,7 @@ def print_table( |
250 | 283 | table.add_column(col_name_map.get(column, column), style="cyan") |
251 | 284 |
|
252 | 285 | 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] |
254 | 287 | table.add_row(*row) |
255 | 288 |
|
256 | 289 | console.print(table) |
|
0 commit comments