Ahem. Still running black?
[python_utils.git] / text_utils.py
1 #!/usr/bin/env python3
2
3 """Utilities for dealing with "text"."""
4
5 from collections import defaultdict
6 import logging
7 import math
8 import sys
9 from typing import List, NamedTuple, Optional
10
11 from ansi import fg, reset
12
13
14 logger = logging.getLogger(__file__)
15
16
17 class RowsColumns(NamedTuple):
18     rows: int
19     columns: int
20
21
22 def get_console_rows_columns() -> RowsColumns:
23     """Returns the number of rows/columns on the current console."""
24
25     from exec_utils import cmd_with_timeout
26
27     try:
28         rows, columns = cmd_with_timeout(
29             "stty size",
30             timeout_seconds=1.0,
31         ).split()
32     except Exception as e:
33         logger.exception(e)
34         raise Exception('Can\'t determine console size?!')
35     return RowsColumns(int(rows), int(columns))
36
37
38 def progress_graph(
39     current: int,
40     total: int,
41     *,
42     width=70,
43     fgcolor=fg("school bus yellow"),
44     left_end="[",
45     right_end="]",
46     redraw=True,
47 ) -> None:
48     """Draws a progress graph."""
49
50     percent = current / total
51     ret = "\r" if redraw else "\n"
52     bar = bar_graph(
53         percent,
54         include_text=True,
55         width=width,
56         fgcolor=fgcolor,
57         left_end=left_end,
58         right_end=right_end,
59     )
60     print(bar, end=ret, flush=True, file=sys.stderr)
61
62
63 def bar_graph(
64     percentage: float,
65     *,
66     include_text=True,
67     width=70,
68     fgcolor=fg("school bus yellow"),
69     reset=reset(),
70     left_end="[",
71     right_end="]",
72 ) -> None:
73     """Returns a string containing a bar graph.
74
75     >>> bar_graph(0.5, fgcolor='', reset='')
76     '[███████████████████████████████████                                   ] 50.0%'
77
78     """
79
80     if percentage < 0.0 or percentage > 1.0:
81         raise ValueError(percentage)
82     if include_text:
83         text = f"{percentage*100.0:2.1f}%"
84     else:
85         text = ""
86     whole_width = math.floor(percentage * width)
87     if whole_width == width:
88         whole_width -= 1
89         part_char = "▉"
90     else:
91         remainder_width = (percentage * width) % 1
92         part_width = math.floor(remainder_width * 8)
93         part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
94     return (
95         left_end
96         + fgcolor
97         + "█" * whole_width
98         + part_char
99         + " " * (width - whole_width - 1)
100         + reset
101         + right_end
102         + " "
103         + text
104     )
105
106
107 def distribute_strings(
108     strings: List[str],
109     *,
110     width: int = 80,
111     alignment: str = "c",
112     padding: str = " ",
113 ) -> str:
114     """
115     Distributes strings into a line with a particular justification.
116
117     >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
118     '   this       is         a       test   '
119     >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
120     'this      is        a         test      '
121     >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
122     '      this        is         a      test'
123
124     """
125     subwidth = math.floor(width / len(strings))
126     retval = ""
127     for string in strings:
128         string = justify_string(
129             string, width=subwidth, alignment=alignment, padding=padding
130         )
131         retval += string
132     while len(retval) > width:
133         retval = retval.replace('  ', ' ', 1)
134     while len(retval) < width:
135         retval = retval.replace(' ', '  ', 1)
136     return retval
137
138
139 def justify_string_by_chunk(string: str, width: int = 80, padding: str = " ") -> str:
140     """
141     Justifies a string.
142
143     >>> justify_string_by_chunk("This is a test", 40)
144     'This       is              a        test'
145     >>> justify_string_by_chunk("This is a test", 20)
146     'This  is    a   test'
147
148     """
149     padding = padding[0]
150     first, *rest, last = string.split()
151     w = width - (len(first) + 1 + len(last) + 1)
152     ret = (
153         first
154         + padding
155         + distribute_strings(rest, width=w, padding=padding)
156         + padding
157         + last
158     )
159     return ret
160
161
162 def justify_string(
163     string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
164 ) -> str:
165     """Justify a string.
166
167     >>> justify_string('This is another test', width=40, alignment='c')
168     '          This is another test          '
169     >>> justify_string('This is another test', width=40, alignment='l')
170     'This is another test                    '
171     >>> justify_string('This is another test', width=40, alignment='r')
172     '                    This is another test'
173     >>> justify_string('This is another test', width=40, alignment='j')
174     'This       is           another     test'
175
176     """
177     alignment = alignment[0]
178     padding = padding[0]
179     while len(string) < width:
180         if alignment == "l":
181             string += padding
182         elif alignment == "r":
183             string = padding + string
184         elif alignment == "j":
185             return justify_string_by_chunk(string, width=width, padding=padding)
186         elif alignment == "c":
187             if len(string) % 2 == 0:
188                 string += padding
189             else:
190                 string = padding + string
191         else:
192             raise ValueError
193     return string
194
195
196 def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
197     """
198     Justifies text.
199
200     >>> justify_text('This is a test of the emergency broadcast system.  This is only a test.',
201     ...              width=40, alignment='j')  #doctest: +NORMALIZE_WHITESPACE
202     'This  is    a  test  of   the  emergency\\nbroadcast system. This is only a test.'
203     """
204     retval = ""
205     line = ""
206     for word in text.split():
207         if len(line) + len(word) > width:
208             line = line[1:]
209             line = justify_string(line, width=width, alignment=alignment)
210             retval = retval + "\n" + line
211             line = ""
212         line = line + " " + word
213     if len(line) > 0:
214         retval += "\n" + line[1:]
215     return retval[1:]
216
217
218 def generate_padded_columns(text: List[str]) -> str:
219     max_width = defaultdict(int)
220     for line in text:
221         for pos, word in enumerate(line.split()):
222             max_width[pos] = max(max_width[pos], len(word))
223
224     for line in text:
225         out = ""
226         for pos, word in enumerate(line.split()):
227             width = max_width[pos]
228             word = justify_string(word, width=width, alignment='l')
229             out += f'{word} '
230         yield out
231
232
233 def wrap_string(text: str, n: int) -> str:
234     chunks = text.split()
235     out = ''
236     width = 0
237     for chunk in chunks:
238         if width + len(chunk) > n:
239             out += '\n'
240             width = 0
241         out += chunk + ' '
242         width += len(chunk) + 1
243     return out
244
245
246 class Indenter(object):
247     """
248     with Indenter(pad_count = 8) as i:
249         i.print('test')
250         with i:
251             i.print('-ing')
252             with i:
253                 i.print('1, 2, 3')
254     """
255
256     def __init__(
257         self,
258         *,
259         pad_prefix: Optional[str] = None,
260         pad_char: str = ' ',
261         pad_count: int = 4,
262     ):
263         self.level = -1
264         if pad_prefix is not None:
265             self.pad_prefix = pad_prefix
266         else:
267             self.pad_prefix = ''
268         self.padding = pad_char * pad_count
269
270     def __enter__(self):
271         self.level += 1
272         return self
273
274     def __exit__(self, exc_type, exc_value, exc_tb):
275         self.level -= 1
276         if self.level < -1:
277             self.level = -1
278
279     def print(self, *arg, **kwargs):
280         import string_utils
281
282         text = string_utils.sprintf(*arg, **kwargs)
283         print(self.pad_prefix + self.padding * self.level + text, end='')
284
285
286 def header(title: str, *, width: int = 80, color: str = ''):
287     """
288     Returns a nice header line with a title.
289
290     >>> header('title', width=60, color='')
291     '----[ title ]-----------------------------------------------'
292
293     """
294     w = width
295     w -= len(title) + 4
296     if w >= 4:
297         left = 4 * '-'
298         right = (w - 4) * '-'
299         if color != '' and color is not None:
300             r = reset()
301         else:
302             r = ''
303         return f'{left}[ {color}{title}{r} ]{right}'
304     else:
305         return ''
306
307
308 if __name__ == '__main__':
309     import doctest
310
311     doctest.testmod()