3 """Utilities for dealing with "text"."""
8 from collections import defaultdict
9 from typing import Dict, Generator, List, NamedTuple, Optional
11 from ansi import fg, reset
13 logger = logging.getLogger(__file__)
16 class RowsColumns(NamedTuple):
21 def get_console_rows_columns() -> RowsColumns:
22 """Returns the number of rows/columns on the current console."""
24 from exec_utils import cmd
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"
59 print(bar, end=ret, flush=True, file=sys.stderr)
67 fgcolor=fg("school bus yellow"),
72 """Returns a string containing a bar graph.
74 >>> bar_graph(0.5, fgcolor='', reset='')
75 '[███████████████████████████████████ ] 50.0%'
79 if percentage < 0.0 or percentage > 1.0:
80 raise ValueError(percentage)
82 text = f"{percentage*100.0:2.1f}%"
85 whole_width = math.floor(percentage * width)
86 if whole_width == width:
89 elif whole_width == 0 and percentage > 0.0:
92 remainder_width = (percentage * width) % 1
93 part_width = math.floor(remainder_width * 8)
94 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
100 + " " * (width - whole_width - 1)
108 def distribute_strings(
112 alignment: str = "c",
116 Distributes strings into a line with a particular justification.
118 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
120 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
122 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
126 subwidth = math.floor(width / len(strings))
128 for string in strings:
129 string = justify_string(
130 string, width=subwidth, alignment=alignment, padding=padding
133 while len(retval) > width:
134 retval = retval.replace(' ', ' ', 1)
135 while len(retval) < width:
136 retval = retval.replace(' ', ' ', 1)
140 def justify_string_by_chunk(string: str, width: int = 80, padding: str = " ") -> 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)
156 + distribute_strings(rest, width=w, padding=padding)
164 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
168 >>> justify_string('This is another test', width=40, alignment='c')
169 ' This is another test '
170 >>> justify_string('This is another test', width=40, alignment='l')
171 'This is another test '
172 >>> justify_string('This is another test', width=40, alignment='r')
173 ' This is another test'
174 >>> justify_string('This is another test', width=40, alignment='j')
175 'This is another test'
178 alignment = alignment[0]
180 while len(string) < width:
183 elif alignment == "r":
184 string = padding + string
185 elif alignment == "j":
186 return justify_string_by_chunk(string, width=width, padding=padding)
187 elif alignment == "c":
188 if len(string) % 2 == 0:
191 string = padding + string
197 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
201 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
202 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
203 'This is a test of the emergency\\nbroadcast system. This is only a test.'
207 for word in text.split():
208 if len(line) + len(word) > width:
210 line = justify_string(line, width=width, alignment=alignment)
211 retval = retval + "\n" + line
213 line = line + " " + word
215 retval += "\n" + line[1:]
219 def generate_padded_columns(text: List[str]) -> Generator:
220 max_width: Dict[int, int] = defaultdict(int)
222 for pos, word in enumerate(line.split()):
223 max_width[pos] = max(max_width[pos], len(word))
227 for pos, word in enumerate(line.split()):
228 width = max_width[pos]
229 word = justify_string(word, width=width, alignment='l')
234 def wrap_string(text: str, n: int) -> str:
235 chunks = text.split()
239 if width + len(chunk) > n:
243 width += len(chunk) + 1
247 class Indenter(object):
249 with Indenter(pad_count = 8) as i:
260 pad_prefix: Optional[str] = None,
265 if pad_prefix is not None:
266 self.pad_prefix = pad_prefix
269 self.padding = pad_char * pad_count
275 def __exit__(self, exc_type, exc_value, exc_tb):
280 def print(self, *arg, **kwargs):
283 text = string_utils.sprintf(*arg, **kwargs)
284 print(self.pad_prefix + self.padding * self.level + text, end='')
287 def header(title: str, *, width: int = 80, color: str = ''):
289 Returns a nice header line with a title.
291 >>> header('title', width=60, color='')
292 '----[ title ]-----------------------------------------------'
299 right = (w - 4) * '-'
300 if color != '' and color is not None:
304 return f'{left}[ {color}{title}{r} ]{right}'
309 if __name__ == '__main__':