~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/progress.py

  • Committer: Martin Pool
  • Date: 2009-06-23 06:58:46 UTC
  • mto: This revision was merged to the branch mainline in revision 4586.
  • Revision ID: mbp@sourcefrog.net-20090623065846-wvsuj9gip4e723i1
Update docstrings for recent progress changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
25
25
import sys
26
26
import time
27
27
import os
28
 
 
29
 
 
 
28
import warnings
 
29
 
 
30
 
 
31
from bzrlib import (
 
32
    errors,
 
33
    osutils,
 
34
    trace,
 
35
    ui,
 
36
    )
 
37
from bzrlib.trace import mutter
30
38
from bzrlib.symbol_versioning import (
 
39
    deprecated_function,
31
40
    deprecated_in,
32
41
    deprecated_method,
33
42
    )
34
43
 
35
44
 
 
45
# XXX: deprecated; can be removed when the ProgressBar factory is removed
36
46
def _supports_progress(f):
37
 
    """Detect if we can use pretty progress bars on file F.
 
47
    """Detect if we can use pretty progress bars on the output stream f.
38
48
 
39
49
    If this returns true we expect that a human may be looking at that
40
50
    output, and that we can repaint a line to update it.
41
 
 
42
 
    This doesn't check the policy for whether we *should* use them.
43
51
    """
44
52
    isatty = getattr(f, 'isatty', None)
45
53
    if isatty is None:
46
54
        return False
47
55
    if not isatty():
48
56
        return False
49
 
    # The following case also handles Win32 - on that platform $TERM is
50
 
    # typically never set, so the case None is treated as a smart terminal,
51
 
    # not dumb.  <https://bugs.launchpad.net/bugs/334808>  win32 files do have
52
 
    # isatty methods that return true.
53
57
    if os.environ.get('TERM') == 'dumb':
54
58
        # e.g. emacs compile window
55
59
        return False
65
69
    Code updating the task may also set fields as hints about how to display
66
70
    it: show_pct, show_spinner, show_eta, show_count, show_bar.  UIs
67
71
    will not necessarily respect all these fields.
68
 
    
69
 
    :ivar update_latency: The interval (in seconds) at which the PB should be
70
 
        updated.  Setting this to zero suggests every update should be shown
71
 
        synchronously.
72
 
 
73
 
    :ivar show_transport_activity: If true (default), transport activity
74
 
        will be shown when this task is drawn.  Disable it if you're sure 
75
 
        that only irrelevant or uninteresting transport activity can occur
76
 
        during this task.
77
72
    """
78
73
 
79
 
    def __init__(self, parent_task=None, ui_factory=None, progress_view=None):
 
74
    def __init__(self, parent_task=None, ui_factory=None):
80
75
        """Construct a new progress task.
81
76
 
82
 
        :param parent_task: Enclosing ProgressTask or None.
83
 
 
84
 
        :param progress_view: ProgressView to display this ProgressTask.
85
 
 
86
 
        :param ui_factory: The UI factory that will display updates; 
87
 
            deprecated in favor of passing progress_view directly.
88
 
 
89
77
        Normally you should not call this directly but rather through
90
78
        `ui_factory.nested_progress_bar`.
91
79
        """
94
82
        self.total_cnt = None
95
83
        self.current_cnt = None
96
84
        self.msg = ''
97
 
        # TODO: deprecate passing ui_factory
98
85
        self.ui_factory = ui_factory
99
 
        self.progress_view = progress_view
100
86
        self.show_pct = False
101
87
        self.show_spinner = True
102
88
        self.show_eta = False,
103
89
        self.show_count = True
104
90
        self.show_bar = True
105
 
        self.update_latency = 0.1
106
 
        self.show_transport_activity = True
107
91
 
108
92
    def __repr__(self):
109
93
        return '%s(%r/%r, msg=%r)' % (
117
101
        self.current_cnt = current_cnt
118
102
        if total_cnt:
119
103
            self.total_cnt = total_cnt
120
 
        if self.progress_view:
121
 
            self.progress_view.show_progress(self)
122
 
        else:
123
 
            self.ui_factory._progress_updated(self)
 
104
        self.ui_factory._progress_updated(self)
124
105
 
125
106
    def tick(self):
126
107
        self.update(self.msg)
127
108
 
128
109
    def finished(self):
129
 
        if self.progress_view:
130
 
            self.progress_view.task_finished(self)
131
 
        else:
132
 
            self.ui_factory._progress_finished(self)
 
110
        self.ui_factory._progress_finished(self)
133
111
 
134
112
    def make_sub_task(self):
135
 
        return ProgressTask(self, ui_factory=self.ui_factory,
136
 
            progress_view=self.progress_view)
 
113
        return ProgressTask(self, self.ui_factory)
137
114
 
138
115
    def _overall_completion_fraction(self, child_fraction=0.0):
139
116
        """Return fractional completion of this task and its parents
152
129
                own_fraction = 0.0
153
130
            return self._parent_task._overall_completion_fraction(own_fraction)
154
131
 
155
 
    @deprecated_method(deprecated_in((2, 1, 0)))
156
132
    def note(self, fmt_string, *args):
157
 
        """Record a note without disrupting the progress bar.
158
 
        
159
 
        Deprecated: use ui_factory.note() instead or bzrlib.trace.  Note that
160
 
        ui_factory.note takes just one string as the argument, not a format
161
 
        string and arguments.
162
 
        """
 
133
        """Record a note without disrupting the progress bar."""
 
134
        # XXX: shouldn't be here; put it in mutter or the ui instead
163
135
        if args:
164
136
            self.ui_factory.note(fmt_string % args)
165
137
        else:
166
138
            self.ui_factory.note(fmt_string)
167
139
 
168
140
    def clear(self):
169
 
        # TODO: deprecate this method; the model object shouldn't be concerned
170
 
        # with whether it's shown or not.  Most callers use this because they
171
 
        # want to write some different non-progress output to the screen, but
172
 
        # they should probably instead use a stream that's synchronized with
173
 
        # the progress output.  It may be there is a model-level use for
174
 
        # saying "this task's not active at the moment" but I don't see it. --
175
 
        # mbp 20090623
176
 
        if self.progress_view:
177
 
            self.progress_view.clear()
 
141
        # XXX: shouldn't be here; put it in mutter or the ui instead
 
142
        self.ui_factory.clear_term()
 
143
 
 
144
 
 
145
@deprecated_function(deprecated_in((1, 16, 0)))
 
146
def ProgressBar(to_file=None, **kwargs):
 
147
    """Construct a progress bar.
 
148
 
 
149
    Deprecated; ask the ui_factory for a progress task instead.
 
150
    """
 
151
    if to_file is None:
 
152
        to_file = sys.stderr
 
153
    requested_bar_type = os.environ.get('BZR_PROGRESS_BAR')
 
154
    # An value of '' or not set reverts to standard processing
 
155
    if requested_bar_type in (None, ''):
 
156
        if _supports_progress(to_file):
 
157
            return TTYProgressBar(to_file=to_file, **kwargs)
178
158
        else:
179
 
            self.ui_factory.clear_term()
180
 
 
181
 
 
182
 
# NOTE: This is also deprecated; you should provide a ProgressView instead.
 
159
            return DummyProgress(to_file=to_file, **kwargs)
 
160
    else:
 
161
        # Minor sanitation to prevent spurious errors
 
162
        requested_bar_type = requested_bar_type.lower().strip()
 
163
        # TODO: jam 20060710 Arguably we shouldn't raise an exception
 
164
        #       but should instead just disable progress bars if we
 
165
        #       don't recognize the type
 
166
        if requested_bar_type not in _progress_bar_types:
 
167
            raise errors.InvalidProgressBarType(requested_bar_type,
 
168
                                                _progress_bar_types.keys())
 
169
        return _progress_bar_types[requested_bar_type](to_file=to_file, **kwargs)
 
170
 
 
171
 
183
172
class _BaseProgressBar(object):
184
173
 
185
174
    def __init__(self,
226
215
        self.to_messages_file.write(fmt_string % args)
227
216
        self.to_messages_file.write('\n')
228
217
 
229
 
 
230
 
class DummyProgress(object):
 
218
    @deprecated_function(deprecated_in((1, 16, 0)))
 
219
    def child_progress(self, **kwargs):
 
220
        return ChildProgress(**kwargs)
 
221
 
 
222
 
 
223
class DummyProgress(_BaseProgressBar):
231
224
    """Progress-bar standin that does nothing.
232
225
 
233
 
    This was previously often constructed by application code if no progress
234
 
    bar was explicitly passed in.  That's no longer recommended: instead, just
235
 
    create a progress task from the ui_factory.  This class can be used in
236
 
    test code that needs to fake a progress task for some reason.
237
 
    """
 
226
    This can be used as the default argument for methods that
 
227
    take an optional progress indicator."""
238
228
 
239
229
    def tick(self):
240
230
        pass
255
245
        return DummyProgress(**kwargs)
256
246
 
257
247
 
 
248
class DotsProgressBar(_BaseProgressBar):
 
249
 
 
250
    @deprecated_function(deprecated_in((1, 16, 0)))
 
251
    def __init__(self, **kwargs):
 
252
        _BaseProgressBar.__init__(self, **kwargs)
 
253
        self.last_msg = None
 
254
        self.need_nl = False
 
255
 
 
256
    def tick(self):
 
257
        self.update()
 
258
 
 
259
    def update(self, msg=None, current_cnt=None, total_cnt=None):
 
260
        if msg and msg != self.last_msg:
 
261
            if self.need_nl:
 
262
                self.to_file.write('\n')
 
263
            self.to_file.write(msg + ': ')
 
264
            self.last_msg = msg
 
265
        self.need_nl = True
 
266
        self.to_file.write('.')
 
267
 
 
268
    def clear(self):
 
269
        if self.need_nl:
 
270
            self.to_file.write('\n')
 
271
        self.need_nl = False
 
272
 
 
273
    def child_update(self, message, current, total):
 
274
        self.tick()
 
275
 
 
276
 
 
277
class TTYProgressBar(_BaseProgressBar):
 
278
    """Progress bar display object.
 
279
 
 
280
    Several options are available to control the display.  These can
 
281
    be passed as parameters to the constructor or assigned at any time:
 
282
 
 
283
    show_pct
 
284
        Show percentage complete.
 
285
    show_spinner
 
286
        Show rotating baton.  This ticks over on every update even
 
287
        if the values don't change.
 
288
    show_eta
 
289
        Show predicted time-to-completion.
 
290
    show_bar
 
291
        Show bar graph.
 
292
    show_count
 
293
        Show numerical counts.
 
294
 
 
295
    The output file should be in line-buffered or unbuffered mode.
 
296
    """
 
297
    SPIN_CHARS = r'/-\|'
 
298
 
 
299
    @deprecated_function(deprecated_in((1, 16, 0)))
 
300
    def __init__(self, **kwargs):
 
301
        from bzrlib.osutils import terminal_width
 
302
        _BaseProgressBar.__init__(self, **kwargs)
 
303
        self.spin_pos = 0
 
304
        self.width = terminal_width()
 
305
        self.last_updates = []
 
306
        self._max_last_updates = 10
 
307
        self.child_fraction = 0
 
308
        self._have_output = False
 
309
 
 
310
    def throttle(self, old_msg):
 
311
        """Return True if the bar was updated too recently"""
 
312
        # time.time consistently takes 40/4000 ms = 0.01 ms.
 
313
        # time.clock() is faster, but gives us CPU time, not wall-clock time
 
314
        now = time.time()
 
315
        if self.start_time is not None and (now - self.start_time) < 1:
 
316
            return True
 
317
        if old_msg != self.last_msg:
 
318
            return False
 
319
        interval = now - self.last_update
 
320
        # if interval > 0
 
321
        if interval < self.MIN_PAUSE:
 
322
            return True
 
323
 
 
324
        self.last_updates.append(now - self.last_update)
 
325
        # Don't let the queue grow without bound
 
326
        self.last_updates = self.last_updates[-self._max_last_updates:]
 
327
        self.last_update = now
 
328
        return False
 
329
 
 
330
    def tick(self):
 
331
        self.update(self.last_msg, self.last_cnt, self.last_total,
 
332
                    self.child_fraction)
 
333
 
 
334
    def child_update(self, message, current, total):
 
335
        if current is not None and total != 0:
 
336
            child_fraction = float(current) / total
 
337
            if self.last_cnt is None:
 
338
                pass
 
339
            elif self.last_cnt + child_fraction <= self.last_total:
 
340
                self.child_fraction = child_fraction
 
341
        if self.last_msg is None:
 
342
            self.last_msg = ''
 
343
        self.tick()
 
344
 
 
345
    def update(self, msg, current_cnt=None, total_cnt=None,
 
346
            child_fraction=0):
 
347
        """Update and redraw progress bar.
 
348
        """
 
349
        if msg is None:
 
350
            msg = self.last_msg
 
351
 
 
352
        if total_cnt is None:
 
353
            total_cnt = self.last_total
 
354
 
 
355
        if current_cnt < 0:
 
356
            current_cnt = 0
 
357
 
 
358
        if current_cnt > total_cnt:
 
359
            total_cnt = current_cnt
 
360
 
 
361
        ## # optional corner case optimisation
 
362
        ## # currently does not seem to fire so costs more than saved.
 
363
        ## # trivial optimal case:
 
364
        ## # NB if callers are doing a clear and restore with
 
365
        ## # the saved values, this will prevent that:
 
366
        ## # in that case add a restore method that calls
 
367
        ## # _do_update or some such
 
368
        ## if (self.last_msg == msg and
 
369
        ##     self.last_cnt == current_cnt and
 
370
        ##     self.last_total == total_cnt and
 
371
        ##     self.child_fraction == child_fraction):
 
372
        ##     return
 
373
 
 
374
        if msg is None:
 
375
            msg = ''
 
376
 
 
377
        old_msg = self.last_msg
 
378
        # save these for the tick() function
 
379
        self.last_msg = msg
 
380
        self.last_cnt = current_cnt
 
381
        self.last_total = total_cnt
 
382
        self.child_fraction = child_fraction
 
383
 
 
384
        # each function call takes 20ms/4000 = 0.005 ms,
 
385
        # but multiple that by 4000 calls -> starts to cost.
 
386
        # so anything to make this function call faster
 
387
        # will improve base 'diff' time by up to 0.1 seconds.
 
388
        if self.throttle(old_msg):
 
389
            return
 
390
 
 
391
        if self.show_eta and self.start_time and self.last_total:
 
392
            eta = get_eta(self.start_time, self.last_cnt + self.child_fraction,
 
393
                    self.last_total, last_updates = self.last_updates)
 
394
            eta_str = " " + str_tdelta(eta)
 
395
        else:
 
396
            eta_str = ""
 
397
 
 
398
        if self.show_spinner:
 
399
            spin_str = self.SPIN_CHARS[self.spin_pos % 4] + ' '
 
400
        else:
 
401
            spin_str = ''
 
402
 
 
403
        # always update this; it's also used for the bar
 
404
        self.spin_pos += 1
 
405
 
 
406
        if self.show_pct and self.last_total and self.last_cnt:
 
407
            pct = 100.0 * ((self.last_cnt + self.child_fraction) / self.last_total)
 
408
            pct_str = ' (%5.1f%%)' % pct
 
409
        else:
 
410
            pct_str = ''
 
411
 
 
412
        if not self.show_count:
 
413
            count_str = ''
 
414
        elif self.last_cnt is None:
 
415
            count_str = ''
 
416
        elif self.last_total is None:
 
417
            count_str = ' %i' % (self.last_cnt)
 
418
        else:
 
419
            # make both fields the same size
 
420
            t = '%i' % (self.last_total)
 
421
            c = '%*i' % (len(t), self.last_cnt)
 
422
            count_str = ' ' + c + '/' + t
 
423
 
 
424
        if self.show_bar:
 
425
            # progress bar, if present, soaks up all remaining space
 
426
            cols = self.width - 1 - len(self.last_msg) - len(spin_str) - len(pct_str) \
 
427
                   - len(eta_str) - len(count_str) - 3
 
428
 
 
429
            if self.last_total:
 
430
                # number of markers highlighted in bar
 
431
                markers = int(round(float(cols) *
 
432
                              (self.last_cnt + self.child_fraction) / self.last_total))
 
433
                bar_str = '[' + ('=' * markers).ljust(cols) + '] '
 
434
            elif False:
 
435
                # don't know total, so can't show completion.
 
436
                # so just show an expanded spinning thingy
 
437
                m = self.spin_pos % cols
 
438
                ms = (' ' * m + '*').ljust(cols)
 
439
 
 
440
                bar_str = '[' + ms + '] '
 
441
            else:
 
442
                bar_str = ''
 
443
        else:
 
444
            bar_str = ''
 
445
 
 
446
        m = spin_str + bar_str + self.last_msg + count_str \
 
447
            + pct_str + eta_str
 
448
        self.to_file.write('\r%-*.*s' % (self.width - 1, self.width - 1, m))
 
449
        self._have_output = True
 
450
        #self.to_file.flush()
 
451
 
 
452
    def clear(self):
 
453
        if self._have_output:
 
454
            self.to_file.write('\r%s\r' % (' ' * (self.width - 1)))
 
455
        self._have_output = False
 
456
        #self.to_file.flush()
 
457
 
 
458
 
 
459
class ChildProgress(_BaseProgressBar):
 
460
    """A progress indicator that pushes its data to the parent"""
 
461
 
 
462
    @deprecated_function(deprecated_in((1, 16, 0)))
 
463
    def __init__(self, _stack, **kwargs):
 
464
        _BaseProgressBar.__init__(self, _stack=_stack, **kwargs)
 
465
        self.parent = _stack.top()
 
466
        self.current = None
 
467
        self.total = None
 
468
        self.child_fraction = 0
 
469
        self.message = None
 
470
 
 
471
    def update(self, msg, current_cnt=None, total_cnt=None):
 
472
        self.current = current_cnt
 
473
        if total_cnt is not None:
 
474
            self.total = total_cnt
 
475
        self.message = msg
 
476
        self.child_fraction = 0
 
477
        self.tick()
 
478
 
 
479
    def child_update(self, message, current, total):
 
480
        if current is None or total == 0:
 
481
            self.child_fraction = 0
 
482
        else:
 
483
            self.child_fraction = float(current) / total
 
484
        self.tick()
 
485
 
 
486
    def tick(self):
 
487
        if self.current is None:
 
488
            count = None
 
489
        else:
 
490
            count = self.current+self.child_fraction
 
491
            if count > self.total:
 
492
                if __debug__:
 
493
                    mutter('clamping count of %d to %d' % (count, self.total))
 
494
                count = self.total
 
495
        self.parent.child_update(self.message, count, self.total)
 
496
 
 
497
    def clear(self):
 
498
        pass
 
499
 
 
500
    def note(self, *args, **kwargs):
 
501
        self.parent.note(*args, **kwargs)
 
502
 
 
503
 
258
504
def str_tdelta(delt):
259
505
    if delt is None:
260
506
        return "-:--:--"
311
557
        else:
312
558
            self.cur_phase += 1
313
559
        self.pb.update(self.message, self.cur_phase, self.total)
 
560
 
 
561
 
 
562
_progress_bar_types = {}
 
563
_progress_bar_types['dummy'] = DummyProgress
 
564
_progress_bar_types['none'] = DummyProgress
 
565
_progress_bar_types['tty'] = TTYProgressBar
 
566
_progress_bar_types['dots'] = DotsProgressBar