/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: Martin Pool
  • Date: 2009-06-23 09:17:21 UTC
  • mto: (4712.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4715.
  • Revision ID: mbp@sourcefrog.net-20090623091721-ix4tpdsj2i9g1fxb
Deprecate ProgressTask.note

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)))
 
132
    @deprecated_method(deprecated_in((1, 17, 0)))
156
133
    def note(self, fmt_string, *args):
157
134
        """Record a note without disrupting the progress bar.
158
135
        
173
150
        # the progress output.  It may be there is a model-level use for
174
151
        # saying "this task's not active at the moment" but I don't see it. --
175
152
        # mbp 20090623
176
 
        if self.progress_view:
177
 
            self.progress_view.clear()
 
153
        self.ui_factory.clear_term()
 
154
 
 
155
 
 
156
@deprecated_function(deprecated_in((1, 16, 0)))
 
157
def ProgressBar(to_file=None, **kwargs):
 
158
    """Abstract factory"""
 
159
    if to_file is None:
 
160
        to_file = sys.stderr
 
161
    requested_bar_type = os.environ.get('BZR_PROGRESS_BAR')
 
162
    # An value of '' or not set reverts to standard processing
 
163
    if requested_bar_type in (None, ''):
 
164
        if _supports_progress(to_file):
 
165
            return TTYProgressBar(to_file=to_file, **kwargs)
178
166
        else:
179
 
            self.ui_factory.clear_term()
180
 
 
181
 
 
182
 
# NOTE: This is also deprecated; you should provide a ProgressView instead.
 
167
            return DummyProgress(to_file=to_file, **kwargs)
 
168
    else:
 
169
        # Minor sanitation to prevent spurious errors
 
170
        requested_bar_type = requested_bar_type.lower().strip()
 
171
        # TODO: jam 20060710 Arguably we shouldn't raise an exception
 
172
        #       but should instead just disable progress bars if we
 
173
        #       don't recognize the type
 
174
        if requested_bar_type not in _progress_bar_types:
 
175
            raise errors.InvalidProgressBarType(requested_bar_type,
 
176
                                                _progress_bar_types.keys())
 
177
        return _progress_bar_types[requested_bar_type](to_file=to_file, **kwargs)
 
178
 
 
179
 
183
180
class _BaseProgressBar(object):
184
181
 
185
182
    def __init__(self,
226
223
        self.to_messages_file.write(fmt_string % args)
227
224
        self.to_messages_file.write('\n')
228
225
 
229
 
 
230
 
class DummyProgress(object):
 
226
    @deprecated_function(deprecated_in((1, 16, 0)))
 
227
    def child_progress(self, **kwargs):
 
228
        return ChildProgress(**kwargs)
 
229
 
 
230
 
 
231
class DummyProgress(_BaseProgressBar):
231
232
    """Progress-bar standin that does nothing.
232
233
 
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
 
    """
 
234
    This can be used as the default argument for methods that
 
235
    take an optional progress indicator."""
238
236
 
239
237
    def tick(self):
240
238
        pass
255
253
        return DummyProgress(**kwargs)
256
254
 
257
255
 
 
256
class DotsProgressBar(_BaseProgressBar):
 
257
 
 
258
    @deprecated_function(deprecated_in((1, 16, 0)))
 
259
    def __init__(self, **kwargs):
 
260
        _BaseProgressBar.__init__(self, **kwargs)
 
261
        self.last_msg = None
 
262
        self.need_nl = False
 
263
 
 
264
    def tick(self):
 
265
        self.update()
 
266
 
 
267
    def update(self, msg=None, current_cnt=None, total_cnt=None):
 
268
        if msg and msg != self.last_msg:
 
269
            if self.need_nl:
 
270
                self.to_file.write('\n')
 
271
            self.to_file.write(msg + ': ')
 
272
            self.last_msg = msg
 
273
        self.need_nl = True
 
274
        self.to_file.write('.')
 
275
 
 
276
    def clear(self):
 
277
        if self.need_nl:
 
278
            self.to_file.write('\n')
 
279
        self.need_nl = False
 
280
 
 
281
    def child_update(self, message, current, total):
 
282
        self.tick()
 
283
 
 
284
 
 
285
class TTYProgressBar(_BaseProgressBar):
 
286
    """Progress bar display object.
 
287
 
 
288
    Several options are available to control the display.  These can
 
289
    be passed as parameters to the constructor or assigned at any time:
 
290
 
 
291
    show_pct
 
292
        Show percentage complete.
 
293
    show_spinner
 
294
        Show rotating baton.  This ticks over on every update even
 
295
        if the values don't change.
 
296
    show_eta
 
297
        Show predicted time-to-completion.
 
298
    show_bar
 
299
        Show bar graph.
 
300
    show_count
 
301
        Show numerical counts.
 
302
 
 
303
    The output file should be in line-buffered or unbuffered mode.
 
304
    """
 
305
    SPIN_CHARS = r'/-\|'
 
306
 
 
307
    @deprecated_function(deprecated_in((1, 16, 0)))
 
308
    def __init__(self, **kwargs):
 
309
        from bzrlib.osutils import terminal_width
 
310
        _BaseProgressBar.__init__(self, **kwargs)
 
311
        self.spin_pos = 0
 
312
        self.width = terminal_width()
 
313
        self.last_updates = []
 
314
        self._max_last_updates = 10
 
315
        self.child_fraction = 0
 
316
        self._have_output = False
 
317
 
 
318
    def throttle(self, old_msg):
 
319
        """Return True if the bar was updated too recently"""
 
320
        # time.time consistently takes 40/4000 ms = 0.01 ms.
 
321
        # time.clock() is faster, but gives us CPU time, not wall-clock time
 
322
        now = time.time()
 
323
        if self.start_time is not None and (now - self.start_time) < 1:
 
324
            return True
 
325
        if old_msg != self.last_msg:
 
326
            return False
 
327
        interval = now - self.last_update
 
328
        # if interval > 0
 
329
        if interval < self.MIN_PAUSE:
 
330
            return True
 
331
 
 
332
        self.last_updates.append(now - self.last_update)
 
333
        # Don't let the queue grow without bound
 
334
        self.last_updates = self.last_updates[-self._max_last_updates:]
 
335
        self.last_update = now
 
336
        return False
 
337
 
 
338
    def tick(self):
 
339
        self.update(self.last_msg, self.last_cnt, self.last_total,
 
340
                    self.child_fraction)
 
341
 
 
342
    def child_update(self, message, current, total):
 
343
        if current is not None and total != 0:
 
344
            child_fraction = float(current) / total
 
345
            if self.last_cnt is None:
 
346
                pass
 
347
            elif self.last_cnt + child_fraction <= self.last_total:
 
348
                self.child_fraction = child_fraction
 
349
        if self.last_msg is None:
 
350
            self.last_msg = ''
 
351
        self.tick()
 
352
 
 
353
    def update(self, msg, current_cnt=None, total_cnt=None,
 
354
            child_fraction=0):
 
355
        """Update and redraw progress bar.
 
356
        """
 
357
        if msg is None:
 
358
            msg = self.last_msg
 
359
 
 
360
        if total_cnt is None:
 
361
            total_cnt = self.last_total
 
362
 
 
363
        if current_cnt < 0:
 
364
            current_cnt = 0
 
365
 
 
366
        if current_cnt > total_cnt:
 
367
            total_cnt = current_cnt
 
368
 
 
369
        ## # optional corner case optimisation
 
370
        ## # currently does not seem to fire so costs more than saved.
 
371
        ## # trivial optimal case:
 
372
        ## # NB if callers are doing a clear and restore with
 
373
        ## # the saved values, this will prevent that:
 
374
        ## # in that case add a restore method that calls
 
375
        ## # _do_update or some such
 
376
        ## if (self.last_msg == msg and
 
377
        ##     self.last_cnt == current_cnt and
 
378
        ##     self.last_total == total_cnt and
 
379
        ##     self.child_fraction == child_fraction):
 
380
        ##     return
 
381
 
 
382
        if msg is None:
 
383
            msg = ''
 
384
 
 
385
        old_msg = self.last_msg
 
386
        # save these for the tick() function
 
387
        self.last_msg = msg
 
388
        self.last_cnt = current_cnt
 
389
        self.last_total = total_cnt
 
390
        self.child_fraction = child_fraction
 
391
 
 
392
        # each function call takes 20ms/4000 = 0.005 ms,
 
393
        # but multiple that by 4000 calls -> starts to cost.
 
394
        # so anything to make this function call faster
 
395
        # will improve base 'diff' time by up to 0.1 seconds.
 
396
        if self.throttle(old_msg):
 
397
            return
 
398
 
 
399
        if self.show_eta and self.start_time and self.last_total:
 
400
            eta = get_eta(self.start_time, self.last_cnt + self.child_fraction,
 
401
                    self.last_total, last_updates = self.last_updates)
 
402
            eta_str = " " + str_tdelta(eta)
 
403
        else:
 
404
            eta_str = ""
 
405
 
 
406
        if self.show_spinner:
 
407
            spin_str = self.SPIN_CHARS[self.spin_pos % 4] + ' '
 
408
        else:
 
409
            spin_str = ''
 
410
 
 
411
        # always update this; it's also used for the bar
 
412
        self.spin_pos += 1
 
413
 
 
414
        if self.show_pct and self.last_total and self.last_cnt:
 
415
            pct = 100.0 * ((self.last_cnt + self.child_fraction) / self.last_total)
 
416
            pct_str = ' (%5.1f%%)' % pct
 
417
        else:
 
418
            pct_str = ''
 
419
 
 
420
        if not self.show_count:
 
421
            count_str = ''
 
422
        elif self.last_cnt is None:
 
423
            count_str = ''
 
424
        elif self.last_total is None:
 
425
            count_str = ' %i' % (self.last_cnt)
 
426
        else:
 
427
            # make both fields the same size
 
428
            t = '%i' % (self.last_total)
 
429
            c = '%*i' % (len(t), self.last_cnt)
 
430
            count_str = ' ' + c + '/' + t
 
431
 
 
432
        if self.show_bar:
 
433
            # progress bar, if present, soaks up all remaining space
 
434
            cols = self.width - 1 - len(self.last_msg) - len(spin_str) - len(pct_str) \
 
435
                   - len(eta_str) - len(count_str) - 3
 
436
 
 
437
            if self.last_total:
 
438
                # number of markers highlighted in bar
 
439
                markers = int(round(float(cols) *
 
440
                              (self.last_cnt + self.child_fraction) / self.last_total))
 
441
                bar_str = '[' + ('=' * markers).ljust(cols) + '] '
 
442
            elif False:
 
443
                # don't know total, so can't show completion.
 
444
                # so just show an expanded spinning thingy
 
445
                m = self.spin_pos % cols
 
446
                ms = (' ' * m + '*').ljust(cols)
 
447
 
 
448
                bar_str = '[' + ms + '] '
 
449
            else:
 
450
                bar_str = ''
 
451
        else:
 
452
            bar_str = ''
 
453
 
 
454
        m = spin_str + bar_str + self.last_msg + count_str \
 
455
            + pct_str + eta_str
 
456
        self.to_file.write('\r%-*.*s' % (self.width - 1, self.width - 1, m))
 
457
        self._have_output = True
 
458
        #self.to_file.flush()
 
459
 
 
460
    def clear(self):
 
461
        if self._have_output:
 
462
            self.to_file.write('\r%s\r' % (' ' * (self.width - 1)))
 
463
        self._have_output = False
 
464
        #self.to_file.flush()
 
465
 
 
466
 
 
467
class ChildProgress(_BaseProgressBar):
 
468
    """A progress indicator that pushes its data to the parent"""
 
469
 
 
470
    @deprecated_function(deprecated_in((1, 16, 0)))
 
471
    def __init__(self, _stack, **kwargs):
 
472
        _BaseProgressBar.__init__(self, _stack=_stack, **kwargs)
 
473
        self.parent = _stack.top()
 
474
        self.current = None
 
475
        self.total = None
 
476
        self.child_fraction = 0
 
477
        self.message = None
 
478
 
 
479
    def update(self, msg, current_cnt=None, total_cnt=None):
 
480
        self.current = current_cnt
 
481
        if total_cnt is not None:
 
482
            self.total = total_cnt
 
483
        self.message = msg
 
484
        self.child_fraction = 0
 
485
        self.tick()
 
486
 
 
487
    def child_update(self, message, current, total):
 
488
        if current is None or total == 0:
 
489
            self.child_fraction = 0
 
490
        else:
 
491
            self.child_fraction = float(current) / total
 
492
        self.tick()
 
493
 
 
494
    def tick(self):
 
495
        if self.current is None:
 
496
            count = None
 
497
        else:
 
498
            count = self.current+self.child_fraction
 
499
            if count > self.total:
 
500
                if __debug__:
 
501
                    mutter('clamping count of %d to %d' % (count, self.total))
 
502
                count = self.total
 
503
        self.parent.child_update(self.message, count, self.total)
 
504
 
 
505
    def clear(self):
 
506
        pass
 
507
 
 
508
    def note(self, *args, **kwargs):
 
509
        self.parent.note(*args, **kwargs)
 
510
 
 
511
 
258
512
def str_tdelta(delt):
259
513
    if delt is None:
260
514
        return "-:--:--"
311
565
        else:
312
566
            self.cur_phase += 1
313
567
        self.pb.update(self.message, self.cur_phase, self.total)
 
568
 
 
569
 
 
570
_progress_bar_types = {}
 
571
_progress_bar_types['dummy'] = DummyProgress
 
572
_progress_bar_types['none'] = DummyProgress
 
573
_progress_bar_types['tty'] = TTYProgressBar
 
574
_progress_bar_types['dots'] = DotsProgressBar