2 # -*- coding: utf-8 -*-
4 """Utilities for dealing with "text"."""
9 from collections import defaultdict
10 from typing import Dict, Generator, List, NamedTuple, Optional, Tuple
12 from ansi import fg, reset
14 logger = logging.getLogger(__file__)
17 class RowsColumns(NamedTuple):
24 def get_console_rows_columns() -> RowsColumns:
25 """Returns the number of rows/columns on the current console."""
27 from exec_utils import cmd
34 except Exception as e:
36 raise Exception('Can\'t determine console size?!') from e
37 return RowsColumns(int(rows), int(columns))
45 fgcolor=fg("school bus yellow"),
50 """Draws a progress graph."""
52 percent = current / total
53 ret = "\r" if redraw else "\n"
62 print(bar, end=ret, flush=True, file=sys.stderr)
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:
92 elif whole_width == 0 and percentage > 0.0:
95 remainder_width = (percentage * width) % 1
96 part_width = math.floor(remainder_width * 8)
97 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
103 + " " * (width - whole_width - 1)
111 def sparkline(numbers: List[float]) -> Tuple[float, float, str]:
113 Makes a "sparkline" little inline histogram graph. Auto scales.
115 >>> sparkline([1, 2, 3, 5, 10, 3, 5, 7])
118 >>> sparkline([104, 99, 93, 96, 82, 77, 85, 73])
119 (73, 104, '█▇▆▆▃▂▄▁')
122 _bar = '▁▂▃▄▅▆▇█' # Unicode: 9601, 9602, 9603, 9604, 9605, 9606, 9607, 9608
125 min_num, max_num = min(numbers), max(numbers)
126 span = max_num - min_num
128 _bar[min([barcount - 1, int((n - min_num) / span * barcount)])] for n in numbers
130 return min_num, max_num, sline
133 def distribute_strings(
137 alignment: str = "c",
141 Distributes strings into a line with a particular justification.
143 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
145 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
147 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
151 subwidth = math.floor(width / len(strings))
153 for string in strings:
154 string = justify_string(string, width=subwidth, alignment=alignment, padding=padding)
156 while len(retval) > width:
157 retval = retval.replace(' ', ' ', 1)
158 while len(retval) < width:
159 retval = retval.replace(' ', ' ', 1)
163 def justify_string_by_chunk(string: str, width: int = 80, padding: str = " ") -> str:
167 >>> justify_string_by_chunk("This is a test", 40)
169 >>> justify_string_by_chunk("This is a test", 20)
174 first, *rest, last = string.split()
175 w = width - (len(first) + 1 + len(last) + 1)
176 ret = first + padding + distribute_strings(rest, width=w, padding=padding) + padding + last
181 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
185 >>> justify_string('This is another test', width=40, alignment='c')
186 ' This is another test '
187 >>> justify_string('This is another test', width=40, alignment='l')
188 'This is another test '
189 >>> justify_string('This is another test', width=40, alignment='r')
190 ' This is another test'
191 >>> justify_string('This is another test', width=40, alignment='j')
192 'This is another test'
195 alignment = alignment[0]
197 while len(string) < width:
200 elif alignment == "r":
201 string = padding + string
202 elif alignment == "j":
203 return justify_string_by_chunk(string, width=width, padding=padding)
204 elif alignment == "c":
205 if len(string) % 2 == 0:
208 string = padding + string
214 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
218 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
219 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
220 'This is a test of the emergency\\nbroadcast system. This is only a test.'
224 for word in text.split():
225 if len(line) + len(word) > width:
227 line = justify_string(line, width=width, alignment=alignment)
228 retval = retval + "\n" + line
230 line = line + " " + word
232 retval += "\n" + line[1:]
236 def generate_padded_columns(text: List[str]) -> Generator:
237 max_width: Dict[int, int] = defaultdict(int)
239 for pos, word in enumerate(line.split()):
240 max_width[pos] = max(max_width[pos], len(word))
244 for pos, word in enumerate(line.split()):
245 width = max_width[pos]
246 word = justify_string(word, width=width, alignment='l')
251 def wrap_string(text: str, n: int) -> str:
252 chunks = text.split()
256 if width + len(chunk) > n:
260 width += len(chunk) + 1
264 class Indenter(object):
266 with Indenter(pad_count = 8) as i:
277 pad_prefix: Optional[str] = None,
282 if pad_prefix is not None:
283 self.pad_prefix = pad_prefix
286 self.padding = pad_char * pad_count
292 def __exit__(self, exc_type, exc_value, exc_tb):
297 def print(self, *arg, **kwargs):
300 text = string_utils.sprintf(*arg, **kwargs)
301 print(self.pad_prefix + self.padding * self.level + text, end='')
304 def header(title: str, *, width: int = 80, color: str = ''):
306 Returns a nice header line with a title.
308 >>> header('title', width=60, color='')
309 '----[ title ]-----------------------------------------------'
316 right = (w - 4) * '-'
317 if color != '' and color is not None:
321 return f'{left}[ {color}{title}{r} ]{right}'
326 if __name__ == '__main__':