~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/progress.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-07 16:05:27 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607160527-2b3649154d0e2e84
more code cleanup

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca>
2
 
# Copyright (C) 2005, 2006 Canonical Ltd
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
 
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
17
 
18
18
 
19
19
"""Simple text-mode progress indicator.
35
35
# TODO: Optionally show elapsed time instead/as well as ETA; nicer
36
36
# when the rate is unpredictable
37
37
 
 
38
 
38
39
import sys
39
40
import time
40
41
import os
41
 
 
42
 
from bzrlib.lazy_import import lazy_import
43
 
lazy_import(globals(), """
44
 
from bzrlib import (
45
 
    errors,
46
 
    )
47
 
""")
48
 
 
49
 
from bzrlib.trace import mutter
 
42
from collections import deque
 
43
 
 
44
 
 
45
import bzrlib.errors as errors
 
46
from bzrlib.trace import mutter 
50
47
 
51
48
 
52
49
def _supports_progress(f):
53
 
    isatty = getattr(f, 'isatty', None)
54
 
    if isatty is None:
 
50
    if not hasattr(f, 'isatty'):
55
51
        return False
56
 
    if not isatty():
 
52
    if not f.isatty():
57
53
        return False
58
54
    if os.environ.get('TERM') == 'dumb':
59
55
        # e.g. emacs compile window
61
57
    return True
62
58
 
63
59
 
64
 
_progress_bar_types = {}
65
 
 
66
60
 
67
61
def ProgressBar(to_file=None, **kwargs):
68
62
    """Abstract factory"""
69
63
    if to_file is None:
70
64
        to_file = sys.stderr
71
 
    requested_bar_type = os.environ.get('BZR_PROGRESS_BAR')
72
 
    # An value of '' or not set reverts to standard processing
73
 
    if requested_bar_type in (None, ''):
74
 
        if _supports_progress(to_file):
75
 
            return TTYProgressBar(to_file=to_file, **kwargs)
76
 
        else:
77
 
            return DotsProgressBar(to_file=to_file, **kwargs)
 
65
    if _supports_progress(to_file):
 
66
        return TTYProgressBar(to_file=to_file, **kwargs)
78
67
    else:
79
 
        # Minor sanitation to prevent spurious errors
80
 
        requested_bar_type = requested_bar_type.lower().strip()
81
 
        # TODO: jam 20060710 Arguably we shouldn't raise an exception
82
 
        #       but should instead just disable progress bars if we
83
 
        #       don't recognize the type
84
 
        if requested_bar_type not in _progress_bar_types:
85
 
            raise errors.InvalidProgressBarType(requested_bar_type,
86
 
                                                _progress_bar_types.keys())
87
 
        return _progress_bar_types[requested_bar_type](to_file=to_file, **kwargs)
88
 
 
 
68
        return DotsProgressBar(to_file=to_file, **kwargs)
 
69
    
89
70
 
90
71
class ProgressBarStack(object):
91
72
    """A stack of progress bars."""
112
93
        self._show_count = show_count
113
94
        self._to_messages_file = to_messages_file
114
95
        self._stack = []
115
 
        self._klass = klass or ProgressBar
 
96
        self._klass = klass or TTYProgressBar
116
97
 
117
98
    def top(self):
118
99
        if len(self._stack) != 0:
156
137
                 to_file=None,
157
138
                 show_pct=False,
158
139
                 show_spinner=False,
159
 
                 show_eta=False,
 
140
                 show_eta=True,
160
141
                 show_bar=True,
161
142
                 show_count=True,
162
143
                 to_messages_file=None,
179
160
        self._stack = _stack
180
161
        # seed throttler
181
162
        self.MIN_PAUSE = 0.1 # seconds
182
 
        now = time.time()
 
163
        now = time.clock()
183
164
        # starting now
184
165
        self.start_time = now
185
166
        # next update should not throttle
225
206
        return DummyProgress(**kwargs)
226
207
 
227
208
 
228
 
_progress_bar_types['dummy'] = DummyProgress
229
 
_progress_bar_types['none'] = DummyProgress
230
 
 
231
 
 
232
209
class DotsProgressBar(_BaseProgressBar):
233
210
 
234
211
    def __init__(self, **kwargs):
256
233
    def child_update(self, message, current, total):
257
234
        self.tick()
258
235
 
259
 
 
260
 
_progress_bar_types['dots'] = DotsProgressBar
261
 
 
262
236
    
263
237
class TTYProgressBar(_BaseProgressBar):
264
238
    """Progress bar display object.
288
262
        _BaseProgressBar.__init__(self, **kwargs)
289
263
        self.spin_pos = 0
290
264
        self.width = terminal_width()
291
 
        self.last_updates = []
292
 
        self._max_last_updates = 10
 
265
        self.start_time = None
 
266
        self.last_updates = deque()
293
267
        self.child_fraction = 0
294
 
        self._have_output = False
295
268
    
296
269
 
297
 
    def throttle(self, old_msg):
 
270
    def throttle(self):
298
271
        """Return True if the bar was updated too recently"""
299
272
        # time.time consistently takes 40/4000 ms = 0.01 ms.
300
 
        # time.clock() is faster, but gives us CPU time, not wall-clock time
301
 
        now = time.time()
302
 
        if self.start_time is not None and (now - self.start_time) < 1:
303
 
            return True
304
 
        if old_msg != self.last_msg:
305
 
            return False
 
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
        
 
278
        now = time.clock()
306
279
        interval = now - self.last_update
307
280
        # if interval > 0
308
281
        if interval < self.MIN_PAUSE:
309
282
            return True
310
283
 
311
284
        self.last_updates.append(now - self.last_update)
312
 
        # Don't let the queue grow without bound
313
 
        self.last_updates = self.last_updates[-self._max_last_updates:]
314
285
        self.last_update = now
315
286
        return False
316
287
        
370
341
        # but multiple that by 4000 calls -> starts to cost.
371
342
        # so anything to make this function call faster
372
343
        # will improve base 'diff' time by up to 0.1 seconds.
373
 
        if self.throttle(old_msg):
 
344
        if old_msg == self.last_msg and self.throttle():
374
345
            return
375
346
 
376
347
        if self.show_eta and self.start_time and self.last_total:
429
400
            bar_str = ''
430
401
 
431
402
        m = spin_str + bar_str + self.last_msg + count_str + pct_str + eta_str
432
 
        self.to_file.write('\r%-*.*s' % (self.width - 1, self.width - 1, m))
433
 
        self._have_output = True
 
403
 
 
404
        assert len(m) < self.width
 
405
        self.to_file.write('\r' + m.ljust(self.width - 1))
434
406
        #self.to_file.flush()
435
407
            
436
408
    def clear(self):        
437
 
        if self._have_output:
438
 
            self.to_file.write('\r%s\r' % (' ' * (self.width - 1)))
439
 
        self._have_output = False
 
409
        self.to_file.write('\r%s\r' % (' ' * (self.width - 1)))
440
410
        #self.to_file.flush()        
441
411
 
442
412
 
443
 
_progress_bar_types['tty'] = TTYProgressBar
444
 
 
445
 
 
446
413
class ChildProgress(_BaseProgressBar):
447
414
    """A progress indicator that pushes its data to the parent"""
448
415
 
508
475
    if current > total:
509
476
        return None                     # wtf?
510
477
 
511
 
    elapsed = time.time() - start_time
 
478
    elapsed = time.clock() - start_time
512
479
 
513
480
    if elapsed < 2.0:                   # not enough time to estimate
514
481
        return None
518
485
    assert total_duration >= elapsed
519
486
 
520
487
    if last_updates and len(last_updates) >= n_recent:
 
488
        while len(last_updates) > n_recent:
 
489
            last_updates.popleft()
521
490
        avg = sum(last_updates) / float(len(last_updates))
522
491
        time_left = avg * (total - current)
523
492