cmd2 2.7.0__py3-none-any.whl → 3.0.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cmd2/__init__.py +41 -38
- cmd2/argparse_completer.py +80 -81
- cmd2/argparse_custom.py +322 -123
- cmd2/clipboard.py +1 -1
- cmd2/cmd2.py +1264 -837
- cmd2/colors.py +270 -0
- cmd2/command_definition.py +13 -5
- cmd2/constants.py +0 -6
- cmd2/decorators.py +41 -104
- cmd2/exceptions.py +1 -1
- cmd2/history.py +7 -11
- cmd2/parsing.py +12 -17
- cmd2/plugin.py +1 -2
- cmd2/py_bridge.py +15 -10
- cmd2/rich_utils.py +451 -0
- cmd2/rl_utils.py +12 -8
- cmd2/string_utils.py +166 -0
- cmd2/styles.py +72 -0
- cmd2/terminal_utils.py +144 -0
- cmd2/transcript.py +7 -9
- cmd2/utils.py +88 -508
- {cmd2-2.7.0.dist-info → cmd2-3.0.0b1.dist-info}/METADATA +22 -44
- cmd2-3.0.0b1.dist-info/RECORD +27 -0
- cmd2/ansi.py +0 -1093
- cmd2/table_creator.py +0 -1122
- cmd2-2.7.0.dist-info/RECORD +0 -24
- {cmd2-2.7.0.dist-info → cmd2-3.0.0b1.dist-info}/WHEEL +0 -0
- {cmd2-2.7.0.dist-info → cmd2-3.0.0b1.dist-info}/licenses/LICENSE +0 -0
- {cmd2-2.7.0.dist-info → cmd2-3.0.0b1.dist-info}/top_level.txt +0 -0
cmd2/table_creator.py
DELETED
@@ -1,1122 +0,0 @@
|
|
1
|
-
"""cmd2 table creation API.
|
2
|
-
|
3
|
-
This API is built upon two core classes: Column and TableCreator
|
4
|
-
The general use case is to inherit from TableCreator to create a table class with custom formatting options.
|
5
|
-
There are already implemented and ready-to-use examples of this below TableCreator's code.
|
6
|
-
"""
|
7
|
-
|
8
|
-
import copy
|
9
|
-
import io
|
10
|
-
from collections import (
|
11
|
-
deque,
|
12
|
-
)
|
13
|
-
from collections.abc import Sequence
|
14
|
-
from enum import (
|
15
|
-
Enum,
|
16
|
-
)
|
17
|
-
from typing import (
|
18
|
-
Any,
|
19
|
-
Optional,
|
20
|
-
)
|
21
|
-
|
22
|
-
from wcwidth import ( # type: ignore[import]
|
23
|
-
wcwidth,
|
24
|
-
)
|
25
|
-
|
26
|
-
from . import (
|
27
|
-
ansi,
|
28
|
-
constants,
|
29
|
-
utils,
|
30
|
-
)
|
31
|
-
|
32
|
-
# Constants
|
33
|
-
EMPTY = ''
|
34
|
-
SPACE = ' '
|
35
|
-
|
36
|
-
|
37
|
-
class HorizontalAlignment(Enum):
|
38
|
-
"""Horizontal alignment of text in a cell."""
|
39
|
-
|
40
|
-
LEFT = 1
|
41
|
-
CENTER = 2
|
42
|
-
RIGHT = 3
|
43
|
-
|
44
|
-
|
45
|
-
class VerticalAlignment(Enum):
|
46
|
-
"""Vertical alignment of text in a cell."""
|
47
|
-
|
48
|
-
TOP = 1
|
49
|
-
MIDDLE = 2
|
50
|
-
BOTTOM = 3
|
51
|
-
|
52
|
-
|
53
|
-
class Column:
|
54
|
-
"""Table column configuration."""
|
55
|
-
|
56
|
-
def __init__(
|
57
|
-
self,
|
58
|
-
header: str,
|
59
|
-
*,
|
60
|
-
width: Optional[int] = None,
|
61
|
-
header_horiz_align: HorizontalAlignment = HorizontalAlignment.LEFT,
|
62
|
-
header_vert_align: VerticalAlignment = VerticalAlignment.BOTTOM,
|
63
|
-
style_header_text: bool = True,
|
64
|
-
data_horiz_align: HorizontalAlignment = HorizontalAlignment.LEFT,
|
65
|
-
data_vert_align: VerticalAlignment = VerticalAlignment.TOP,
|
66
|
-
style_data_text: bool = True,
|
67
|
-
max_data_lines: float = constants.INFINITY,
|
68
|
-
) -> None:
|
69
|
-
"""Column initializer.
|
70
|
-
|
71
|
-
:param header: label for column header
|
72
|
-
:param width: display width of column. This does not account for any borders or padding which
|
73
|
-
may be added (e.g pre_line, inter_cell, and post_line). Header and data text wrap within
|
74
|
-
this width using word-based wrapping (defaults to actual width of header or 1 if header is blank)
|
75
|
-
:param header_horiz_align: horizontal alignment of header cells (defaults to left)
|
76
|
-
:param header_vert_align: vertical alignment of header cells (defaults to bottom)
|
77
|
-
:param style_header_text: if True, then the table is allowed to apply styles to the header text, which may
|
78
|
-
conflict with any styles the header already has. If False, the header is printed as is.
|
79
|
-
Table classes which apply style to headers must account for the value of this flag.
|
80
|
-
(defaults to True)
|
81
|
-
:param data_horiz_align: horizontal alignment of data cells (defaults to left)
|
82
|
-
:param data_vert_align: vertical alignment of data cells (defaults to top)
|
83
|
-
:param style_data_text: if True, then the table is allowed to apply styles to the data text, which may
|
84
|
-
conflict with any styles the data already has. If False, the data is printed as is.
|
85
|
-
Table classes which apply style to data must account for the value of this flag.
|
86
|
-
(defaults to True)
|
87
|
-
:param max_data_lines: maximum lines allowed in a data cell. If line count exceeds this, then the final
|
88
|
-
line displayed will be truncated with an ellipsis. (defaults to INFINITY)
|
89
|
-
:raises ValueError: if width is less than 1
|
90
|
-
:raises ValueError: if max_data_lines is less than 1
|
91
|
-
"""
|
92
|
-
self.header = header
|
93
|
-
|
94
|
-
if width is not None and width < 1:
|
95
|
-
raise ValueError("Column width cannot be less than 1")
|
96
|
-
self.width: int = width if width is not None else -1
|
97
|
-
|
98
|
-
self.header_horiz_align = header_horiz_align
|
99
|
-
self.header_vert_align = header_vert_align
|
100
|
-
self.style_header_text = style_header_text
|
101
|
-
|
102
|
-
self.data_horiz_align = data_horiz_align
|
103
|
-
self.data_vert_align = data_vert_align
|
104
|
-
self.style_data_text = style_data_text
|
105
|
-
|
106
|
-
if max_data_lines < 1:
|
107
|
-
raise ValueError("Max data lines cannot be less than 1")
|
108
|
-
|
109
|
-
self.max_data_lines = max_data_lines
|
110
|
-
|
111
|
-
|
112
|
-
class TableCreator:
|
113
|
-
"""Base table creation class.
|
114
|
-
|
115
|
-
This class handles ANSI style sequences and characters with display widths greater than 1
|
116
|
-
when performing width calculations. It was designed with the ability to build tables one row at a time. This helps
|
117
|
-
when you have large data sets that you don't want to hold in memory or when you receive portions of the data set
|
118
|
-
incrementally.
|
119
|
-
|
120
|
-
TableCreator has one public method: generate_row()
|
121
|
-
|
122
|
-
This function and the Column class provide all features needed to build tables with headers, borders, colors,
|
123
|
-
horizontal and vertical alignment, and wrapped text. However, it's generally easier to inherit from this class and
|
124
|
-
implement a more granular API rather than use TableCreator directly. There are ready-to-use examples of this
|
125
|
-
defined after this class.
|
126
|
-
"""
|
127
|
-
|
128
|
-
def __init__(self, cols: Sequence[Column], *, tab_width: int = 4) -> None:
|
129
|
-
"""TableCreator initializer.
|
130
|
-
|
131
|
-
:param cols: column definitions for this table
|
132
|
-
:param tab_width: all tabs will be replaced with this many spaces. If a row's fill_char is a tab,
|
133
|
-
then it will be converted to one space.
|
134
|
-
:raises ValueError: if tab_width is less than 1
|
135
|
-
"""
|
136
|
-
if tab_width < 1:
|
137
|
-
raise ValueError("Tab width cannot be less than 1")
|
138
|
-
|
139
|
-
self.cols = copy.copy(cols)
|
140
|
-
self.tab_width = tab_width
|
141
|
-
|
142
|
-
for col in self.cols:
|
143
|
-
# Replace tabs before calculating width of header strings
|
144
|
-
col.header = col.header.replace('\t', SPACE * self.tab_width)
|
145
|
-
|
146
|
-
# For headers with the width not yet set, use the width of the
|
147
|
-
# widest line in the header or 1 if the header has no width
|
148
|
-
if col.width <= 0:
|
149
|
-
col.width = max(1, ansi.widest_line(col.header))
|
150
|
-
|
151
|
-
@staticmethod
|
152
|
-
def _wrap_long_word(word: str, max_width: int, max_lines: float, is_last_word: bool) -> tuple[str, int, int]:
|
153
|
-
"""Wrap a long word over multiple lines, used by _wrap_text().
|
154
|
-
|
155
|
-
:param word: word being wrapped
|
156
|
-
:param max_width: maximum display width of a line
|
157
|
-
:param max_lines: maximum lines to wrap before ending the last line displayed with an ellipsis
|
158
|
-
:param is_last_word: True if this is the last word of the total text being wrapped
|
159
|
-
:return: Tuple(wrapped text, lines used, display width of last line)
|
160
|
-
"""
|
161
|
-
styles_dict = utils.get_styles_dict(word)
|
162
|
-
wrapped_buf = io.StringIO()
|
163
|
-
|
164
|
-
# How many lines we've used
|
165
|
-
total_lines = 1
|
166
|
-
|
167
|
-
# Display width of the current line we are building
|
168
|
-
cur_line_width = 0
|
169
|
-
|
170
|
-
char_index = 0
|
171
|
-
while char_index < len(word):
|
172
|
-
# We've reached the last line. Let truncate_line do the rest.
|
173
|
-
if total_lines == max_lines:
|
174
|
-
# If this isn't the last word, but it's gonna fill the final line, then force truncate_line
|
175
|
-
# to place an ellipsis at the end of it by making the word too wide.
|
176
|
-
remaining_word = word[char_index:]
|
177
|
-
if not is_last_word and ansi.style_aware_wcswidth(remaining_word) == max_width:
|
178
|
-
remaining_word += "EXTRA"
|
179
|
-
|
180
|
-
truncated_line = utils.truncate_line(remaining_word, max_width)
|
181
|
-
cur_line_width = ansi.style_aware_wcswidth(truncated_line)
|
182
|
-
wrapped_buf.write(truncated_line)
|
183
|
-
break
|
184
|
-
|
185
|
-
# Check if we're at a style sequence. These don't count toward display width.
|
186
|
-
if char_index in styles_dict:
|
187
|
-
wrapped_buf.write(styles_dict[char_index])
|
188
|
-
char_index += len(styles_dict[char_index])
|
189
|
-
continue
|
190
|
-
|
191
|
-
cur_char = word[char_index]
|
192
|
-
cur_char_width = wcwidth(cur_char)
|
193
|
-
|
194
|
-
if cur_char_width > max_width:
|
195
|
-
# We have a case where the character is wider than max_width. This can happen if max_width
|
196
|
-
# is 1 and the text contains wide characters (e.g. East Asian). Replace it with an ellipsis.
|
197
|
-
cur_char = constants.HORIZONTAL_ELLIPSIS
|
198
|
-
cur_char_width = wcwidth(cur_char)
|
199
|
-
|
200
|
-
if cur_line_width + cur_char_width > max_width:
|
201
|
-
# Adding this char will exceed the max_width. Start a new line.
|
202
|
-
wrapped_buf.write('\n')
|
203
|
-
total_lines += 1
|
204
|
-
cur_line_width = 0
|
205
|
-
continue
|
206
|
-
|
207
|
-
# Add this character and move to the next one
|
208
|
-
cur_line_width += cur_char_width
|
209
|
-
wrapped_buf.write(cur_char)
|
210
|
-
char_index += 1
|
211
|
-
|
212
|
-
return wrapped_buf.getvalue(), total_lines, cur_line_width
|
213
|
-
|
214
|
-
@staticmethod
|
215
|
-
def _wrap_text(text: str, max_width: int, max_lines: float) -> str:
|
216
|
-
"""Wrap text into lines with a display width no longer than max_width.
|
217
|
-
|
218
|
-
This function breaks words on whitespace boundaries. If a word is longer than the space remaining on a line,
|
219
|
-
then it will start on a new line. ANSI escape sequences do not count toward the width of a line.
|
220
|
-
|
221
|
-
:param text: text to be wrapped
|
222
|
-
:param max_width: maximum display width of a line
|
223
|
-
:param max_lines: maximum lines to wrap before ending the last line displayed with an ellipsis
|
224
|
-
:return: wrapped text
|
225
|
-
"""
|
226
|
-
# MyPy Issue #7057 documents regression requiring nonlocals to be defined earlier
|
227
|
-
cur_line_width = 0
|
228
|
-
total_lines = 0
|
229
|
-
|
230
|
-
def add_word(word_to_add: str, is_last_word: bool) -> None:
|
231
|
-
"""Aadd a word to the wrapped text, called from loop.
|
232
|
-
|
233
|
-
:param word_to_add: the word being added
|
234
|
-
:param is_last_word: True if this is the last word of the total text being wrapped
|
235
|
-
"""
|
236
|
-
nonlocal cur_line_width
|
237
|
-
nonlocal total_lines
|
238
|
-
|
239
|
-
# No more space to add word
|
240
|
-
if total_lines == max_lines and cur_line_width == max_width:
|
241
|
-
return
|
242
|
-
|
243
|
-
word_width = ansi.style_aware_wcswidth(word_to_add)
|
244
|
-
|
245
|
-
# If the word is wider than max width of a line, attempt to start it on its own line and wrap it
|
246
|
-
if word_width > max_width:
|
247
|
-
room_to_add = True
|
248
|
-
|
249
|
-
if cur_line_width > 0:
|
250
|
-
# The current line already has text, check if there is room to create a new line
|
251
|
-
if total_lines < max_lines:
|
252
|
-
wrapped_buf.write('\n')
|
253
|
-
total_lines += 1
|
254
|
-
else:
|
255
|
-
# We will truncate this word on the remaining line
|
256
|
-
room_to_add = False
|
257
|
-
|
258
|
-
if room_to_add:
|
259
|
-
wrapped_word, lines_used, cur_line_width = TableCreator._wrap_long_word(
|
260
|
-
word_to_add, max_width, max_lines - total_lines + 1, is_last_word
|
261
|
-
)
|
262
|
-
# Write the word to the buffer
|
263
|
-
wrapped_buf.write(wrapped_word)
|
264
|
-
total_lines += lines_used - 1
|
265
|
-
return
|
266
|
-
|
267
|
-
# We aren't going to wrap the word across multiple lines
|
268
|
-
remaining_width = max_width - cur_line_width
|
269
|
-
|
270
|
-
# Check if we need to start a new line
|
271
|
-
if word_width > remaining_width and total_lines < max_lines:
|
272
|
-
# Save the last character in wrapped_buf, which can't be empty at this point.
|
273
|
-
seek_pos = wrapped_buf.tell() - 1
|
274
|
-
wrapped_buf.seek(seek_pos)
|
275
|
-
last_char = wrapped_buf.read()
|
276
|
-
|
277
|
-
wrapped_buf.write('\n')
|
278
|
-
total_lines += 1
|
279
|
-
cur_line_width = 0
|
280
|
-
remaining_width = max_width
|
281
|
-
|
282
|
-
# Only when a space is following a space do we want to start the next line with it.
|
283
|
-
if word_to_add == SPACE and last_char != SPACE:
|
284
|
-
return
|
285
|
-
|
286
|
-
# Check if we've hit the last line we're allowed to create
|
287
|
-
if total_lines == max_lines:
|
288
|
-
# If this word won't fit, truncate it
|
289
|
-
if word_width > remaining_width:
|
290
|
-
word_to_add = utils.truncate_line(word_to_add, remaining_width)
|
291
|
-
word_width = remaining_width
|
292
|
-
|
293
|
-
# If this isn't the last word, but it's gonna fill the final line, then force truncate_line
|
294
|
-
# to place an ellipsis at the end of it by making the word too wide.
|
295
|
-
elif not is_last_word and word_width == remaining_width:
|
296
|
-
word_to_add = utils.truncate_line(word_to_add + "EXTRA", remaining_width)
|
297
|
-
|
298
|
-
cur_line_width += word_width
|
299
|
-
wrapped_buf.write(word_to_add)
|
300
|
-
|
301
|
-
############################################################################################################
|
302
|
-
# _wrap_text() main code
|
303
|
-
############################################################################################################
|
304
|
-
# Buffer of the wrapped text
|
305
|
-
wrapped_buf = io.StringIO()
|
306
|
-
|
307
|
-
# How many lines we've used
|
308
|
-
total_lines = 0
|
309
|
-
|
310
|
-
# Respect the existing line breaks
|
311
|
-
data_str_lines = text.splitlines()
|
312
|
-
for data_line_index, data_line in enumerate(data_str_lines):
|
313
|
-
total_lines += 1
|
314
|
-
|
315
|
-
if data_line_index > 0:
|
316
|
-
wrapped_buf.write('\n')
|
317
|
-
|
318
|
-
# If the last line is empty, then add a newline and stop
|
319
|
-
if data_line_index == len(data_str_lines) - 1 and not data_line:
|
320
|
-
wrapped_buf.write('\n')
|
321
|
-
break
|
322
|
-
|
323
|
-
# Locate the styles in this line
|
324
|
-
styles_dict = utils.get_styles_dict(data_line)
|
325
|
-
|
326
|
-
# Display width of the current line we are building
|
327
|
-
cur_line_width = 0
|
328
|
-
|
329
|
-
# Current word being built
|
330
|
-
cur_word_buf = io.StringIO()
|
331
|
-
|
332
|
-
char_index = 0
|
333
|
-
while char_index < len(data_line):
|
334
|
-
if total_lines == max_lines and cur_line_width == max_width:
|
335
|
-
break
|
336
|
-
|
337
|
-
# Check if we're at a style sequence. These don't count toward display width.
|
338
|
-
if char_index in styles_dict:
|
339
|
-
cur_word_buf.write(styles_dict[char_index])
|
340
|
-
char_index += len(styles_dict[char_index])
|
341
|
-
continue
|
342
|
-
|
343
|
-
cur_char = data_line[char_index]
|
344
|
-
if cur_char == SPACE:
|
345
|
-
# If we've reached the end of a word, then add the word to the wrapped text
|
346
|
-
if cur_word_buf.tell() > 0:
|
347
|
-
# is_last_word is False since there is a space after the word
|
348
|
-
add_word(cur_word_buf.getvalue(), is_last_word=False)
|
349
|
-
cur_word_buf = io.StringIO()
|
350
|
-
|
351
|
-
# Add the space to the wrapped text
|
352
|
-
last_word = data_line_index == len(data_str_lines) - 1 and char_index == len(data_line) - 1
|
353
|
-
add_word(cur_char, last_word)
|
354
|
-
else:
|
355
|
-
# Add this character to the word buffer
|
356
|
-
cur_word_buf.write(cur_char)
|
357
|
-
|
358
|
-
char_index += 1
|
359
|
-
|
360
|
-
# Add the final word of this line if it's been started
|
361
|
-
if cur_word_buf.tell() > 0:
|
362
|
-
last_word = data_line_index == len(data_str_lines) - 1 and char_index == len(data_line)
|
363
|
-
add_word(cur_word_buf.getvalue(), last_word)
|
364
|
-
|
365
|
-
# Stop line loop if we've written to max_lines
|
366
|
-
if total_lines == max_lines:
|
367
|
-
# If this isn't the last data line and there is space
|
368
|
-
# left on the final wrapped line, then add an ellipsis
|
369
|
-
if data_line_index < len(data_str_lines) - 1 and cur_line_width < max_width:
|
370
|
-
wrapped_buf.write(constants.HORIZONTAL_ELLIPSIS)
|
371
|
-
break
|
372
|
-
|
373
|
-
return wrapped_buf.getvalue()
|
374
|
-
|
375
|
-
def _generate_cell_lines(self, cell_data: Any, is_header: bool, col: Column, fill_char: str) -> tuple[deque[str], int]:
|
376
|
-
"""Generate the lines of a table cell.
|
377
|
-
|
378
|
-
:param cell_data: data to be included in cell
|
379
|
-
:param is_header: True if writing a header cell, otherwise writing a data cell. This determines whether to
|
380
|
-
use header or data alignment settings as well as maximum lines to wrap.
|
381
|
-
:param col: Column definition for this cell
|
382
|
-
:param fill_char: character that fills remaining space in a cell. If your text has a background color,
|
383
|
-
then give fill_char the same background color. (Cannot be a line breaking character)
|
384
|
-
:return: Tuple(deque of cell lines, display width of the cell)
|
385
|
-
"""
|
386
|
-
# Convert data to string and replace tabs with spaces
|
387
|
-
data_str = str(cell_data).replace('\t', SPACE * self.tab_width)
|
388
|
-
|
389
|
-
# Wrap text in this cell
|
390
|
-
max_lines = constants.INFINITY if is_header else col.max_data_lines
|
391
|
-
wrapped_text = self._wrap_text(data_str, col.width, max_lines)
|
392
|
-
|
393
|
-
# Align the text horizontally
|
394
|
-
horiz_alignment = col.header_horiz_align if is_header else col.data_horiz_align
|
395
|
-
if horiz_alignment == HorizontalAlignment.LEFT:
|
396
|
-
text_alignment = utils.TextAlignment.LEFT
|
397
|
-
elif horiz_alignment == HorizontalAlignment.CENTER:
|
398
|
-
text_alignment = utils.TextAlignment.CENTER
|
399
|
-
else:
|
400
|
-
text_alignment = utils.TextAlignment.RIGHT
|
401
|
-
|
402
|
-
aligned_text = utils.align_text(wrapped_text, fill_char=fill_char, width=col.width, alignment=text_alignment)
|
403
|
-
|
404
|
-
# Calculate cell_width first to avoid having 2 copies of aligned_text.splitlines() in memory
|
405
|
-
cell_width = ansi.widest_line(aligned_text)
|
406
|
-
lines = deque(aligned_text.splitlines())
|
407
|
-
|
408
|
-
return lines, cell_width
|
409
|
-
|
410
|
-
def generate_row(
|
411
|
-
self,
|
412
|
-
row_data: Sequence[Any],
|
413
|
-
is_header: bool,
|
414
|
-
*,
|
415
|
-
fill_char: str = SPACE,
|
416
|
-
pre_line: str = EMPTY,
|
417
|
-
inter_cell: str = (2 * SPACE),
|
418
|
-
post_line: str = EMPTY,
|
419
|
-
) -> str:
|
420
|
-
"""Generate a header or data table row.
|
421
|
-
|
422
|
-
:param row_data: data with an entry for each column in the row
|
423
|
-
:param is_header: True if writing a header cell, otherwise writing a data cell. This determines whether to
|
424
|
-
use header or data alignment settings as well as maximum lines to wrap.
|
425
|
-
:param fill_char: character that fills remaining space in a cell. Defaults to space. If this is a tab,
|
426
|
-
then it will be converted to one space. (Cannot be a line breaking character)
|
427
|
-
:param pre_line: string to print before each line of a row. This can be used for a left row border and
|
428
|
-
padding before the first cell's text. (Defaults to blank)
|
429
|
-
:param inter_cell: string to print where two cells meet. This can be used for a border between cells and padding
|
430
|
-
between it and the 2 cells' text. (Defaults to 2 spaces)
|
431
|
-
:param post_line: string to print after each line of a row. This can be used for padding after
|
432
|
-
the last cell's text and a right row border. (Defaults to blank)
|
433
|
-
:return: row string
|
434
|
-
:raises ValueError: if row_data isn't the same length as self.cols
|
435
|
-
:raises TypeError: if fill_char is more than one character (not including ANSI style sequences)
|
436
|
-
:raises ValueError: if fill_char, pre_line, inter_cell, or post_line contains an unprintable
|
437
|
-
character like a newline
|
438
|
-
"""
|
439
|
-
|
440
|
-
class Cell:
|
441
|
-
"""Inner class which represents a table cell."""
|
442
|
-
|
443
|
-
def __init__(self) -> None:
|
444
|
-
# Data in this cell split into individual lines
|
445
|
-
self.lines: deque[str] = deque()
|
446
|
-
|
447
|
-
# Display width of this cell
|
448
|
-
self.width = 0
|
449
|
-
|
450
|
-
if len(row_data) != len(self.cols):
|
451
|
-
raise ValueError("Length of row_data must match length of cols")
|
452
|
-
|
453
|
-
# Replace tabs (tabs in data strings will be handled in _generate_cell_lines())
|
454
|
-
fill_char = fill_char.replace('\t', SPACE)
|
455
|
-
pre_line = pre_line.replace('\t', SPACE * self.tab_width)
|
456
|
-
inter_cell = inter_cell.replace('\t', SPACE * self.tab_width)
|
457
|
-
post_line = post_line.replace('\t', SPACE * self.tab_width)
|
458
|
-
|
459
|
-
# Validate fill_char character count
|
460
|
-
if len(ansi.strip_style(fill_char)) != 1:
|
461
|
-
raise TypeError("Fill character must be exactly one character long")
|
462
|
-
|
463
|
-
# Look for unprintable characters
|
464
|
-
validation_dict = {'fill_char': fill_char, 'pre_line': pre_line, 'inter_cell': inter_cell, 'post_line': post_line}
|
465
|
-
for key, val in validation_dict.items():
|
466
|
-
if ansi.style_aware_wcswidth(val) == -1:
|
467
|
-
raise ValueError(f"{key} contains an unprintable character")
|
468
|
-
|
469
|
-
# Number of lines this row uses
|
470
|
-
total_lines = 0
|
471
|
-
|
472
|
-
# Generate the cells for this row
|
473
|
-
cells = []
|
474
|
-
|
475
|
-
for col_index, col in enumerate(self.cols):
|
476
|
-
cell = Cell()
|
477
|
-
cell.lines, cell.width = self._generate_cell_lines(row_data[col_index], is_header, col, fill_char)
|
478
|
-
cells.append(cell)
|
479
|
-
total_lines = max(len(cell.lines), total_lines)
|
480
|
-
|
481
|
-
row_buf = io.StringIO()
|
482
|
-
|
483
|
-
# Vertically align each cell
|
484
|
-
for cell_index, cell in enumerate(cells):
|
485
|
-
col = self.cols[cell_index]
|
486
|
-
vert_align = col.header_vert_align if is_header else col.data_vert_align
|
487
|
-
|
488
|
-
# Check if this cell need vertical filler
|
489
|
-
line_diff = total_lines - len(cell.lines)
|
490
|
-
if line_diff == 0:
|
491
|
-
continue
|
492
|
-
|
493
|
-
# Add vertical filler lines
|
494
|
-
padding_line = utils.align_left(EMPTY, fill_char=fill_char, width=cell.width)
|
495
|
-
if vert_align == VerticalAlignment.TOP:
|
496
|
-
to_top = 0
|
497
|
-
to_bottom = line_diff
|
498
|
-
elif vert_align == VerticalAlignment.MIDDLE:
|
499
|
-
to_top = line_diff // 2
|
500
|
-
to_bottom = line_diff - to_top
|
501
|
-
else:
|
502
|
-
to_top = line_diff
|
503
|
-
to_bottom = 0
|
504
|
-
|
505
|
-
for _ in range(to_top):
|
506
|
-
cell.lines.appendleft(padding_line)
|
507
|
-
for _ in range(to_bottom):
|
508
|
-
cell.lines.append(padding_line)
|
509
|
-
|
510
|
-
# Build this row one line at a time
|
511
|
-
for line_index in range(total_lines):
|
512
|
-
for cell_index, cell in enumerate(cells):
|
513
|
-
if cell_index == 0:
|
514
|
-
row_buf.write(pre_line)
|
515
|
-
|
516
|
-
row_buf.write(cell.lines[line_index])
|
517
|
-
|
518
|
-
if cell_index < len(self.cols) - 1:
|
519
|
-
row_buf.write(inter_cell)
|
520
|
-
if cell_index == len(self.cols) - 1:
|
521
|
-
row_buf.write(post_line)
|
522
|
-
|
523
|
-
# Add a newline if this is not the last line
|
524
|
-
if line_index < total_lines - 1:
|
525
|
-
row_buf.write('\n')
|
526
|
-
|
527
|
-
return row_buf.getvalue()
|
528
|
-
|
529
|
-
|
530
|
-
############################################################################################################
|
531
|
-
# The following are implementations of TableCreator which demonstrate how to make various types
|
532
|
-
# of tables. They can be used as-is or serve as inspiration for other custom table classes.
|
533
|
-
############################################################################################################
|
534
|
-
class SimpleTable(TableCreator):
|
535
|
-
"""Implementation of TableCreator which generates a borderless table with an optional divider row after the header.
|
536
|
-
|
537
|
-
This class can be used to create the whole table at once or one row at a time.
|
538
|
-
"""
|
539
|
-
|
540
|
-
def __init__(
|
541
|
-
self,
|
542
|
-
cols: Sequence[Column],
|
543
|
-
*,
|
544
|
-
column_spacing: int = 2,
|
545
|
-
tab_width: int = 4,
|
546
|
-
divider_char: Optional[str] = '-',
|
547
|
-
header_bg: Optional[ansi.BgColor] = None,
|
548
|
-
data_bg: Optional[ansi.BgColor] = None,
|
549
|
-
) -> None:
|
550
|
-
"""SimpleTable initializer.
|
551
|
-
|
552
|
-
:param cols: column definitions for this table
|
553
|
-
:param column_spacing: how many spaces to place between columns. Defaults to 2.
|
554
|
-
:param tab_width: all tabs will be replaced with this many spaces. If a row's fill_char is a tab,
|
555
|
-
then it will be converted to one space.
|
556
|
-
:param divider_char: optional character used to build the header divider row. Set this to blank or None if you don't
|
557
|
-
want a divider row. Defaults to dash. (Cannot be a line breaking character)
|
558
|
-
:param header_bg: optional background color for header cells (defaults to None)
|
559
|
-
:param data_bg: optional background color for data cells (defaults to None)
|
560
|
-
:raises ValueError: if tab_width is less than 1
|
561
|
-
:raises ValueError: if column_spacing is less than 0
|
562
|
-
:raises TypeError: if divider_char is longer than one character
|
563
|
-
:raises ValueError: if divider_char is an unprintable character
|
564
|
-
"""
|
565
|
-
super().__init__(cols, tab_width=tab_width)
|
566
|
-
|
567
|
-
if column_spacing < 0:
|
568
|
-
raise ValueError("Column spacing cannot be less than 0")
|
569
|
-
|
570
|
-
self.column_spacing = column_spacing
|
571
|
-
|
572
|
-
if divider_char == '':
|
573
|
-
divider_char = None
|
574
|
-
|
575
|
-
if divider_char is not None:
|
576
|
-
if len(ansi.strip_style(divider_char)) != 1:
|
577
|
-
raise TypeError("Divider character must be exactly one character long")
|
578
|
-
|
579
|
-
divider_char_width = ansi.style_aware_wcswidth(divider_char)
|
580
|
-
if divider_char_width == -1:
|
581
|
-
raise ValueError("Divider character is an unprintable character")
|
582
|
-
|
583
|
-
self.divider_char = divider_char
|
584
|
-
self.header_bg = header_bg
|
585
|
-
self.data_bg = data_bg
|
586
|
-
|
587
|
-
def apply_header_bg(self, value: Any) -> str:
|
588
|
-
"""If defined, apply the header background color to header text.
|
589
|
-
|
590
|
-
:param value: object whose text is to be colored
|
591
|
-
:return: formatted text.
|
592
|
-
"""
|
593
|
-
if self.header_bg is None:
|
594
|
-
return str(value)
|
595
|
-
return ansi.style(value, bg=self.header_bg)
|
596
|
-
|
597
|
-
def apply_data_bg(self, value: Any) -> str:
|
598
|
-
"""If defined, apply the data background color to data text.
|
599
|
-
|
600
|
-
:param value: object whose text is to be colored
|
601
|
-
:return: formatted data string.
|
602
|
-
"""
|
603
|
-
if self.data_bg is None:
|
604
|
-
return str(value)
|
605
|
-
return ansi.style(value, bg=self.data_bg)
|
606
|
-
|
607
|
-
@classmethod
|
608
|
-
def base_width(cls, num_cols: int, *, column_spacing: int = 2) -> int:
|
609
|
-
"""Calculate the display width required for a table before data is added to it.
|
610
|
-
|
611
|
-
This is useful when determining how wide to make your columns to have a table be a specific width.
|
612
|
-
|
613
|
-
:param num_cols: how many columns the table will have
|
614
|
-
:param column_spacing: how many spaces to place between columns. Defaults to 2.
|
615
|
-
:return: base width
|
616
|
-
:raises ValueError: if column_spacing is less than 0
|
617
|
-
:raises ValueError: if num_cols is less than 1
|
618
|
-
"""
|
619
|
-
if num_cols < 1:
|
620
|
-
raise ValueError("Column count cannot be less than 1")
|
621
|
-
|
622
|
-
data_str = SPACE
|
623
|
-
data_width = ansi.style_aware_wcswidth(data_str) * num_cols
|
624
|
-
|
625
|
-
tbl = cls([Column(data_str)] * num_cols, column_spacing=column_spacing)
|
626
|
-
data_row = tbl.generate_data_row([data_str] * num_cols)
|
627
|
-
|
628
|
-
return ansi.style_aware_wcswidth(data_row) - data_width
|
629
|
-
|
630
|
-
def total_width(self) -> int:
|
631
|
-
"""Calculate the total display width of this table."""
|
632
|
-
base_width = self.base_width(len(self.cols), column_spacing=self.column_spacing)
|
633
|
-
data_width = sum(col.width for col in self.cols)
|
634
|
-
return base_width + data_width
|
635
|
-
|
636
|
-
def generate_header(self) -> str:
|
637
|
-
"""Generate table header with an optional divider row."""
|
638
|
-
header_buf = io.StringIO()
|
639
|
-
|
640
|
-
fill_char = self.apply_header_bg(SPACE)
|
641
|
-
inter_cell = self.apply_header_bg(self.column_spacing * SPACE)
|
642
|
-
|
643
|
-
# Apply background color to header text in Columns which allow it
|
644
|
-
to_display: list[Any] = []
|
645
|
-
for col in self.cols:
|
646
|
-
if col.style_header_text:
|
647
|
-
to_display.append(self.apply_header_bg(col.header))
|
648
|
-
else:
|
649
|
-
to_display.append(col.header)
|
650
|
-
|
651
|
-
# Create the header labels
|
652
|
-
header_labels = self.generate_row(to_display, is_header=True, fill_char=fill_char, inter_cell=inter_cell)
|
653
|
-
header_buf.write(header_labels)
|
654
|
-
|
655
|
-
# Add the divider if necessary
|
656
|
-
divider = self.generate_divider()
|
657
|
-
if divider:
|
658
|
-
header_buf.write('\n' + divider)
|
659
|
-
|
660
|
-
return header_buf.getvalue()
|
661
|
-
|
662
|
-
def generate_divider(self) -> str:
|
663
|
-
"""Generate divider row."""
|
664
|
-
if self.divider_char is None:
|
665
|
-
return ''
|
666
|
-
|
667
|
-
return utils.align_left('', fill_char=self.divider_char, width=self.total_width())
|
668
|
-
|
669
|
-
def generate_data_row(self, row_data: Sequence[Any]) -> str:
|
670
|
-
"""Generate a data row.
|
671
|
-
|
672
|
-
:param row_data: data with an entry for each column in the row
|
673
|
-
:return: data row string
|
674
|
-
:raises ValueError: if row_data isn't the same length as self.cols
|
675
|
-
"""
|
676
|
-
if len(row_data) != len(self.cols):
|
677
|
-
raise ValueError("Length of row_data must match length of cols")
|
678
|
-
|
679
|
-
fill_char = self.apply_data_bg(SPACE)
|
680
|
-
inter_cell = self.apply_data_bg(self.column_spacing * SPACE)
|
681
|
-
|
682
|
-
# Apply background color to data text in Columns which allow it
|
683
|
-
to_display: list[Any] = []
|
684
|
-
for index, col in enumerate(self.cols):
|
685
|
-
if col.style_data_text:
|
686
|
-
to_display.append(self.apply_data_bg(row_data[index]))
|
687
|
-
else:
|
688
|
-
to_display.append(row_data[index])
|
689
|
-
|
690
|
-
return self.generate_row(to_display, is_header=False, fill_char=fill_char, inter_cell=inter_cell)
|
691
|
-
|
692
|
-
def generate_table(self, table_data: Sequence[Sequence[Any]], *, include_header: bool = True, row_spacing: int = 1) -> str:
|
693
|
-
"""Generate a table from a data set.
|
694
|
-
|
695
|
-
:param table_data: Data with an entry for each data row of the table. Each entry should have data for
|
696
|
-
each column in the row.
|
697
|
-
:param include_header: If True, then a header will be included at top of table. (Defaults to True)
|
698
|
-
:param row_spacing: A number 0 or greater specifying how many blank lines to place between
|
699
|
-
each row (Defaults to 1)
|
700
|
-
:raises ValueError: if row_spacing is less than 0
|
701
|
-
"""
|
702
|
-
if row_spacing < 0:
|
703
|
-
raise ValueError("Row spacing cannot be less than 0")
|
704
|
-
|
705
|
-
table_buf = io.StringIO()
|
706
|
-
|
707
|
-
if include_header:
|
708
|
-
header = self.generate_header()
|
709
|
-
table_buf.write(header)
|
710
|
-
if len(table_data) > 0:
|
711
|
-
table_buf.write('\n')
|
712
|
-
|
713
|
-
row_divider = utils.align_left('', fill_char=self.apply_data_bg(SPACE), width=self.total_width()) + '\n'
|
714
|
-
|
715
|
-
for index, row_data in enumerate(table_data):
|
716
|
-
if index > 0 and row_spacing > 0:
|
717
|
-
table_buf.write(row_spacing * row_divider)
|
718
|
-
|
719
|
-
row = self.generate_data_row(row_data)
|
720
|
-
table_buf.write(row)
|
721
|
-
if index < len(table_data) - 1:
|
722
|
-
table_buf.write('\n')
|
723
|
-
|
724
|
-
return table_buf.getvalue()
|
725
|
-
|
726
|
-
|
727
|
-
class BorderedTable(TableCreator):
|
728
|
-
"""Implementation of TableCreator which generates a table with borders around the table and between rows.
|
729
|
-
|
730
|
-
Borders between columns can also be toggled. This class can be used to create the whole table at once or one row at a time.
|
731
|
-
"""
|
732
|
-
|
733
|
-
def __init__(
|
734
|
-
self,
|
735
|
-
cols: Sequence[Column],
|
736
|
-
*,
|
737
|
-
tab_width: int = 4,
|
738
|
-
column_borders: bool = True,
|
739
|
-
padding: int = 1,
|
740
|
-
border_fg: Optional[ansi.FgColor] = None,
|
741
|
-
border_bg: Optional[ansi.BgColor] = None,
|
742
|
-
header_bg: Optional[ansi.BgColor] = None,
|
743
|
-
data_bg: Optional[ansi.BgColor] = None,
|
744
|
-
) -> None:
|
745
|
-
"""BorderedTable initializer.
|
746
|
-
|
747
|
-
:param cols: column definitions for this table
|
748
|
-
:param tab_width: all tabs will be replaced with this many spaces. If a row's fill_char is a tab,
|
749
|
-
then it will be converted to one space.
|
750
|
-
:param column_borders: if True, borders between columns will be included. This gives the table a grid-like
|
751
|
-
appearance. Turning off column borders results in a unified appearance between
|
752
|
-
a row's cells. (Defaults to True)
|
753
|
-
:param padding: number of spaces between text and left/right borders of cell
|
754
|
-
:param border_fg: optional foreground color for borders (defaults to None)
|
755
|
-
:param border_bg: optional background color for borders (defaults to None)
|
756
|
-
:param header_bg: optional background color for header cells (defaults to None)
|
757
|
-
:param data_bg: optional background color for data cells (defaults to None)
|
758
|
-
:raises ValueError: if tab_width is less than 1
|
759
|
-
:raises ValueError: if padding is less than 0
|
760
|
-
"""
|
761
|
-
super().__init__(cols, tab_width=tab_width)
|
762
|
-
self.empty_data = [EMPTY] * len(self.cols)
|
763
|
-
self.column_borders = column_borders
|
764
|
-
|
765
|
-
if padding < 0:
|
766
|
-
raise ValueError("Padding cannot be less than 0")
|
767
|
-
self.padding = padding
|
768
|
-
|
769
|
-
self.border_fg = border_fg
|
770
|
-
self.border_bg = border_bg
|
771
|
-
self.header_bg = header_bg
|
772
|
-
self.data_bg = data_bg
|
773
|
-
|
774
|
-
def apply_border_color(self, value: Any) -> str:
|
775
|
-
"""If defined, apply the border foreground and background colors.
|
776
|
-
|
777
|
-
:param value: object whose text is to be colored
|
778
|
-
:return: formatted text.
|
779
|
-
"""
|
780
|
-
if self.border_fg is None and self.border_bg is None:
|
781
|
-
return str(value)
|
782
|
-
return ansi.style(value, fg=self.border_fg, bg=self.border_bg)
|
783
|
-
|
784
|
-
def apply_header_bg(self, value: Any) -> str:
|
785
|
-
"""If defined, apply the header background color to header text.
|
786
|
-
|
787
|
-
:param value: object whose text is to be colored
|
788
|
-
:return: formatted text.
|
789
|
-
"""
|
790
|
-
if self.header_bg is None:
|
791
|
-
return str(value)
|
792
|
-
return ansi.style(value, bg=self.header_bg)
|
793
|
-
|
794
|
-
def apply_data_bg(self, value: Any) -> str:
|
795
|
-
"""If defined, apply the data background color to data text.
|
796
|
-
|
797
|
-
:param value: object whose text is to be colored
|
798
|
-
:return: formatted data string.
|
799
|
-
"""
|
800
|
-
if self.data_bg is None:
|
801
|
-
return str(value)
|
802
|
-
return ansi.style(value, bg=self.data_bg)
|
803
|
-
|
804
|
-
@classmethod
|
805
|
-
def base_width(cls, num_cols: int, *, column_borders: bool = True, padding: int = 1) -> int:
|
806
|
-
"""Calculate the display width required for a table before data is added to it.
|
807
|
-
|
808
|
-
This is useful when determining how wide to make your columns to have a table be a specific width.
|
809
|
-
|
810
|
-
:param num_cols: how many columns the table will have
|
811
|
-
:param column_borders: if True, borders between columns will be included in the calculation (Defaults to True)
|
812
|
-
:param padding: number of spaces between text and left/right borders of cell
|
813
|
-
:return: base width
|
814
|
-
:raises ValueError: if num_cols is less than 1
|
815
|
-
"""
|
816
|
-
if num_cols < 1:
|
817
|
-
raise ValueError("Column count cannot be less than 1")
|
818
|
-
|
819
|
-
data_str = SPACE
|
820
|
-
data_width = ansi.style_aware_wcswidth(data_str) * num_cols
|
821
|
-
|
822
|
-
tbl = cls([Column(data_str)] * num_cols, column_borders=column_borders, padding=padding)
|
823
|
-
data_row = tbl.generate_data_row([data_str] * num_cols)
|
824
|
-
|
825
|
-
return ansi.style_aware_wcswidth(data_row) - data_width
|
826
|
-
|
827
|
-
def total_width(self) -> int:
|
828
|
-
"""Calculate the total display width of this table."""
|
829
|
-
base_width = self.base_width(len(self.cols), column_borders=self.column_borders, padding=self.padding)
|
830
|
-
data_width = sum(col.width for col in self.cols)
|
831
|
-
return base_width + data_width
|
832
|
-
|
833
|
-
def generate_table_top_border(self) -> str:
|
834
|
-
"""Generate a border which appears at the top of the header and data section."""
|
835
|
-
fill_char = '═'
|
836
|
-
|
837
|
-
pre_line = '╔' + self.padding * '═'
|
838
|
-
|
839
|
-
inter_cell = self.padding * '═'
|
840
|
-
if self.column_borders:
|
841
|
-
inter_cell += "╤"
|
842
|
-
inter_cell += self.padding * '═'
|
843
|
-
|
844
|
-
post_line = self.padding * '═' + '╗'
|
845
|
-
|
846
|
-
return self.generate_row(
|
847
|
-
self.empty_data,
|
848
|
-
is_header=False,
|
849
|
-
fill_char=self.apply_border_color(fill_char),
|
850
|
-
pre_line=self.apply_border_color(pre_line),
|
851
|
-
inter_cell=self.apply_border_color(inter_cell),
|
852
|
-
post_line=self.apply_border_color(post_line),
|
853
|
-
)
|
854
|
-
|
855
|
-
def generate_header_bottom_border(self) -> str:
|
856
|
-
"""Generate a border which appears at the bottom of the header."""
|
857
|
-
fill_char = '═'
|
858
|
-
|
859
|
-
pre_line = '╠' + self.padding * '═'
|
860
|
-
|
861
|
-
inter_cell = self.padding * '═'
|
862
|
-
if self.column_borders:
|
863
|
-
inter_cell += '╪'
|
864
|
-
inter_cell += self.padding * '═'
|
865
|
-
|
866
|
-
post_line = self.padding * '═' + '╣'
|
867
|
-
|
868
|
-
return self.generate_row(
|
869
|
-
self.empty_data,
|
870
|
-
is_header=False,
|
871
|
-
fill_char=self.apply_border_color(fill_char),
|
872
|
-
pre_line=self.apply_border_color(pre_line),
|
873
|
-
inter_cell=self.apply_border_color(inter_cell),
|
874
|
-
post_line=self.apply_border_color(post_line),
|
875
|
-
)
|
876
|
-
|
877
|
-
def generate_row_bottom_border(self) -> str:
|
878
|
-
"""Generate a border which appears at the bottom of rows."""
|
879
|
-
fill_char = '─'
|
880
|
-
|
881
|
-
pre_line = '╟' + self.padding * '─'
|
882
|
-
|
883
|
-
inter_cell = self.padding * '─'
|
884
|
-
if self.column_borders:
|
885
|
-
inter_cell += '┼'
|
886
|
-
inter_cell += self.padding * '─'
|
887
|
-
|
888
|
-
post_line = self.padding * '─' + '╢'
|
889
|
-
|
890
|
-
return self.generate_row(
|
891
|
-
self.empty_data,
|
892
|
-
is_header=False,
|
893
|
-
fill_char=self.apply_border_color(fill_char),
|
894
|
-
pre_line=self.apply_border_color(pre_line),
|
895
|
-
inter_cell=self.apply_border_color(inter_cell),
|
896
|
-
post_line=self.apply_border_color(post_line),
|
897
|
-
)
|
898
|
-
|
899
|
-
def generate_table_bottom_border(self) -> str:
|
900
|
-
"""Generate a border which appears at the bottom of the table."""
|
901
|
-
fill_char = '═'
|
902
|
-
|
903
|
-
pre_line = '╚' + self.padding * '═'
|
904
|
-
|
905
|
-
inter_cell = self.padding * '═'
|
906
|
-
if self.column_borders:
|
907
|
-
inter_cell += '╧'
|
908
|
-
inter_cell += self.padding * '═'
|
909
|
-
|
910
|
-
post_line = self.padding * '═' + '╝'
|
911
|
-
|
912
|
-
return self.generate_row(
|
913
|
-
self.empty_data,
|
914
|
-
is_header=False,
|
915
|
-
fill_char=self.apply_border_color(fill_char),
|
916
|
-
pre_line=self.apply_border_color(pre_line),
|
917
|
-
inter_cell=self.apply_border_color(inter_cell),
|
918
|
-
post_line=self.apply_border_color(post_line),
|
919
|
-
)
|
920
|
-
|
921
|
-
def generate_header(self) -> str:
|
922
|
-
"""Generate table header."""
|
923
|
-
fill_char = self.apply_header_bg(SPACE)
|
924
|
-
|
925
|
-
pre_line = self.apply_border_color('║') + self.apply_header_bg(self.padding * SPACE)
|
926
|
-
|
927
|
-
inter_cell = self.apply_header_bg(self.padding * SPACE)
|
928
|
-
if self.column_borders:
|
929
|
-
inter_cell += self.apply_border_color('│')
|
930
|
-
inter_cell += self.apply_header_bg(self.padding * SPACE)
|
931
|
-
|
932
|
-
post_line = self.apply_header_bg(self.padding * SPACE) + self.apply_border_color('║')
|
933
|
-
|
934
|
-
# Apply background color to header text in Columns which allow it
|
935
|
-
to_display: list[Any] = []
|
936
|
-
for col in self.cols:
|
937
|
-
if col.style_header_text:
|
938
|
-
to_display.append(self.apply_header_bg(col.header))
|
939
|
-
else:
|
940
|
-
to_display.append(col.header)
|
941
|
-
|
942
|
-
# Create the bordered header
|
943
|
-
header_buf = io.StringIO()
|
944
|
-
header_buf.write(self.generate_table_top_border())
|
945
|
-
header_buf.write('\n')
|
946
|
-
header_buf.write(
|
947
|
-
self.generate_row(
|
948
|
-
to_display, is_header=True, fill_char=fill_char, pre_line=pre_line, inter_cell=inter_cell, post_line=post_line
|
949
|
-
)
|
950
|
-
)
|
951
|
-
header_buf.write('\n')
|
952
|
-
header_buf.write(self.generate_header_bottom_border())
|
953
|
-
|
954
|
-
return header_buf.getvalue()
|
955
|
-
|
956
|
-
def generate_data_row(self, row_data: Sequence[Any]) -> str:
|
957
|
-
"""Generate a data row.
|
958
|
-
|
959
|
-
:param row_data: data with an entry for each column in the row
|
960
|
-
:return: data row string
|
961
|
-
:raises ValueError: if row_data isn't the same length as self.cols
|
962
|
-
"""
|
963
|
-
if len(row_data) != len(self.cols):
|
964
|
-
raise ValueError("Length of row_data must match length of cols")
|
965
|
-
|
966
|
-
fill_char = self.apply_data_bg(SPACE)
|
967
|
-
|
968
|
-
pre_line = self.apply_border_color('║') + self.apply_data_bg(self.padding * SPACE)
|
969
|
-
|
970
|
-
inter_cell = self.apply_data_bg(self.padding * SPACE)
|
971
|
-
if self.column_borders:
|
972
|
-
inter_cell += self.apply_border_color('│')
|
973
|
-
inter_cell += self.apply_data_bg(self.padding * SPACE)
|
974
|
-
|
975
|
-
post_line = self.apply_data_bg(self.padding * SPACE) + self.apply_border_color('║')
|
976
|
-
|
977
|
-
# Apply background color to data text in Columns which allow it
|
978
|
-
to_display: list[Any] = []
|
979
|
-
for index, col in enumerate(self.cols):
|
980
|
-
if col.style_data_text:
|
981
|
-
to_display.append(self.apply_data_bg(row_data[index]))
|
982
|
-
else:
|
983
|
-
to_display.append(row_data[index])
|
984
|
-
|
985
|
-
return self.generate_row(
|
986
|
-
to_display, is_header=False, fill_char=fill_char, pre_line=pre_line, inter_cell=inter_cell, post_line=post_line
|
987
|
-
)
|
988
|
-
|
989
|
-
def generate_table(self, table_data: Sequence[Sequence[Any]], *, include_header: bool = True) -> str:
|
990
|
-
"""Generate a table from a data set.
|
991
|
-
|
992
|
-
:param table_data: Data with an entry for each data row of the table. Each entry should have data for
|
993
|
-
each column in the row.
|
994
|
-
:param include_header: If True, then a header will be included at top of table. (Defaults to True)
|
995
|
-
"""
|
996
|
-
table_buf = io.StringIO()
|
997
|
-
|
998
|
-
if include_header:
|
999
|
-
header = self.generate_header()
|
1000
|
-
table_buf.write(header)
|
1001
|
-
else:
|
1002
|
-
top_border = self.generate_table_top_border()
|
1003
|
-
table_buf.write(top_border)
|
1004
|
-
|
1005
|
-
table_buf.write('\n')
|
1006
|
-
|
1007
|
-
for index, row_data in enumerate(table_data):
|
1008
|
-
if index > 0:
|
1009
|
-
row_bottom_border = self.generate_row_bottom_border()
|
1010
|
-
table_buf.write(row_bottom_border)
|
1011
|
-
table_buf.write('\n')
|
1012
|
-
|
1013
|
-
row = self.generate_data_row(row_data)
|
1014
|
-
table_buf.write(row)
|
1015
|
-
table_buf.write('\n')
|
1016
|
-
|
1017
|
-
table_buf.write(self.generate_table_bottom_border())
|
1018
|
-
return table_buf.getvalue()
|
1019
|
-
|
1020
|
-
|
1021
|
-
class AlternatingTable(BorderedTable):
|
1022
|
-
"""Implementation of BorderedTable which uses background colors to distinguish between rows instead of row border lines.
|
1023
|
-
|
1024
|
-
This class can be used to create the whole table at once or one row at a time.
|
1025
|
-
|
1026
|
-
To nest an AlternatingTable within another AlternatingTable, set style_data_text to False on the Column
|
1027
|
-
which contains the nested table. That will prevent the current row's background color from affecting the colors
|
1028
|
-
of the nested table.
|
1029
|
-
"""
|
1030
|
-
|
1031
|
-
def __init__(
|
1032
|
-
self,
|
1033
|
-
cols: Sequence[Column],
|
1034
|
-
*,
|
1035
|
-
tab_width: int = 4,
|
1036
|
-
column_borders: bool = True,
|
1037
|
-
padding: int = 1,
|
1038
|
-
border_fg: Optional[ansi.FgColor] = None,
|
1039
|
-
border_bg: Optional[ansi.BgColor] = None,
|
1040
|
-
header_bg: Optional[ansi.BgColor] = None,
|
1041
|
-
odd_bg: Optional[ansi.BgColor] = None,
|
1042
|
-
even_bg: Optional[ansi.BgColor] = ansi.Bg.DARK_GRAY,
|
1043
|
-
) -> None:
|
1044
|
-
"""AlternatingTable initializer.
|
1045
|
-
|
1046
|
-
Note: Specify background colors using subclasses of BgColor (e.g. Bg, EightBitBg, RgbBg)
|
1047
|
-
|
1048
|
-
:param cols: column definitions for this table
|
1049
|
-
:param tab_width: all tabs will be replaced with this many spaces. If a row's fill_char is a tab,
|
1050
|
-
then it will be converted to one space.
|
1051
|
-
:param column_borders: if True, borders between columns will be included. This gives the table a grid-like
|
1052
|
-
appearance. Turning off column borders results in a unified appearance between
|
1053
|
-
a row's cells. (Defaults to True)
|
1054
|
-
:param padding: number of spaces between text and left/right borders of cell
|
1055
|
-
:param border_fg: optional foreground color for borders (defaults to None)
|
1056
|
-
:param border_bg: optional background color for borders (defaults to None)
|
1057
|
-
:param header_bg: optional background color for header cells (defaults to None)
|
1058
|
-
:param odd_bg: optional background color for odd numbered data rows (defaults to None)
|
1059
|
-
:param even_bg: optional background color for even numbered data rows (defaults to StdBg.DARK_GRAY)
|
1060
|
-
:raises ValueError: if tab_width is less than 1
|
1061
|
-
:raises ValueError: if padding is less than 0
|
1062
|
-
"""
|
1063
|
-
super().__init__(
|
1064
|
-
cols,
|
1065
|
-
tab_width=tab_width,
|
1066
|
-
column_borders=column_borders,
|
1067
|
-
padding=padding,
|
1068
|
-
border_fg=border_fg,
|
1069
|
-
border_bg=border_bg,
|
1070
|
-
header_bg=header_bg,
|
1071
|
-
)
|
1072
|
-
self.row_num = 1
|
1073
|
-
self.odd_bg = odd_bg
|
1074
|
-
self.even_bg = even_bg
|
1075
|
-
|
1076
|
-
def apply_data_bg(self, value: Any) -> str:
|
1077
|
-
"""Apply background color to data text based on what row is being generated and whether a color has been defined.
|
1078
|
-
|
1079
|
-
:param value: object whose text is to be colored
|
1080
|
-
:return: formatted data string.
|
1081
|
-
"""
|
1082
|
-
if self.row_num % 2 == 0 and self.even_bg is not None:
|
1083
|
-
return ansi.style(value, bg=self.even_bg)
|
1084
|
-
if self.row_num % 2 != 0 and self.odd_bg is not None:
|
1085
|
-
return ansi.style(value, bg=self.odd_bg)
|
1086
|
-
return str(value)
|
1087
|
-
|
1088
|
-
def generate_data_row(self, row_data: Sequence[Any]) -> str:
|
1089
|
-
"""Generate a data row.
|
1090
|
-
|
1091
|
-
:param row_data: data with an entry for each column in the row
|
1092
|
-
:return: data row string
|
1093
|
-
"""
|
1094
|
-
row = super().generate_data_row(row_data)
|
1095
|
-
self.row_num += 1
|
1096
|
-
return row
|
1097
|
-
|
1098
|
-
def generate_table(self, table_data: Sequence[Sequence[Any]], *, include_header: bool = True) -> str:
|
1099
|
-
"""Generate a table from a data set.
|
1100
|
-
|
1101
|
-
:param table_data: Data with an entry for each data row of the table. Each entry should have data for
|
1102
|
-
each column in the row.
|
1103
|
-
:param include_header: If True, then a header will be included at top of table. (Defaults to True)
|
1104
|
-
"""
|
1105
|
-
table_buf = io.StringIO()
|
1106
|
-
|
1107
|
-
if include_header:
|
1108
|
-
header = self.generate_header()
|
1109
|
-
table_buf.write(header)
|
1110
|
-
else:
|
1111
|
-
top_border = self.generate_table_top_border()
|
1112
|
-
table_buf.write(top_border)
|
1113
|
-
|
1114
|
-
table_buf.write('\n')
|
1115
|
-
|
1116
|
-
for row_data in table_data:
|
1117
|
-
row = self.generate_data_row(row_data)
|
1118
|
-
table_buf.write(row)
|
1119
|
-
table_buf.write('\n')
|
1120
|
-
|
1121
|
-
table_buf.write(self.generate_table_bottom_border())
|
1122
|
-
return table_buf.getvalue()
|