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):
22 def get_console_rows_columns() -> RowsColumns:
23 """Returns the number of rows/columns on the current console."""
25 from exec_utils import cmd
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:
90 elif whole_width == 0 and percentage > 0.0:
93 remainder_width = (percentage * width) % 1
94 part_width = math.floor(remainder_width * 8)
95 part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
101 + " " * (width - whole_width - 1)
109 def sparkline(numbers: List[float]) -> Tuple[float, float, str]:
111 Makes a "sparkline" little inline histogram graph. Auto scales.
113 >>> sparkline([1, 2, 3, 5, 10, 3, 5, 7])
116 >>> sparkline([104, 99, 93, 96, 82, 77, 85, 73])
117 (73, 104, '█▇▆▆▃▂▄▁')
120 _bar = '▁▂▃▄▅▆▇█' # Unicode: 9601, 9602, 9603, 9604, 9605, 9606, 9607, 9608
123 min_num, max_num = min(numbers), max(numbers)
124 span = max_num - min_num
126 _bar[min([barcount - 1, int((n - min_num) / span * barcount)])] for n in numbers
128 return min_num, max_num, sparkline
131 def distribute_strings(
135 alignment: str = "c",
139 Distributes strings into a line with a particular justification.
141 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
143 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
145 >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
149 subwidth = math.floor(width / len(strings))
151 for string in strings:
152 string = justify_string(string, width=subwidth, alignment=alignment, padding=padding)
154 while len(retval) > width:
155 retval = retval.replace(' ', ' ', 1)
156 while len(retval) < width:
157 retval = retval.replace(' ', ' ', 1)
161 def justify_string_by_chunk(string: str, width: int = 80, padding: str = " ") -> str:
165 >>> justify_string_by_chunk("This is a test", 40)
167 >>> justify_string_by_chunk("This is a test", 20)
172 first, *rest, last = string.split()
173 w = width - (len(first) + 1 + len(last) + 1)
174 ret = first + padding + distribute_strings(rest, width=w, padding=padding) + padding + last
179 string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
183 >>> justify_string('This is another test', width=40, alignment='c')
184 ' This is another test '
185 >>> justify_string('This is another test', width=40, alignment='l')
186 'This is another test '
187 >>> justify_string('This is another test', width=40, alignment='r')
188 ' This is another test'
189 >>> justify_string('This is another test', width=40, alignment='j')
190 'This is another test'
193 alignment = alignment[0]
195 while len(string) < width:
198 elif alignment == "r":
199 string = padding + string
200 elif alignment == "j":
201 return justify_string_by_chunk(string, width=width, padding=padding)
202 elif alignment == "c":
203 if len(string) % 2 == 0:
206 string = padding + string
212 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
216 >>> justify_text('This is a test of the emergency broadcast system. This is only a test.',
217 ... width=40, alignment='j') #doctest: +NORMALIZE_WHITESPACE
218 'This is a test of the emergency\\nbroadcast system. This is only a test.'
222 for word in text.split():
223 if len(line) + len(word) > width:
225 line = justify_string(line, width=width, alignment=alignment)
226 retval = retval + "\n" + line
228 line = line + " " + word
230 retval += "\n" + line[1:]
234 def generate_padded_columns(text: List[str]) -> Generator:
235 max_width: Dict[int, int] = defaultdict(int)
237 for pos, word in enumerate(line.split()):
238 max_width[pos] = max(max_width[pos], len(word))
242 for pos, word in enumerate(line.split()):
243 width = max_width[pos]
244 word = justify_string(word, width=width, alignment='l')
249 def wrap_string(text: str, n: int) -> str:
250 chunks = text.split()
254 if width + len(chunk) > n:
258 width += len(chunk) + 1
262 class Indenter(object):
264 with Indenter(pad_count = 8) as i:
275 pad_prefix: Optional[str] = None,
280 if pad_prefix is not None:
281 self.pad_prefix = pad_prefix
284 self.padding = pad_char * pad_count
290 def __exit__(self, exc_type, exc_value, exc_tb):
295 def print(self, *arg, **kwargs):
298 text = string_utils.sprintf(*arg, **kwargs)
299 print(self.pad_prefix + self.padding * self.level + text, end='')
302 def header(title: str, *, width: int = 80, color: str = ''):
304 Returns a nice header line with a title.
306 >>> header('title', width=60, color='')
307 '----[ title ]-----------------------------------------------'
314 right = (w - 4) * '-'
315 if color != '' and color is not None:
319 return f'{left}[ {color}{title}{r} ]{right}'
324 if __name__ == '__main__':