/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/progress.py

  • Committer: John Arbash Meinel
  • Date: 2006-07-07 14:35:12 UTC
  • mto: This revision was merged to the branch mainline in revision 1854.
  • Revision ID: john@arbash-meinel.com-20060707143512-67c9442bd7f63158
Fix a ui test that depended on clearing

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca>
 
2
# Copyright (C) 2005, 2006 Canonical <canonical.com>
 
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
 
 
18
 
 
19
"""Simple text-mode progress indicator.
 
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: should be a global option e.g. --silent that disables progress
 
30
# indicators, preferably without needing to adjust all code that
 
31
# potentially calls them.
 
32
 
 
33
# TODO: If not on a tty perhaps just print '......' for the benefit of IDEs, etc
 
34
 
 
35
# TODO: Optionally show elapsed time instead/as well as ETA; nicer
 
36
# when the rate is unpredictable
 
37
 
 
38
 
 
39
import sys
 
40
import time
 
41
import os
 
42
from collections import deque
 
43
 
 
44
 
 
45
import bzrlib.errors as errors
 
46
from bzrlib.trace import mutter 
 
47
 
 
48
 
 
49
def _supports_progress(f):
 
50
    if not hasattr(f, 'isatty'):
 
51
        return False
 
52
    if not f.isatty():
 
53
        return False
 
54
    if os.environ.get('TERM') == 'dumb':
 
55
        # e.g. emacs compile window
 
56
        return False
 
57
    return True
 
58
 
 
59
 
 
60
 
 
61
def ProgressBar(to_file=None, **kwargs):
 
62
    """Abstract factory"""
 
63
    if to_file is None:
 
64
        to_file = sys.stderr
 
65
    if _supports_progress(to_file):
 
66
        return TTYProgressBar(to_file=to_file, **kwargs)
 
67
    else:
 
68
        return DotsProgressBar(to_file=to_file, **kwargs)
 
69
    
 
70
 
 
71
class ProgressBarStack(object):
 
72
    """A stack of progress bars."""
 
73
 
 
74
    def __init__(self,
 
75
                 to_file=None,
 
76
                 show_pct=False,
 
77
                 show_spinner=True,
 
78
                 show_eta=False,
 
79
                 show_bar=True,
 
80
                 show_count=True,
 
81
                 to_messages_file=None,
 
82
                 klass=None):
 
83
        """Setup the stack with the parameters the progress bars should have."""
 
84
        if to_file is None:
 
85
            to_file = sys.stderr
 
86
        if to_messages_file is None:
 
87
            to_messages_file = sys.stdout
 
88
        self._to_file = to_file
 
89
        self._show_pct = show_pct
 
90
        self._show_spinner = show_spinner
 
91
        self._show_eta = show_eta
 
92
        self._show_bar = show_bar
 
93
        self._show_count = show_count
 
94
        self._to_messages_file = to_messages_file
 
95
        self._stack = []
 
96
        self._klass = klass or TTYProgressBar
 
97
 
 
98
    def top(self):
 
99
        if len(self._stack) != 0:
 
100
            return self._stack[-1]
 
101
        else:
 
102
            return None
 
103
 
 
104
    def bottom(self):
 
105
        if len(self._stack) != 0:
 
106
            return self._stack[0]
 
107
        else:
 
108
            return None
 
109
 
 
110
    def get_nested(self):
 
111
        """Return a nested progress bar."""
 
112
        if len(self._stack) == 0:
 
113
            func = self._klass
 
114
        else:
 
115
            func = self.top().child_progress
 
116
        new_bar = func(to_file=self._to_file,
 
117
                       show_pct=self._show_pct,
 
118
                       show_spinner=self._show_spinner,
 
119
                       show_eta=self._show_eta,
 
120
                       show_bar=self._show_bar,
 
121
                       show_count=self._show_count,
 
122
                       to_messages_file=self._to_messages_file,
 
123
                       _stack=self)
 
124
        self._stack.append(new_bar)
 
125
        return new_bar
 
126
 
 
127
    def return_pb(self, bar):
 
128
        """Return bar after its been used."""
 
129
        if bar is not self._stack[-1]:
 
130
            raise errors.MissingProgressBarFinish()
 
131
        self._stack.pop()
 
132
 
 
133
 
 
134
class _BaseProgressBar(object):
 
135
 
 
136
    def __init__(self,
 
137
                 to_file=None,
 
138
                 show_pct=False,
 
139
                 show_spinner=False,
 
140
                 show_eta=False,
 
141
                 show_bar=True,
 
142
                 show_count=True,
 
143
                 to_messages_file=None,
 
144
                 _stack=None):
 
145
        object.__init__(self)
 
146
        if to_file is None:
 
147
            to_file = sys.stderr
 
148
        if to_messages_file is None:
 
149
            to_messages_file = sys.stdout
 
150
        self.to_file = to_file
 
151
        self.to_messages_file = to_messages_file
 
152
        self.last_msg = None
 
153
        self.last_cnt = None
 
154
        self.last_total = None
 
155
        self.show_pct = show_pct
 
156
        self.show_spinner = show_spinner
 
157
        self.show_eta = show_eta
 
158
        self.show_bar = show_bar
 
159
        self.show_count = show_count
 
160
        self._stack = _stack
 
161
        # seed throttler
 
162
        self.MIN_PAUSE = 0.1 # seconds
 
163
        now = time.clock()
 
164
        # starting now
 
165
        self.start_time = now
 
166
        # next update should not throttle
 
167
        self.last_update = now - self.MIN_PAUSE - 1
 
168
 
 
169
    def finished(self):
 
170
        """Return this bar to its progress stack."""
 
171
        self.clear()
 
172
        assert self._stack is not None
 
173
        self._stack.return_pb(self)
 
174
 
 
175
    def note(self, fmt_string, *args, **kwargs):
 
176
        """Record a note without disrupting the progress bar."""
 
177
        self.clear()
 
178
        self.to_messages_file.write(fmt_string % args)
 
179
        self.to_messages_file.write('\n')
 
180
 
 
181
    def child_progress(self, **kwargs):
 
182
        return ChildProgress(**kwargs)
 
183
 
 
184
 
 
185
class DummyProgress(_BaseProgressBar):
 
186
    """Progress-bar standin that does nothing.
 
187
 
 
188
    This can be used as the default argument for methods that
 
189
    take an optional progress indicator."""
 
190
    def tick(self):
 
191
        pass
 
192
 
 
193
    def update(self, msg=None, current=None, total=None):
 
194
        pass
 
195
 
 
196
    def child_update(self, message, current, total):
 
197
        pass
 
198
 
 
199
    def clear(self):
 
200
        pass
 
201
        
 
202
    def note(self, fmt_string, *args, **kwargs):
 
203
        """See _BaseProgressBar.note()."""
 
204
 
 
205
    def child_progress(self, **kwargs):
 
206
        return DummyProgress(**kwargs)
 
207
 
 
208
 
 
209
class DotsProgressBar(_BaseProgressBar):
 
210
 
 
211
    def __init__(self, **kwargs):
 
212
        _BaseProgressBar.__init__(self, **kwargs)
 
213
        self.last_msg = None
 
214
        self.need_nl = False
 
215
        
 
216
    def tick(self):
 
217
        self.update()
 
218
        
 
219
    def update(self, msg=None, current_cnt=None, total_cnt=None):
 
220
        if msg and msg != self.last_msg:
 
221
            if self.need_nl:
 
222
                self.to_file.write('\n')
 
223
            self.to_file.write(msg + ': ')
 
224
            self.last_msg = msg
 
225
        self.need_nl = True
 
226
        self.to_file.write('.')
 
227
        
 
228
    def clear(self):
 
229
        if self.need_nl:
 
230
            self.to_file.write('\n')
 
231
        self.need_nl = False
 
232
        
 
233
    def child_update(self, message, current, total):
 
234
        self.tick()
 
235
 
 
236
    
 
237
class TTYProgressBar(_BaseProgressBar):
 
238
    """Progress bar display object.
 
239
 
 
240
    Several options are available to control the display.  These can
 
241
    be passed as parameters to the constructor or assigned at any time:
 
242
 
 
243
    show_pct
 
244
        Show percentage complete.
 
245
    show_spinner
 
246
        Show rotating baton.  This ticks over on every update even
 
247
        if the values don't change.
 
248
    show_eta
 
249
        Show predicted time-to-completion.
 
250
    show_bar
 
251
        Show bar graph.
 
252
    show_count
 
253
        Show numerical counts.
 
254
 
 
255
    The output file should be in line-buffered or unbuffered mode.
 
256
    """
 
257
    SPIN_CHARS = r'/-\|'
 
258
 
 
259
 
 
260
    def __init__(self, **kwargs):
 
261
        from bzrlib.osutils import terminal_width
 
262
        _BaseProgressBar.__init__(self, **kwargs)
 
263
        self.spin_pos = 0
 
264
        self.width = terminal_width()
 
265
        self.last_updates = deque()
 
266
        self.child_fraction = 0
 
267
        self._have_output = False
 
268
    
 
269
 
 
270
    def throttle(self, old_msg):
 
271
        """Return True if the bar was updated too recently"""
 
272
        # time.time consistently takes 40/4000 ms = 0.01 ms.
 
273
        # but every single update to the pb invokes it.
 
274
        # so we use time.clock which takes 20/4000 ms = 0.005ms
 
275
        # on the downside, time.clock() appears to have approximately
 
276
        # 10ms granularity, so we treat a zero-time change as 'throttled.'
 
277
        now = time.clock()
 
278
        if self.start_time is not None and (now - self.start_time) < 1:
 
279
            return True
 
280
        if old_msg != self.last_msg:
 
281
            return False
 
282
        interval = now - self.last_update
 
283
        # if interval > 0
 
284
        if interval < self.MIN_PAUSE:
 
285
            return True
 
286
 
 
287
        self.last_updates.append(now - self.last_update)
 
288
        self.last_update = now
 
289
        return False
 
290
        
 
291
    def tick(self):
 
292
        self.update(self.last_msg, self.last_cnt, self.last_total, 
 
293
                    self.child_fraction)
 
294
 
 
295
    def child_update(self, message, current, total):
 
296
        if current is not None and total != 0:
 
297
            child_fraction = float(current) / total
 
298
            if self.last_cnt is None:
 
299
                pass
 
300
            elif self.last_cnt + child_fraction <= self.last_total:
 
301
                self.child_fraction = child_fraction
 
302
            else:
 
303
                mutter('not updating child fraction')
 
304
        if self.last_msg is None:
 
305
            self.last_msg = ''
 
306
        self.tick()
 
307
 
 
308
    def update(self, msg, current_cnt=None, total_cnt=None, 
 
309
               child_fraction=0):
 
310
        """Update and redraw progress bar."""
 
311
        if msg is None:
 
312
            msg = self.last_msg
 
313
 
 
314
        if total_cnt is None:
 
315
            total_cnt = self.last_total
 
316
 
 
317
        if current_cnt < 0:
 
318
            current_cnt = 0
 
319
            
 
320
        if current_cnt > total_cnt:
 
321
            total_cnt = current_cnt
 
322
        
 
323
        ## # optional corner case optimisation 
 
324
        ## # currently does not seem to fire so costs more than saved.
 
325
        ## # trivial optimal case:
 
326
        ## # NB if callers are doing a clear and restore with
 
327
        ## # the saved values, this will prevent that:
 
328
        ## # in that case add a restore method that calls
 
329
        ## # _do_update or some such
 
330
        ## if (self.last_msg == msg and
 
331
        ##     self.last_cnt == current_cnt and
 
332
        ##     self.last_total == total_cnt and
 
333
        ##     self.child_fraction == child_fraction):
 
334
        ##     return
 
335
 
 
336
        old_msg = self.last_msg
 
337
        # save these for the tick() function
 
338
        self.last_msg = msg
 
339
        self.last_cnt = current_cnt
 
340
        self.last_total = total_cnt
 
341
        self.child_fraction = child_fraction
 
342
 
 
343
        # each function call takes 20ms/4000 = 0.005 ms, 
 
344
        # but multiple that by 4000 calls -> starts to cost.
 
345
        # so anything to make this function call faster
 
346
        # will improve base 'diff' time by up to 0.1 seconds.
 
347
        if self.throttle(old_msg):
 
348
            return
 
349
 
 
350
        if self.show_eta and self.start_time and self.last_total:
 
351
            eta = get_eta(self.start_time, self.last_cnt + self.child_fraction, 
 
352
                    self.last_total, last_updates = self.last_updates)
 
353
            eta_str = " " + str_tdelta(eta)
 
354
        else:
 
355
            eta_str = ""
 
356
 
 
357
        if self.show_spinner:
 
358
            spin_str = self.SPIN_CHARS[self.spin_pos % 4] + ' '            
 
359
        else:
 
360
            spin_str = ''
 
361
 
 
362
        # always update this; it's also used for the bar
 
363
        self.spin_pos += 1
 
364
 
 
365
        if self.show_pct and self.last_total and self.last_cnt:
 
366
            pct = 100.0 * ((self.last_cnt + self.child_fraction) / self.last_total)
 
367
            pct_str = ' (%5.1f%%)' % pct
 
368
        else:
 
369
            pct_str = ''
 
370
 
 
371
        if not self.show_count:
 
372
            count_str = ''
 
373
        elif self.last_cnt is None:
 
374
            count_str = ''
 
375
        elif self.last_total is None:
 
376
            count_str = ' %i' % (self.last_cnt)
 
377
        else:
 
378
            # make both fields the same size
 
379
            t = '%i' % (self.last_total)
 
380
            c = '%*i' % (len(t), self.last_cnt)
 
381
            count_str = ' ' + c + '/' + t 
 
382
 
 
383
        if self.show_bar:
 
384
            # progress bar, if present, soaks up all remaining space
 
385
            cols = self.width - 1 - len(self.last_msg) - len(spin_str) - len(pct_str) \
 
386
                   - len(eta_str) - len(count_str) - 3
 
387
 
 
388
            if self.last_total:
 
389
                # number of markers highlighted in bar
 
390
                markers = int(round(float(cols) * 
 
391
                              (self.last_cnt + self.child_fraction) / self.last_total))
 
392
                bar_str = '[' + ('=' * markers).ljust(cols) + '] '
 
393
            elif False:
 
394
                # don't know total, so can't show completion.
 
395
                # so just show an expanded spinning thingy
 
396
                m = self.spin_pos % cols
 
397
                ms = (' ' * m + '*').ljust(cols)
 
398
                
 
399
                bar_str = '[' + ms + '] '
 
400
            else:
 
401
                bar_str = ''
 
402
        else:
 
403
            bar_str = ''
 
404
 
 
405
        m = spin_str + bar_str + self.last_msg + count_str + pct_str + eta_str
 
406
 
 
407
        assert len(m) < self.width
 
408
        self.to_file.write('\r' + m.ljust(self.width - 1))
 
409
        self._have_output = True
 
410
        #self.to_file.flush()
 
411
            
 
412
    def clear(self):        
 
413
        if self._have_output:
 
414
            self.to_file.write('\r%s\r' % (' ' * (self.width - 1)))
 
415
        self._have_output = False
 
416
        #self.to_file.flush()        
 
417
 
 
418
 
 
419
class ChildProgress(_BaseProgressBar):
 
420
    """A progress indicator that pushes its data to the parent"""
 
421
 
 
422
    def __init__(self, _stack, **kwargs):
 
423
        _BaseProgressBar.__init__(self, _stack=_stack, **kwargs)
 
424
        self.parent = _stack.top()
 
425
        self.current = None
 
426
        self.total = None
 
427
        self.child_fraction = 0
 
428
        self.message = None
 
429
 
 
430
    def update(self, msg, current_cnt=None, total_cnt=None):
 
431
        self.current = current_cnt
 
432
        self.total = total_cnt
 
433
        self.message = msg
 
434
        self.child_fraction = 0
 
435
        self.tick()
 
436
 
 
437
    def child_update(self, message, current, total):
 
438
        if current is None or total == 0:
 
439
            self.child_fraction = 0
 
440
        else:
 
441
            self.child_fraction = float(current) / total
 
442
        self.tick()
 
443
 
 
444
    def tick(self):
 
445
        if self.current is None:
 
446
            count = None
 
447
        else:
 
448
            count = self.current+self.child_fraction
 
449
            if count > self.total:
 
450
                if __debug__:
 
451
                    mutter('clamping count of %d to %d' % (count, self.total))
 
452
                count = self.total
 
453
        self.parent.child_update(self.message, count, self.total)
 
454
 
 
455
    def clear(self):
 
456
        pass
 
457
 
 
458
    def note(self, *args, **kwargs):
 
459
        self.parent.note(*args, **kwargs)
 
460
 
 
461
 
 
462
def str_tdelta(delt):
 
463
    if delt is None:
 
464
        return "-:--:--"
 
465
    delt = int(round(delt))
 
466
    return '%d:%02d:%02d' % (delt/3600,
 
467
                             (delt/60) % 60,
 
468
                             delt % 60)
 
469
 
 
470
 
 
471
def get_eta(start_time, current, total, enough_samples=3, last_updates=None, n_recent=10):
 
472
    if start_time is None:
 
473
        return None
 
474
 
 
475
    if not total:
 
476
        return None
 
477
 
 
478
    if current < enough_samples:
 
479
        return None
 
480
 
 
481
    if current > total:
 
482
        return None                     # wtf?
 
483
 
 
484
    elapsed = time.clock() - start_time
 
485
 
 
486
    if elapsed < 2.0:                   # not enough time to estimate
 
487
        return None
 
488
    
 
489
    total_duration = float(elapsed) * float(total) / float(current)
 
490
 
 
491
    assert total_duration >= elapsed
 
492
 
 
493
    if last_updates and len(last_updates) >= n_recent:
 
494
        while len(last_updates) > n_recent:
 
495
            last_updates.popleft()
 
496
        avg = sum(last_updates) / float(len(last_updates))
 
497
        time_left = avg * (total - current)
 
498
 
 
499
        old_time_left = total_duration - elapsed
 
500
 
 
501
        # We could return the average, or some other value here
 
502
        return (time_left + old_time_left) / 2
 
503
 
 
504
    return total_duration - elapsed
 
505
 
 
506
 
 
507
class ProgressPhase(object):
 
508
    """Update progress object with the current phase"""
 
509
    def __init__(self, message, total, pb):
 
510
        object.__init__(self)
 
511
        self.pb = pb
 
512
        self.message = message
 
513
        self.total = total
 
514
        self.cur_phase = None
 
515
 
 
516
    def next_phase(self):
 
517
        if self.cur_phase is None:
 
518
            self.cur_phase = 0
 
519
        else:
 
520
            self.cur_phase += 1
 
521
        assert self.cur_phase < self.total 
 
522
        self.pb.update(self.message, self.cur_phase, self.total)
 
523
 
 
524
 
 
525
def run_tests():
 
526
    import doctest
 
527
    result = doctest.testmod()
 
528
    if result[1] > 0:
 
529
        if result[0] == 0:
 
530
            print "All tests passed"
 
531
    else:
 
532
        print "No tests to run"
 
533
 
 
534
 
 
535
def demo():
 
536
    sleep = time.sleep
 
537
    
 
538
    print 'dumb-terminal test:'
 
539
    pb = DotsProgressBar()
 
540
    for i in range(100):
 
541
        pb.update('Leoparden', i, 99)
 
542
        sleep(0.1)
 
543
    sleep(1.5)
 
544
    pb.clear()
 
545
    sleep(1.5)
 
546
    
 
547
    print 'smart-terminal test:'
 
548
    pb = ProgressBar(show_pct=True, show_bar=True, show_spinner=False)
 
549
    for i in range(100):
 
550
        pb.update('Elephanten', i, 99)
 
551
        sleep(0.1)
 
552
    sleep(2)
 
553
    pb.clear()
 
554
    sleep(1)
 
555
 
 
556
    print 'done!'
 
557
 
 
558
if __name__ == "__main__":
 
559
    demo()