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(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(string: str, width: int = 80, padding: str = " ") -> str:
142 >>> justify_string_by_chunk("This is a test", 40)
144 >>> justify_string_by_chunk("This is a test", 20)
149 first, *rest, last = string.split()
150 w = width - (len(first) + 1 + len(last) + 1)
151 ret = first + padding + distribute_strings(rest, width=w, padding=padding) + padding + last
156 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
160 >>> justify_string('This is another test', width=40, alignment='c')
161 ' This is another test '
162 >>> justify_string('This is another test', width=40, alignment='l')
163 'This is another test '
164 >>> justify_string('This is another test', width=40, alignment='r')
165 ' This is another test'
166 >>> justify_string('This is another test', width=40, alignment='j')
167 'This is another test'
170 alignment = alignment[0]
172 while len(string) < width:
175 elif alignment == "r":
176 string = padding + string
177 elif alignment == "j":
178 return justify_string_by_chunk(string, width=width, padding=padding)
179 elif alignment == "c":
180 if len(string) % 2 == 0:
183 string = padding + string
189 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
193 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
194 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
195 'This is a test of the emergency\\nbroadcast system. This is only a test.'
199 for word in text.split():
200 if len(line) + len(word) > width:
202 line = justify_string(line, width=width, alignment=alignment)
203 retval = retval + "\n" + line
205 line = line + " " + word
207 retval += "\n" + line[1:]
211 def generate_padded_columns(text: List[str]) -> Generator:
212 max_width: Dict[int, int] = defaultdict(int)
214 for pos, word in enumerate(line.split()):
215 max_width[pos] = max(max_width[pos], len(word))
219 for pos, word in enumerate(line.split()):
220 width = max_width[pos]
221 word = justify_string(word, width=width, alignment='l')
226 def wrap_string(text: str, n: int) -> str:
227 chunks = text.split()
231 if width + len(chunk) > n:
235 width += len(chunk) + 1
239 class Indenter(object):
241 with Indenter(pad_count = 8) as i:
252 pad_prefix: Optional[str] = None,
257 if pad_prefix is not None:
258 self.pad_prefix = pad_prefix
261 self.padding = pad_char * pad_count
267 def __exit__(self, exc_type, exc_value, exc_tb):
272 def print(self, *arg, **kwargs):
275 text = string_utils.sprintf(*arg, **kwargs)
276 print(self.pad_prefix + self.padding * self.level + text, end='')
279 def header(title: str, *, width: int = 80, color: str = ''):
281 Returns a nice header line with a title.
283 >>> header('title', width=60, color='')
284 '----[ title ]-----------------------------------------------'
291 right = (w - 4) * '-'
292 if color != '' and color is not None:
296 return f'{left}[ {color}{title}{r} ]{right}'
301 if __name__ == '__main__':