/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: 2005-06-10 07:10:25 UTC
  • Revision ID: mbp@sourcefrog.net-20050610071025-30505d735a905de5
- some cleanups for the progressbar method

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Aaron Bentley
2
 
# <aaron.bentley@utoronto.ca>
 
1
# Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca>
 
2
# Copyright (C) 2005 Canonical <canonical.com>
3
3
#
4
4
#    This program is free software; you can redistribute it and/or modify
5
5
#    it under the terms of the GNU General Public License as published by
15
15
#    along with this program; if not, write to the Free Software
16
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
17
 
 
18
 
 
19
"""
 
20
Simple text-mode progress indicator.
 
21
 
 
22
Everyone loves ascii art!
 
23
 
 
24
To display an indicator, create a ProgressBar object.  Call it,
 
25
passing Progress objects indicating the current state.  When done,
 
26
call clear().
 
27
 
 
28
Progress is suppressed when output is not sent to a terminal, so as
 
29
not to clutter log files.
 
30
"""
 
31
 
 
32
# TODO: remove functions in favour of keeping everything in one class
 
33
 
 
34
 
18
35
import sys
19
36
import datetime
20
37
 
 
38
 
 
39
def _width():
 
40
    """Return estimated terminal width.
 
41
 
 
42
    TODO: Do something smart on Windows?
 
43
 
 
44
    TODO: Is there anything that gets a better update when the window
 
45
          is resized while the program is running?
 
46
    """
 
47
    import os
 
48
    try:
 
49
        return int(os.environ['COLUMNS'])
 
50
    except (IndexError, KeyError, ValueError):
 
51
        return 80
 
52
 
 
53
 
 
54
def _supports_progress(f):
 
55
    return hasattr(f, 'isatty') and f.isatty()
 
56
 
 
57
 
 
58
 
21
59
class Progress(object):
22
60
    def __init__(self, units, current, total=None):
23
61
        self.units = units
35
73
            return "%i of %i %s %.1f%%" % (self.current, self.total, self.units,
36
74
                                         self.percent)
37
75
        else:
38
 
            return "%i %s" (self.current, self.units) 
 
76
            return "%i %s" (self.current, self.units)
 
77
 
 
78
 
39
79
 
40
80
class ProgressBar(object):
41
 
    def __init__(self):
 
81
    def __init__(self, to_file=sys.stderr):
 
82
        object.__init__(self)
42
83
        self.start = None
43
 
        object.__init__(self)
 
84
        self.to_file = to_file
 
85
        self.suppressed = not _supports_progress(self.to_file)
 
86
 
44
87
 
45
88
    def __call__(self, progress):
46
89
        if self.start is None:
47
90
            self.start = datetime.datetime.now()
48
 
        progress_bar(progress, start_time=self.start)
 
91
        if not self.suppressed:
 
92
            draw_progress_bar(progress, start_time=self.start,
 
93
                              to_file=self.to_file)
 
94
 
 
95
    def clear(self):
 
96
        if not self.suppressed:
 
97
            clear_progress_bar(self.to_file)
 
98
    
 
99
 
49
100
        
50
101
def divide_timedelta(delt, divisor):
51
102
    """Divides a timedelta object"""
58
109
        return "-:--:--"
59
110
    return str(datetime.timedelta(delt.days, delt.seconds))
60
111
 
 
112
 
61
113
def get_eta(start_time, progress, enough_samples=20):
62
114
    if start_time is None or progress.current == 0:
63
115
        return None
72
124
        eta = total_duration - total_duration
73
125
    return eta
74
126
 
75
 
def progress_bar(progress, start_time=None):
 
127
 
 
128
def draw_progress_bar(progress, start_time=None, to_file=sys.stderr):
76
129
    eta = get_eta(start_time, progress)
77
130
    if start_time is not None:
78
131
        eta_str = " "+str_tdelta(eta)
81
134
 
82
135
    fmt = " %i of %i %s (%.1f%%)"
83
136
    f = fmt % (progress.total, progress.total, progress.units, 100.0)
84
 
    max = len(f)
85
 
    cols = 77 - max
 
137
    cols = _width() - 3 - len(f)
86
138
    if start_time is not None:
87
139
        cols -= len(eta_str)
88
140
    markers = int (float(cols) * progress.current / progress.total)
89
141
    txt = fmt % (progress.current, progress.total, progress.units,
90
142
                 progress.percent)
91
 
    sys.stderr.write("\r[%s%s]%s%s" % ('='*markers, ' '*(cols-markers), txt, 
 
143
    to_file.write("\r[%s%s]%s%s" % ('='*markers, ' '*(cols-markers), txt, 
92
144
                                       eta_str))
93
145
 
94
 
def clear_progress_bar():
95
 
    sys.stderr.write('\r%s\r' % (' '*79))
 
146
def clear_progress_bar(to_file=sys.stderr):
 
147
    to_file.write('\r%s\r' % (' '*79))
 
148
 
96
149
 
97
150
def spinner_str(progress, show_text=False):
98
151
    """
114
167
        text+=" %i %s" % (progress.current, progress.units)
115
168
    return text
116
169
 
 
170
 
117
171
def spinner(progress, show_text=False, output=sys.stderr):
118
172
    """
119
173
    Update a spinner progress indicator on an output
126
180
    """
127
181
    output.write('\r%s' % spinner_str(progress, show_text))
128
182
 
 
183
 
129
184
def run_tests():
130
185
    import doctest
131
186
    result = doctest.testmod()
134
189
            print "All tests passed"
135
190
    else:
136
191
        print "No tests to run"
 
192
 
 
193
 
 
194
def demo():
 
195
    from time import sleep
 
196
    pb = ProgressBar()
 
197
    for i in range(100):
 
198
        pb(Progress('Elephanten', i, 100))
 
199
        sleep(0.3)
 
200
    print 'done!'
 
201
 
137
202
if __name__ == "__main__":
138
 
    run_tests()
 
203
    demo()