~bzr-pqm/bzr/bzr.dev

649 by Martin Pool
- some cleanups for the progressbar method
1
# Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca>
2
# Copyright (C) 2005 Canonical <canonical.com>
648 by Martin Pool
- import aaron's progress-indicator code
3
#
4
#    This program is free software; you can redistribute it and/or modify
5
#    it under the terms of the GNU General Public License as published by
6
#    the Free Software Foundation; either version 2 of the License, or
7
#    (at your option) any later version.
8
#
9
#    This program is distributed in the hope that it will be useful,
10
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
11
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
#    GNU General Public License for more details.
13
#
14
#    You should have received a copy of the GNU General Public License
15
#    along with this program; if not, write to the Free Software
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
649 by Martin Pool
- some cleanups for the progressbar method
18
889 by Martin Pool
- show progress bar during inventory conversion to weave, and make profiling optional
19
"""Simple text-mode progress indicator.
649 by Martin Pool
- some cleanups for the progressbar method
20
21
To display an indicator, create a ProgressBar object.  Call it,
22
passing Progress objects indicating the current state.  When done,
23
call clear().
24
25
Progress is suppressed when output is not sent to a terminal, so as
26
not to clutter log files.
27
"""
28
29
# TODO: remove functions in favour of keeping everything in one class
30
652 by Martin Pool
doc
31
# TODO: should be a global option e.g. --silent that disables progress
32
# indicators, preferably without needing to adjust all code that
33
# potentially calls them.
34
655 by Martin Pool
- better calculation of progress bar position
35
# TODO: Perhaps don't write updates faster than a certain rate, say
36
# 5/second.
37
649 by Martin Pool
- some cleanups for the progressbar method
38
648 by Martin Pool
- import aaron's progress-indicator code
39
import sys
660 by Martin Pool
- use plain unix time, not datetime module
40
import time
648 by Martin Pool
- import aaron's progress-indicator code
41
649 by Martin Pool
- some cleanups for the progressbar method
42
43
def _width():
44
    """Return estimated terminal width.
45
46
    TODO: Do something smart on Windows?
47
48
    TODO: Is there anything that gets a better update when the window
49
          is resized while the program is running?
50
    """
51
    import os
52
    try:
53
        return int(os.environ['COLUMNS'])
54
    except (IndexError, KeyError, ValueError):
55
        return 80
56
57
58
def _supports_progress(f):
695 by Martin Pool
- don't display progress bars on really dumb terminals
59
    if not hasattr(f, 'isatty'):
60
        return False
61
    if not f.isatty():
62
        return False
63
    import os
64
    if os.environ.get('TERM') == 'dumb':
65
        # e.g. emacs compile window
66
        return False
67
    return True
649 by Martin Pool
- some cleanups for the progressbar method
68
69
70
648 by Martin Pool
- import aaron's progress-indicator code
71
class ProgressBar(object):
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
72
    """Progress bar display object.
73
74
    Several options are available to control the display.  These can
75
    be passed as parameters to the constructor or assigned at any time:
76
77
    show_pct
78
        Show percentage complete.
79
    show_spinner
80
        Show rotating baton.  This ticks over on every update even
81
        if the values don't change.
82
    show_eta
83
        Show predicted time-to-completion.
84
    show_bar
85
        Show bar graph.
86
    show_count
87
        Show numerical counts.
88
89
    The output file should be in line-buffered or unbuffered mode.
90
    """
91
    SPIN_CHARS = r'/-\|'
661 by Martin Pool
- limit rate at which progress bar is updated
92
    MIN_PAUSE = 0.1 # seconds
93
94
    start_time = None
95
    last_update = None
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
96
    
97
    def __init__(self,
98
                 to_file=sys.stderr,
99
                 show_pct=False,
100
                 show_spinner=False,
101
                 show_eta=True,
102
                 show_bar=True,
103
                 show_count=True):
649 by Martin Pool
- some cleanups for the progressbar method
104
        object.__init__(self)
105
        self.to_file = to_file
106
        self.suppressed = not _supports_progress(self.to_file)
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
107
        self.spin_pos = 0
108
 
681 by Martin Pool
- assign missing fields in Progress object
109
        self.last_msg = None
110
        self.last_cnt = None
111
        self.last_total = None
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
112
        self.show_pct = show_pct
113
        self.show_spinner = show_spinner
114
        self.show_eta = show_eta
115
        self.show_bar = show_bar
116
        self.show_count = show_count
117
118
119
    def tick(self):
120
        self.update(self.last_msg, self.last_cnt, self.last_total)
121
                 
122
123
667 by Martin Pool
- allow for progressbar updates with no count, only a message
124
    def update(self, msg, current_cnt=None, total_cnt=None):
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
125
        """Update and redraw progress bar."""
661 by Martin Pool
- limit rate at which progress bar is updated
126
        if self.suppressed:
127
            return
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
128
129
        # save these for the tick() function
130
        self.last_msg = msg
131
        self.last_cnt = current_cnt
132
        self.last_total = total_cnt
133
            
661 by Martin Pool
- limit rate at which progress bar is updated
134
        now = time.time()
135
        if self.start_time is None:
136
            self.start_time = now
137
        else:
138
            interval = now - self.last_update
139
            if interval > 0 and interval < self.MIN_PAUSE:
140
                return
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
141
661 by Martin Pool
- limit rate at which progress bar is updated
142
        self.last_update = now
143
        
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
144
        width = _width()
145
146
        if total_cnt:
147
            assert current_cnt <= total_cnt
148
        if current_cnt:
149
            assert current_cnt >= 0
150
        
151
        if self.show_eta and self.start_time and total_cnt:
152
            eta = get_eta(self.start_time, current_cnt, total_cnt)
153
            eta_str = " " + str_tdelta(eta)
154
        else:
155
            eta_str = ""
156
157
        if self.show_spinner:
158
            spin_str = self.SPIN_CHARS[self.spin_pos % 4] + ' '            
159
        else:
160
            spin_str = ''
161
162
        # always update this; it's also used for the bar
163
        self.spin_pos += 1
164
165
        if self.show_pct and total_cnt and current_cnt:
166
            pct = 100.0 * current_cnt / total_cnt
167
            pct_str = ' (%5.1f%%)' % pct
168
        else:
169
            pct_str = ''
170
171
        if not self.show_count:
172
            count_str = ''
173
        elif current_cnt is None:
174
            count_str = ''
175
        elif total_cnt is None:
176
            count_str = ' %i' % (current_cnt)
177
        else:
178
            # make both fields the same size
179
            t = '%i' % (total_cnt)
180
            c = '%*i' % (len(t), current_cnt)
181
            count_str = ' ' + c + '/' + t 
182
183
        if self.show_bar:
184
            # progress bar, if present, soaks up all remaining space
185
            cols = width - 1 - len(msg) - len(spin_str) - len(pct_str) \
186
                   - len(eta_str) - len(count_str) - 3
187
188
            if total_cnt:
189
                # number of markers highlighted in bar
190
                markers = int(round(float(cols) * current_cnt / total_cnt))
191
                bar_str = '[' + ('=' * markers).ljust(cols) + '] '
669 by Martin Pool
- don't show progress bar unless completion is known
192
            elif False:
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
193
                # don't know total, so can't show completion.
194
                # so just show an expanded spinning thingy
195
                m = self.spin_pos % cols
668 by Martin Pool
- fix sweeping bar progress indicator
196
                ms = (' ' * m + '*').ljust(cols)
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
197
                
198
                bar_str = '[' + ms + '] '
669 by Martin Pool
- don't show progress bar unless completion is known
199
            else:
200
                bar_str = ''
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
201
        else:
202
            bar_str = ''
203
204
        m = spin_str + bar_str + msg + count_str + pct_str + eta_str
205
206
        assert len(m) < width
207
        self.to_file.write('\r' + m.ljust(width - 1))
208
        #self.to_file.flush()
209
            
649 by Martin Pool
- some cleanups for the progressbar method
210
211
    def clear(self):
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
212
        if self.suppressed:
213
            return
214
        
215
        self.to_file.write('\r%s\r' % (' ' * (_width() - 1)))
216
        #self.to_file.flush()        
649 by Martin Pool
- some cleanups for the progressbar method
217
    
218
648 by Martin Pool
- import aaron's progress-indicator code
219
        
220
def str_tdelta(delt):
221
    if delt is None:
222
        return "-:--:--"
660 by Martin Pool
- use plain unix time, not datetime module
223
    delt = int(round(delt))
224
    return '%d:%02d:%02d' % (delt/3600,
225
                             (delt/60) % 60,
226
                             delt % 60)
227
228
229
def get_eta(start_time, current, total, enough_samples=3):
230
    if start_time is None:
231
        return None
232
233
    if not total:
234
        return None
235
236
    if current < enough_samples:
237
        return None
238
239
    if current > total:
240
        return None                     # wtf?
241
242
    elapsed = time.time() - start_time
243
244
    if elapsed < 2.0:                   # not enough time to estimate
245
        return None
246
    
247
    total_duration = float(elapsed) * float(total) / float(current)
248
249
    assert total_duration >= elapsed
250
251
    return total_duration - elapsed
648 by Martin Pool
- import aaron's progress-indicator code
252
649 by Martin Pool
- some cleanups for the progressbar method
253
648 by Martin Pool
- import aaron's progress-indicator code
254
def run_tests():
255
    import doctest
256
    result = doctest.testmod()
257
    if result[1] > 0:
258
        if result[0] == 0:
259
            print "All tests passed"
260
    else:
261
        print "No tests to run"
649 by Martin Pool
- some cleanups for the progressbar method
262
263
264
def demo():
265
    from time import sleep
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
266
    pb = ProgressBar(show_pct=True, show_bar=True, show_spinner=False)
649 by Martin Pool
- some cleanups for the progressbar method
267
    for i in range(100):
658 by Martin Pool
- clean up and add a bunch of options to the progress indicator
268
        pb.update('Elephanten', i, 99)
269
        sleep(0.1)
270
    sleep(2)
271
    pb.clear()
272
    sleep(1)
649 by Martin Pool
- some cleanups for the progressbar method
273
    print 'done!'
274
648 by Martin Pool
- import aaron's progress-indicator code
275
if __name__ == "__main__":
649 by Martin Pool
- some cleanups for the progressbar method
276
    demo()