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
28 rows, columns = cmd_with_timeout(
32 except Exception as e:
34 raise Exception('Can\'t determine console size?!')
35 return RowsColumns(int(rows), int(columns))
43 fgcolor=fg("school bus yellow"),
48 """Draws a progress graph."""
50 percent = current / total
51 ret = "\r" if redraw else "\n"
60 print(bar, end=ret, flush=True, file=sys.stderr)
68 fgcolor=fg("school bus yellow"),
73 """Returns a string containing a bar graph.
75 >>> bar_graph(0.5, fgcolor='', reset='')
76 '[███████████████████████████████████ ] 50.0%'
80 if percentage < 0.0 or percentage > 1.0:
81 raise ValueError(percentage)
83 text = f"{percentage*100.0:2.1f}%"
86 whole_width = math.floor(percentage * width)
87 if whole_width == width:
90 elif whole_width == 0 and percentage > 0.0:
93 remainder_width = (percentage * width) % 1
94 part_width = math.floor(remainder_width * 8)
95 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
101 + " " * (width - whole_width - 1)
109 def distribute_strings(
113 alignment: str = "c",
117 Distributes strings into a line with a particular justification.
119 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
121 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
123 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
127 subwidth = math.floor(width / len(strings))
129 for string in strings:
130 string = justify_string(
131 string, width=subwidth, alignment=alignment, padding=padding
134 while len(retval) > width:
135 retval = retval.replace(' ', ' ', 1)
136 while len(retval) < width:
137 retval = retval.replace(' ', ' ', 1)
141 def justify_string_by_chunk(string: str, width: int = 80, padding: str = " ") -> str:
145 >>> justify_string_by_chunk("This is a test", 40)
147 >>> justify_string_by_chunk("This is a test", 20)
152 first, *rest, last = string.split()
153 w = width - (len(first) + 1 + len(last) + 1)
157 + distribute_strings(rest, width=w, padding=padding)
165 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
169 >>> justify_string('This is another test', width=40, alignment='c')
170 ' This is another test '
171 >>> justify_string('This is another test', width=40, alignment='l')
172 'This is another test '
173 >>> justify_string('This is another test', width=40, alignment='r')
174 ' This is another test'
175 >>> justify_string('This is another test', width=40, alignment='j')
176 'This is another test'
179 alignment = alignment[0]
181 while len(string) < width:
184 elif alignment == "r":
185 string = padding + string
186 elif alignment == "j":
187 return justify_string_by_chunk(string, width=width, padding=padding)
188 elif alignment == "c":
189 if len(string) % 2 == 0:
192 string = padding + string
198 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
202 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
203 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
204 'This is a test of the emergency\\nbroadcast system. This is only a test.'
208 for word in text.split():
209 if len(line) + len(word) > width:
211 line = justify_string(line, width=width, alignment=alignment)
212 retval = retval + "\n" + line
214 line = line + " " + word
216 retval += "\n" + line[1:]
220 def generate_padded_columns(text: List[str]) -> str:
221 max_width = defaultdict(int)
223 for pos, word in enumerate(line.split()):
224 max_width[pos] = max(max_width[pos], len(word))
228 for pos, word in enumerate(line.split()):
229 width = max_width[pos]
230 word = justify_string(word, width=width, alignment='l')
235 def wrap_string(text: str, n: int) -> str:
236 chunks = text.split()
240 if width + len(chunk) > n:
244 width += len(chunk) + 1
248 class Indenter(object):
250 with Indenter(pad_count = 8) as i:
261 pad_prefix: Optional[str] = None,
266 if pad_prefix is not None:
267 self.pad_prefix = pad_prefix
270 self.padding = pad_char * pad_count
276 def __exit__(self, exc_type, exc_value, exc_tb):
281 def print(self, *arg, **kwargs):
284 text = string_utils.sprintf(*arg, **kwargs)
285 print(self.pad_prefix + self.padding * self.level + text, end='')
288 def header(title: str, *, width: int = 80, color: str = ''):
290 Returns a nice header line with a title.
292 >>> header('title', width=60, color='')
293 '----[ title ]-----------------------------------------------'
300 right = (w - 4) * '-'
301 if color != '' and color is not None:
305 return f'{left}[ {color}{title}{r} ]{right}'
310 if __name__ == '__main__':