Various changes.
[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     try:
27         rows, columns = cmd_with_timeout(
28             "stty size",
29             timeout_seconds=5.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     print(
59         bar,
60         end=ret,
61         flush=True,
62         file=sys.stderr)
63
64
65 def bar_graph(
66     percentage: float,
67     *,
68     include_text=True,
69     width=70,
70     fgcolor=fg("school bus yellow"),
71     reset=reset(),
72     left_end="[",
73     right_end="]",
74 ) -> None:
75     """Returns a string containing a bar graph.
76
77     >>> bar_graph(0.5, fgcolor='', reset='')
78     '[███████████████████████████████████                                   ] 50.0%'
79
80     """
81
82     if percentage < 0.0 or percentage > 1.0:
83         raise ValueError(percentage)
84     if include_text:
85         text = f"{percentage*100.0:2.1f}%"
86     else:
87         text = ""
88     whole_width = math.floor(percentage * width)
89     if whole_width == width:
90         whole_width -= 1
91         part_char = "▉"
92     else:
93         remainder_width = (percentage * width) % 1
94         part_width = math.floor(remainder_width * 8)
95         part_char = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][part_width]
96     return (
97         left_end +
98         fgcolor +
99         "█" * whole_width + part_char +
100         " " * (width - whole_width - 1) +
101         reset +
102         right_end + " " +
103         text)
104
105
106 def distribute_strings(
107     strings: List[str],
108     *,
109     width: int = 80,
110     alignment: str = "c",
111     padding: str = " ",
112 ) -> str:
113     """
114     Distributes strings into a line with a particular justification.
115
116     >>> distribute_strings(['this', 'is', 'a', 'test'], width=40)
117     '   this       is         a       test   '
118     >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='l')
119     'this      is        a         test      '
120     >>> distribute_strings(['this', 'is', 'a', 'test'], width=40, alignment='r')
121     '      this        is         a      test'
122
123     """
124     subwidth = math.floor(width / len(strings))
125     retval = ""
126     for string in strings:
127         string = justify_string(
128             string, width=subwidth, alignment=alignment, padding=padding
129         )
130         retval += string
131     return retval
132
133
134 def justify_string_by_chunk(
135     string: str, width: int = 80, padding: str = " "
136 ) -> str:
137     """
138     Justifies a string.
139
140     >>> justify_string_by_chunk("This is a test", 40)
141     'This       is              a        test'
142     >>> justify_string_by_chunk("This is a test", 20)
143     'This  is    a   test'
144
145     """
146     padding = padding[0]
147     first, *rest, last = string.split()
148     w = width - (len(first) + 1 + len(last) + 1)
149     retval = (
150         first + padding + distribute_strings(rest, width=w, padding=padding)
151     )
152     while len(retval) + len(last) < width:
153         retval += padding
154     retval += last
155     return retval
156
157
158 def justify_string(
159     string: str, *, width: int = 80, alignment: str = "c", padding: str = " "
160 ) -> str:
161     """Justify a string.
162
163     >>> justify_string('This is another test', width=40, alignment='c')
164     '          This is another test          '
165     >>> justify_string('This is another test', width=40, alignment='l')
166     'This is another test                    '
167     >>> justify_string('This is another test', width=40, alignment='r')
168     '                    This is another test'
169     >>> justify_string('This is another test', width=40, alignment='j')
170     'This       is           another     test'
171
172     """
173     alignment = alignment[0]
174     padding = padding[0]
175     while len(string) < width:
176         if alignment == "l":
177             string += padding
178         elif alignment == "r":
179             string = padding + string
180         elif alignment == "j":
181             return justify_string_by_chunk(
182                 string,
183                 width=width,
184                 padding=padding
185             )
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     def __init__(self,
256                  *,
257                  pad_prefix: Optional[str] = None,
258                  pad_char: str = ' ',
259                  pad_count: int = 4):
260         self.level = -1
261         if pad_prefix is not None:
262             self.pad_prefix = pad_prefix
263         else:
264             self.pad_prefix = ''
265         self.padding = pad_char * pad_count
266
267     def __enter__(self):
268         self.level += 1
269         return self
270
271     def __exit__(self, exc_type, exc_value, exc_tb):
272         self.level -= 1
273         if self.level < -1:
274             self.level = -1
275
276     def print(self, *arg, **kwargs):
277         import string_utils
278         text = string_utils.sprintf(*arg, **kwargs)
279         print(self.pad_prefix + self.padding * self.level + text, end='')
280
281
282 def header(title: str, *, width: int = 80, color: str = ''):
283     """
284     Returns a nice header line with a title.
285
286     >>> header('title', width=60, color='')
287     '----[ title ]-----------------------------------------------'
288
289     """
290     w = width
291     w -= (len(title) + 4)
292     if w >= 4:
293         left = 4 * '-'
294         right = (w - 4) * '-'
295         if color != '' and color is not None:
296             r = reset()
297         else:
298             r = ''
299         return f'{left}[ {color}{title}{r} ]{right}'
300     else:
301         return ''
302
303
304 if __name__ == '__main__':
305     import doctest
306     doctest.testmod()