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