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
131 while(len(retval) > width):
132 retval = retval.replace(' ', ' ', 1)
133 while(len(retval) < width):
134 retval = retval.replace(' ', ' ', 1)
138 def justify_string_by_chunk(
139 string: str, width: int = 80, padding: str = " "
144 >>> justify_string_by_chunk("This is a test", 40)
146 >>> justify_string_by_chunk("This is a test", 20)
151 first, *rest, last = string.split()
152 w = width - (len(first) + 1 + len(last) + 1)
153 ret = first + padding + distribute_strings(rest, width=w, padding=padding) + padding + last
158 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
162 >>> justify_string('This is another test', width=40, alignment='c')
163 ' This is another test '
164 >>> justify_string('This is another test', width=40, alignment='l')
165 'This is another test '
166 >>> justify_string('This is another test', width=40, alignment='r')
167 ' This is another test'
168 >>> justify_string('This is another test', width=40, alignment='j')
169 'This is another test'
172 alignment = alignment[0]
174 while len(string) < width:
177 elif alignment == "r":
178 string = padding + string
179 elif alignment == "j":
180 return justify_string_by_chunk(
185 elif alignment == "c":
186 if len(string) % 2 == 0:
189 string = padding + string
195 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
199 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
200 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
201 'This is a test of the emergency\\nbroadcast system. This is only a test.'
205 for word in text.split():
206 if len(line) + len(word) > width:
208 line = justify_string(line, width=width, alignment=alignment)
209 retval = retval + "\n" + line
211 line = line + " " + word
213 retval += "\n" + line[1:]
217 def generate_padded_columns(text: List[str]) -> str:
218 max_width = defaultdict(int)
220 for pos, word in enumerate(line.split()):
221 max_width[pos] = max(max_width[pos], len(word))
225 for pos, word in enumerate(line.split()):
226 width = max_width[pos]
227 word = justify_string(word, width=width, alignment='l')
232 def wrap_string(text: str, n: int) -> str:
233 chunks = text.split()
237 if width + len(chunk) > n:
241 width += len(chunk) + 1
245 class Indenter(object):
247 with Indenter(pad_count = 8) as i:
256 pad_prefix: Optional[str] = None,
260 if pad_prefix is not None:
261 self.pad_prefix = pad_prefix
264 self.padding = pad_char * pad_count
270 def __exit__(self, exc_type, exc_value, exc_tb):
275 def print(self, *arg, **kwargs):
277 text = string_utils.sprintf(*arg, **kwargs)
278 print(self.pad_prefix + self.padding * self.level + text, end='')
281 def header(title: str, *, width: int = 80, color: str = ''):
283 Returns a nice header line with a title.
285 >>> header('title', width=60, color='')
286 '----[ title ]-----------------------------------------------'
290 w -= (len(title) + 4)
293 right = (w - 4) * '-'
294 if color != '' and color is not None:
298 return f'{left}[ {color}{title}{r} ]{right}'
303 if __name__ == '__main__':