blob: b45445ef819be7295a0e4cef3dc46751229ac91c [file] [log] [blame]
Alex0989ecf2022-03-29 13:43:21 -05001# Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com)
2# Copyright 2019-2022 Mirantis, Inc.
Alex41485522019-04-12 17:26:18 -05003import sys
4
5
Alexe4de1142022-11-04 19:26:03 -05006class cl_typewriter(object):
7 previous = 0
8 carret = 0
9
10 def cl_start(self, sttr):
11 self.previous = self.carret
12 self.carret += len(sttr)
13 sys.stdout.write("\r{}".format(sttr))
14
15 def cl_inline(self, sttr):
16 self.carret += len(sttr)
17 sys.stdout.write("{}".format(sttr))
18
19 def cl_sameline(self, sttr):
20 self.cl_inline("\r" + sttr)
21 self.cl_flush()
22
23 def cl_flush(self, newline=False):
24 if newline:
25 self.cl_inline("\n")
26 self.carret = 0
27 elif self.previous > self.carret:
28 self.cl_inline(" "*(self.previous - self.carret))
29 sys.stdout.flush()
30
31
Alex41485522019-04-12 17:26:18 -050032class Progress(object):
Alexd9fd85e2019-05-16 16:58:24 -050033 _strsize = 0
34 _note_size = 0
35
Alex41485522019-04-12 17:26:18 -050036 def __init__(self, max_index, bar_size=21):
37 self.total = max_index
38 # bar size in symbols
39 self.bar_size = bar_size
40
41 def write_progress(self, index, note=''):
Alex3ebc5632019-04-18 16:47:18 -050042 # calc index and percent values
Alexd9fd85e2019-05-16 16:58:24 -050043 _suffix = ''
44 new_size = len(note)
45 if self._note_size > new_size:
46 _suffix = ' '*(self._note_size - new_size)
Alex1f90e7b2021-09-03 15:31:28 -050047 if index:
48 _percent = (100 * index) // self.total
49 _index = (self.bar_size * index) // self.total
50 else:
51 _percent = 0
52 _index = 0
53
Alex41485522019-04-12 17:26:18 -050054 # clear the line
55 sys.stdout.write('\r')
56 # print new progress
57 _format = "[{:"+str(self.bar_size-1)+"}] {}/{} ({}%) {}"
Alexd9fd85e2019-05-16 16:58:24 -050058 _progress_string = _format.format(
Alex41485522019-04-12 17:26:18 -050059 '='*_index,
60 index,
61 self.total,
62 _percent,
Alexd9fd85e2019-05-16 16:58:24 -050063 note + _suffix
64 )
65 sys.stdout.write(_progress_string)
66 # Save new note size and whole string size
67 self._strsize = len(_progress_string)
68 self._note_size = new_size
Alex41485522019-04-12 17:26:18 -050069 sys.stdout.flush()
Alex3ebc5632019-04-18 16:47:18 -050070
Alexd9fd85e2019-05-16 16:58:24 -050071 def clearline(self):
72 sys.stdout.write('\r')
73 sys.stdout.write(' '*self._strsize)
74 sys.stdout.write('\r')
Alexd0391d42019-05-21 18:48:55 -050075 sys.stdout.flush()
Alexd9fd85e2019-05-16 16:58:24 -050076
77 def end(self):
78 self._note_size = 0
79 self._strsize = 0
Alex41485522019-04-12 17:26:18 -050080 sys.stdout.write('\n')