3 """Utilities for dealing with "text"."""
5 from collections import defaultdict
9 from typing import List, NamedTuple, Optional
11 from ansi import fg, reset
14 logger = logging.getLogger(__file__)
17 class RowsColumns(NamedTuple):
22 def get_console_rows_columns() -> RowsColumns:
23 """Returns the number of rows/columns on the current console."""
25 from exec_utils import cmd_with_timeout
27 rows, columns = cmd_with_timeout(
31 except Exception as e:
33 raise Exception('Can\'t determine console size?!')
34 return RowsColumns(int(rows), int(columns))
42 fgcolor=fg("school bus yellow"),
47 """Draws a progress graph."""
49 percent = current / total
50 ret = "\r" if redraw else "\n"
57 right_end = right_end)
70 fgcolor=fg("school bus yellow"),
75 """Returns a string containing a bar graph.
77 >>> bar_graph(0.5, fgcolor='', reset='')
78 '[███████████████████████████████████ ] 50.0%'
82 if percentage < 0.0 or percentage > 1.0:
83 raise ValueError(percentage)
85 text = f"{percentage*100.0:2.1f}%"
88 whole_width = math.floor(percentage * width)
89 if whole_width == width:
93 remainder_width = (percentage * width) % 1
94 part_width = math.floor(remainder_width * 8)
95 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
99 "█" * whole_width + part_char +
100 " " * (width - whole_width - 1) +
106 def distribute_strings(
110 alignment: str = "c",
114 Distributes strings into a line with a particular justification.
116 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
118 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
120 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
124 subwidth = math.floor(width / len(strings))
126 for string in strings:
127 string = justify_string(
128 string, width=subwidth, alignment=alignment, padding=padding
134 def justify_string_by_chunk(
135 string: str, width: int = 80, padding: str = " "
140 >>> justify_string_by_chunk("This is a test", 40)
142 >>> justify_string_by_chunk("This is a test", 20)
147 first, *rest, last = string.split()
148 w = width - (len(first) + 1 + len(last) + 1)
150 first + padding + distribute_strings(rest, width=w, padding=padding)
152 while len(retval) + len(last) < width:
159 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
163 >>> justify_string('This is another test', width=40, alignment='c')
164 ' This is another test '
165 >>> justify_string('This is another test', width=40, alignment='l')
166 'This is another test '
167 >>> justify_string('This is another test', width=40, alignment='r')
168 ' This is another test'
169 >>> justify_string('This is another test', width=40, alignment='j')
170 'This is another test'
173 alignment = alignment[0]
175 while len(string) < width:
178 elif alignment == "r":
179 string = padding + string
180 elif alignment == "j":
181 return justify_string_by_chunk(
186 elif alignment == "c":
187 if len(string) % 2 == 0:
190 string = padding + string
196 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
200 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
201 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
202 'This is a test of the emergency\\nbroadcast system. This is only a test.'
206 for word in text.split():
207 if len(line) + len(word) > width:
209 line = justify_string(line, width=width, alignment=alignment)
210 retval = retval + "\n" + line
212 line = line + " " + word
214 retval += "\n" + line[1:]
218 def generate_padded_columns(text: List[str]) -> str:
219 max_width = defaultdict(int)
221 for pos, word in enumerate(line.split()):
222 max_width[pos] = max(max_width[pos], len(word))
226 for pos, word in enumerate(line.split()):
227 width = max_width[pos]
228 word = justify_string(word, width=width, alignment='l')
233 def wrap_string(text: str, n: int) -> str:
234 chunks = text.split()
238 if width + len(chunk) > n:
242 width += len(chunk) + 1
246 class Indenter(object):
248 with Indenter(pad_count = 8) as i:
257 pad_prefix: Optional[str] = None,
261 if pad_prefix is not None:
262 self.pad_prefix = pad_prefix
265 self.padding = pad_char * pad_count
271 def __exit__(self, exc_type, exc_value, exc_tb):
276 def print(self, *arg, **kwargs):
278 text = string_utils.sprintf(*arg, **kwargs)
279 print(self.pad_prefix + self.padding * self.level + text, end='')
282 def header(title: str, *, width: int = 80, color: str = ''):
284 Returns a nice header line with a title.
286 >>> header('title', width=60, color='')
287 '----[ title ]-----------------------------------------------'
291 w -= (len(title) + 4)
294 right = (w - 4) * '-'
295 if color != '' and color is not None:
299 return f'{left}[ {color}{title}{r} ]{right}'
304 if __name__ == '__main__':