/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 08:43:05 UTC
  • mto: This revision was merged to the branch mainline in revision 4558.
  • Revision ID: mbp@sourcefrog.net-20090623084305-lcuasmyncbq2ncfk
More test updates to use CannedInputUIFactory

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