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:
91 remainder_width = (percentage * width) % 1
92 part_width = math.floor(remainder_width * 8)
93 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
99 + " " * (width - whole_width - 1)
107 def distribute_strings(
111 alignment: str = "c",
115 Distributes strings into a line with a particular justification.
117 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
119 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
121 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
125 subwidth = math.floor(width / len(strings))
127 for string in strings:
128 string = justify_string(
129 string, width=subwidth, alignment=alignment, padding=padding
132 while len(retval) > width:
133 retval = retval.replace(' ', ' ', 1)
134 while len(retval) < width:
135 retval = retval.replace(' ', ' ', 1)
139 def justify_string_by_chunk(string: str, width: int = 80, padding: str = " ") -> str:
143 >>> justify_string_by_chunk("This is a test", 40)
145 >>> justify_string_by_chunk("This is a test", 20)
150 first, *rest, last = string.split()
151 w = width - (len(first) + 1 + len(last) + 1)
155 + distribute_strings(rest, width=w, padding=padding)
163 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
167 >>> justify_string('This is another test', width=40, alignment='c')
168 ' This is another test '
169 >>> justify_string('This is another test', width=40, alignment='l')
170 'This is another test '
171 >>> justify_string('This is another test', width=40, alignment='r')
172 ' This is another test'
173 >>> justify_string('This is another test', width=40, alignment='j')
174 'This is another test'
177 alignment = alignment[0]
179 while len(string) < width:
182 elif alignment == "r":
183 string = padding + string
184 elif alignment == "j":
185 return justify_string_by_chunk(string, width=width, padding=padding)
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:
259 pad_prefix: Optional[str] = None,
264 if pad_prefix is not None:
265 self.pad_prefix = pad_prefix
268 self.padding = pad_char * pad_count
274 def __exit__(self, exc_type, exc_value, exc_tb):
279 def print(self, *arg, **kwargs):
282 text = string_utils.sprintf(*arg, **kwargs)
283 print(self.pad_prefix + self.padding * self.level + text, end='')
286 def header(title: str, *, width: int = 80, color: str = ''):
288 Returns a nice header line with a title.
290 >>> header('title', width=60, color='')
291 '----[ title ]-----------------------------------------------'
298 right = (w - 4) * '-'
299 if color != '' and color is not None:
303 return f'{left}[ {color}{title}{r} ]{right}'
308 if __name__ == '__main__':