~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/progress.py

  • Committer: Martin Pool
  • Date: 2005-07-07 10:22:02 UTC
  • Revision ID: mbp@sourcefrog.net-20050707102201-2d2a13a25098b101
- rearrange and clear up merged weave

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
 
19
 
"""Simple text-mode progress indicator.
 
19
"""
 
20
Simple text-mode progress indicator.
 
21
 
 
22
Everyone loves ascii art!
20
23
 
21
24
To display an indicator, create a ProgressBar object.  Call it,
22
25
passing Progress objects indicating the current state.  When done,
26
29
not to clutter log files.
27
30
"""
28
31
 
 
32
# TODO: remove functions in favour of keeping everything in one class
 
33
 
29
34
# TODO: should be a global option e.g. --silent that disables progress
30
35
# indicators, preferably without needing to adjust all code that
31
36
# potentially calls them.
32
37
 
33
 
# TODO: If not on a tty perhaps just print '......' for the benefit of IDEs, etc
34
 
 
35
 
# TODO: Optionally show elapsed time instead/as well as ETA; nicer
36
 
# when the rate is unpredictable
 
38
# TODO: Perhaps don't write updates faster than a certain rate, say
 
39
# 5/second.
37
40
 
38
41
 
39
42
import sys
40
43
import time
41
 
import os
42
44
 
43
45
 
44
46
def _width():
49
51
    TODO: Is there anything that gets a better update when the window
50
52
          is resized while the program is running?
51
53
    """
 
54
    import os
52
55
    try:
53
56
        return int(os.environ['COLUMNS'])
54
57
    except (IndexError, KeyError, ValueError):
60
63
        return False
61
64
    if not f.isatty():
62
65
        return False
 
66
    import os
63
67
    if os.environ.get('TERM') == 'dumb':
64
68
        # e.g. emacs compile window
65
69
        return False
67
71
 
68
72
 
69
73
 
70
 
def ProgressBar(to_file=sys.stderr, **kwargs):
71
 
    """Abstract factory"""
72
 
    if _supports_progress(to_file):
73
 
        return TTYProgressBar(to_file=to_file, **kwargs)
74
 
    else:
75
 
        return DotsProgressBar(to_file=to_file, **kwargs)
76
 
    
77
 
    
78
 
class _BaseProgressBar(object):
79
 
    def __init__(self,
80
 
                 to_file=sys.stderr,
81
 
                 show_pct=False,
82
 
                 show_spinner=False,
83
 
                 show_eta=True,
84
 
                 show_bar=True,
85
 
                 show_count=True):
86
 
        object.__init__(self)
87
 
        self.to_file = to_file
88
 
 
89
 
        self.last_msg = None
90
 
        self.last_cnt = None
91
 
        self.last_total = None
92
 
        self.show_pct = show_pct
93
 
        self.show_spinner = show_spinner
94
 
        self.show_eta = show_eta
95
 
        self.show_bar = show_bar
96
 
        self.show_count = show_count
97
 
 
98
 
 
99
 
 
100
 
class DummyProgress(_BaseProgressBar):
101
 
    """Progress-bar standin that does nothing.
102
 
 
103
 
    This can be used as the default argument for methods that
104
 
    take an optional progress indicator."""
105
 
    def tick(self):
106
 
        pass
107
 
 
108
 
    def update(self, msg=None, current=None, total=None):
109
 
        pass
110
 
 
111
 
    def clear(self):
112
 
        pass
113
 
        
114
 
    
115
 
class DotsProgressBar(_BaseProgressBar):
116
 
    def __init__(self, **kwargs):
117
 
        _BaseProgressBar.__init__(self, **kwargs)
118
 
        self.last_msg = None
119
 
        self.need_nl = False
120
 
        
121
 
    def tick(self):
122
 
        self.update()
123
 
        
124
 
    def update(self, msg=None, current_cnt=None, total_cnt=None):
125
 
        if msg and msg != self.last_msg:
126
 
            if self.need_nl:
127
 
                self.to_file.write('\n')
128
 
            
129
 
            self.to_file.write(msg + ': ')
130
 
            self.last_msg = msg
131
 
        self.need_nl = True
132
 
        self.to_file.write('.')
133
 
        
134
 
    def clear(self):
135
 
        if self.need_nl:
136
 
            self.to_file.write('\n')
137
 
        
138
 
    
139
 
class TTYProgressBar(_BaseProgressBar):
 
74
class ProgressBar(object):
140
75
    """Progress bar display object.
141
76
 
142
77
    Several options are available to control the display.  These can
159
94
    SPIN_CHARS = r'/-\|'
160
95
    MIN_PAUSE = 0.1 # seconds
161
96
 
162
 
 
163
 
    def __init__(self, **kwargs):
164
 
        _BaseProgressBar.__init__(self, **kwargs)
 
97
    start_time = None
 
98
    last_update = None
 
99
    
 
100
    def __init__(self,
 
101
                 to_file=sys.stderr,
 
102
                 show_pct=False,
 
103
                 show_spinner=False,
 
104
                 show_eta=True,
 
105
                 show_bar=True,
 
106
                 show_count=True):
 
107
        object.__init__(self)
 
108
        self.to_file = to_file
 
109
        self.suppressed = not _supports_progress(self.to_file)
165
110
        self.spin_pos = 0
166
 
        self.width = _width()
167
 
        self.start_time = None
168
 
        self.last_update = None
169
 
    
170
 
 
171
 
    def throttle(self):
172
 
        """Return True if the bar was updated too recently"""
173
 
        now = time.time()
174
 
        if self.start_time is None:
175
 
            self.start_time = self.last_update = now
176
 
            return False
177
 
        else:
178
 
            interval = now - self.last_update
179
 
            if interval > 0 and interval < self.MIN_PAUSE:
180
 
                return True
181
 
 
182
 
        self.last_update = now
183
 
        return False
184
 
        
 
111
 
 
112
        self.last_msg = None
 
113
        self.last_cnt = None
 
114
        self.last_total = None
 
115
        self.show_pct = show_pct
 
116
        self.show_spinner = show_spinner
 
117
        self.show_eta = show_eta
 
118
        self.show_bar = show_bar
 
119
        self.show_count = show_count
 
120
 
185
121
 
186
122
    def tick(self):
187
123
        self.update(self.last_msg, self.last_cnt, self.last_total)
190
126
 
191
127
    def update(self, msg, current_cnt=None, total_cnt=None):
192
128
        """Update and redraw progress bar."""
 
129
        if self.suppressed:
 
130
            return
193
131
 
194
132
        # save these for the tick() function
195
133
        self.last_msg = msg
196
134
        self.last_cnt = current_cnt
197
135
        self.last_total = total_cnt
198
136
            
199
 
        if self.throttle():
200
 
            return 
 
137
        now = time.time()
 
138
        if self.start_time is None:
 
139
            self.start_time = now
 
140
        else:
 
141
            interval = now - self.last_update
 
142
            if interval > 0 and interval < self.MIN_PAUSE:
 
143
                return
 
144
 
 
145
        self.last_update = now
201
146
        
 
147
        width = _width()
 
148
 
202
149
        if total_cnt:
203
150
            assert current_cnt <= total_cnt
204
151
        if current_cnt:
238
185
 
239
186
        if self.show_bar:
240
187
            # progress bar, if present, soaks up all remaining space
241
 
            cols = self.width - 1 - len(msg) - len(spin_str) - len(pct_str) \
 
188
            cols = width - 1 - len(msg) - len(spin_str) - len(pct_str) \
242
189
                   - len(eta_str) - len(count_str) - 3
243
190
 
244
191
            if total_cnt:
259
206
 
260
207
        m = spin_str + bar_str + msg + count_str + pct_str + eta_str
261
208
 
262
 
        assert len(m) < self.width
263
 
        self.to_file.write('\r' + m.ljust(self.width - 1))
 
209
        assert len(m) < width
 
210
        self.to_file.write('\r' + m.ljust(width - 1))
264
211
        #self.to_file.flush()
265
212
            
266
213
 
267
 
    def clear(self):        
268
 
        self.to_file.write('\r%s\r' % (' ' * (self.width - 1)))
 
214
    def clear(self):
 
215
        if self.suppressed:
 
216
            return
 
217
        
 
218
        self.to_file.write('\r%s\r' % (' ' * (_width() - 1)))
269
219
        #self.to_file.flush()        
270
220
    
271
221
 
315
265
 
316
266
 
317
267
def demo():
318
 
    sleep = time.sleep
319
 
    
320
 
    print 'dumb-terminal test:'
321
 
    pb = DotsProgressBar()
322
 
    for i in range(100):
323
 
        pb.update('Leoparden', i, 99)
324
 
        sleep(0.1)
325
 
    sleep(1.5)
326
 
    pb.clear()
327
 
    sleep(1.5)
328
 
    
329
 
    print 'smart-terminal test:'
 
268
    from time import sleep
330
269
    pb = ProgressBar(show_pct=True, show_bar=True, show_spinner=False)
331
270
    for i in range(100):
332
271
        pb.update('Elephanten', i, 99)
334
273
    sleep(2)
335
274
    pb.clear()
336
275
    sleep(1)
337
 
 
338
276
    print 'done!'
339
277
 
340
278
if __name__ == "__main__":