~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to progress.py

  • Committer: Aaron Bentley
  • Date: 2005-05-20 22:50:42 UTC
  • Revision ID: abentley@bruiser-20050520225042-0e48c7c0eddc23f3
merged ETA changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
17
 
18
18
import sys
 
19
import datetime
19
20
 
20
21
class Progress(object):
21
22
    def __init__(self, units, current, total=None):
33
34
        else:
34
35
            return "%i %s" (self.current, self.units) 
35
36
 
36
 
 
37
 
def progress_bar(progress):
 
37
class ProgressBar(object):
 
38
    def __init__(self):
 
39
        self.start = None
 
40
        object.__init__(self)
 
41
 
 
42
    def __call__(self, progress):
 
43
        if self.start is None:
 
44
            self.start = datetime.datetime.now()
 
45
        progress_bar(progress, start_time=self.start)
 
46
        
 
47
def divide_timedelta(delt, divisor):
 
48
    """Divides a timedelta object"""
 
49
    return datetime.timedelta(float(delt.days)/divisor, 
 
50
                              float(delt.seconds)/divisor, 
 
51
                              float(delt.microseconds)/divisor)
 
52
 
 
53
def str_tdelta(delt):
 
54
    if delt is None:
 
55
        return "-:--:--"
 
56
    return str(datetime.timedelta(delt.days, delt.seconds))
 
57
 
 
58
def get_eta(start_time, progress, enough_samples=20):
 
59
    if start_time is None or progress.current == 0:
 
60
        return None
 
61
    elif progress.current < enough_samples:
 
62
        return None
 
63
    elapsed = datetime.datetime.now() - start_time
 
64
    total_duration = divide_timedelta((elapsed) * long(progress.total), 
 
65
                                      progress.current)
 
66
    if elapsed < total_duration:
 
67
        eta = total_duration - elapsed
 
68
    else:
 
69
        eta = total_duration - total_duration
 
70
    return eta
 
71
 
 
72
def progress_bar(progress, start_time=None):
 
73
    eta = get_eta(start_time, progress)
 
74
    if start_time is not None:
 
75
        eta_str = " "+str_tdelta(eta)
 
76
    else:
 
77
        eta_str = ""
 
78
 
38
79
    fmt = " %i of %i %s (%.1f%%)"
39
80
    f = fmt % (progress.total, progress.total, progress.units, 100.0)
40
81
    max = len(f)
41
82
    cols = 77 - max
 
83
    if start_time is not None:
 
84
        cols -= len(eta_str)
42
85
    markers = int (float(cols) * progress.current / progress.total)
43
86
    txt = fmt % (progress.current, progress.total, progress.units,
44
87
                 progress.percent)
45
 
    sys.stderr.write("\r[%s%s]%s" % ('='*markers, ' '*(cols-markers), txt))
 
88
    sys.stderr.write("\r[%s%s]%s%s" % ('='*markers, ' '*(cols-markers), txt, 
 
89
                                       eta_str))
46
90
 
47
91
def clear_progress_bar():
48
92
    sys.stderr.write('\r%s\r' % (' '*79))