/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
649 by Martin Pool
- some cleanups for the progressbar method
1
# Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca>
2
# Copyright (C) 2005 Canonical <canonical.com>
648 by Martin Pool
- import aaron's progress-indicator code
3
#
4
#    This program is free software; you can redistribute it and/or modify
5
#    it under the terms of the GNU General Public License as published by
6
#    the Free Software Foundation; either version 2 of the License, or
7
#    (at your option) any later version.
8
#
9
#    This program is distributed in the hope that it will be useful,
10
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
11
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
#    GNU General Public License for more details.
13
#
14
#    You should have received a copy of the GNU General Public License
15
#    along with this program; if not, write to the Free Software
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
649 by Martin Pool
- some cleanups for the progressbar method
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
652 by Martin Pool
doc
34
# TODO: should be a global option e.g. --silent that disables progress
35
# indicators, preferably without needing to adjust all code that
36
# potentially calls them.
37
649 by Martin Pool
- some cleanups for the progressbar method
38
648 by Martin Pool
- import aaron's progress-indicator code
39
import sys
40
import datetime
41
649 by Martin Pool
- some cleanups for the progressbar method
42
43
def _width():
44
    """Return estimated terminal width.
45
46
    TODO: Do something smart on Windows?
47
48
    TODO: Is there anything that gets a better update when the window
49
          is resized while the program is running?
50
    """
51
    import os
52
    try:
53
        return int(os.environ['COLUMNS'])
54
    except (IndexError, KeyError, ValueError):
55
        return 80
56
57
58
def _supports_progress(f):
59
    return hasattr(f, 'isatty') and f.isatty()
60
61
62
648 by Martin Pool
- import aaron's progress-indicator code
63
class Progress(object):
64
    def __init__(self, units, current, total=None):
65
        self.units = units
66
        self.current = current
67
        self.total = total
68
69
    def _get_percent(self):
70
        if self.total is not None and self.current is not None:
71
            return 100.0 * self.current / self.total
72
73
    percent = property(_get_percent)
74
75
    def __str__(self):
76
        if self.total is not None:
77
            return "%i of %i %s %.1f%%" % (self.current, self.total, self.units,
78
                                         self.percent)
79
        else:
649 by Martin Pool
- some cleanups for the progressbar method
80
            return "%i %s" (self.current, self.units)
81
82
648 by Martin Pool
- import aaron's progress-indicator code
83
84
class ProgressBar(object):
649 by Martin Pool
- some cleanups for the progressbar method
85
    def __init__(self, to_file=sys.stderr):
86
        object.__init__(self)
648 by Martin Pool
- import aaron's progress-indicator code
87
        self.start = None
649 by Martin Pool
- some cleanups for the progressbar method
88
        self.to_file = to_file
89
        self.suppressed = not _supports_progress(self.to_file)
90
648 by Martin Pool
- import aaron's progress-indicator code
91
92
    def __call__(self, progress):
93
        if self.start is None:
94
            self.start = datetime.datetime.now()
649 by Martin Pool
- some cleanups for the progressbar method
95
        if not self.suppressed:
96
            draw_progress_bar(progress, start_time=self.start,
97
                              to_file=self.to_file)
98
99
    def clear(self):
100
        if not self.suppressed:
101
            clear_progress_bar(self.to_file)
102
    
103
648 by Martin Pool
- import aaron's progress-indicator code
104
        
105
def divide_timedelta(delt, divisor):
106
    """Divides a timedelta object"""
107
    return datetime.timedelta(float(delt.days)/divisor, 
108
                              float(delt.seconds)/divisor, 
109
                              float(delt.microseconds)/divisor)
110
111
def str_tdelta(delt):
112
    if delt is None:
113
        return "-:--:--"
114
    return str(datetime.timedelta(delt.days, delt.seconds))
115
649 by Martin Pool
- some cleanups for the progressbar method
116
648 by Martin Pool
- import aaron's progress-indicator code
117
def get_eta(start_time, progress, enough_samples=20):
118
    if start_time is None or progress.current == 0:
119
        return None
120
    elif progress.current < enough_samples:
121
        return None
122
    elapsed = datetime.datetime.now() - start_time
123
    total_duration = divide_timedelta((elapsed) * long(progress.total), 
124
                                      progress.current)
125
    if elapsed < total_duration:
126
        eta = total_duration - elapsed
127
    else:
128
        eta = total_duration - total_duration
129
    return eta
130
649 by Martin Pool
- some cleanups for the progressbar method
131
132
def draw_progress_bar(progress, start_time=None, to_file=sys.stderr):
648 by Martin Pool
- import aaron's progress-indicator code
133
    eta = get_eta(start_time, progress)
134
    if start_time is not None:
135
        eta_str = " "+str_tdelta(eta)
136
    else:
137
        eta_str = ""
138
139
    fmt = " %i of %i %s (%.1f%%)"
140
    f = fmt % (progress.total, progress.total, progress.units, 100.0)
649 by Martin Pool
- some cleanups for the progressbar method
141
    cols = _width() - 3 - len(f)
648 by Martin Pool
- import aaron's progress-indicator code
142
    if start_time is not None:
143
        cols -= len(eta_str)
144
    markers = int (float(cols) * progress.current / progress.total)
145
    txt = fmt % (progress.current, progress.total, progress.units,
146
                 progress.percent)
649 by Martin Pool
- some cleanups for the progressbar method
147
    to_file.write("\r[%s%s]%s%s" % ('='*markers, ' '*(cols-markers), txt, 
648 by Martin Pool
- import aaron's progress-indicator code
148
                                       eta_str))
149
649 by Martin Pool
- some cleanups for the progressbar method
150
def clear_progress_bar(to_file=sys.stderr):
151
    to_file.write('\r%s\r' % (' '*79))
152
648 by Martin Pool
- import aaron's progress-indicator code
153
154
def spinner_str(progress, show_text=False):
155
    """
156
    Produces the string for a textual "spinner" progress indicator
157
    :param progress: an object represinting current progress
158
    :param show_text: If true, show progress text as well
159
    :return: The spinner string
160
161
    >>> spinner_str(Progress("baloons", 0))
162
    '|'
163
    >>> spinner_str(Progress("baloons", 5))
164
    '/'
165
    >>> spinner_str(Progress("baloons", 6), show_text=True)
166
    '- 6 baloons'
167
    """
168
    positions = ('|', '/', '-', '\\')
169
    text = positions[progress.current % 4]
170
    if show_text:
171
        text+=" %i %s" % (progress.current, progress.units)
172
    return text
173
649 by Martin Pool
- some cleanups for the progressbar method
174
648 by Martin Pool
- import aaron's progress-indicator code
175
def spinner(progress, show_text=False, output=sys.stderr):
176
    """
177
    Update a spinner progress indicator on an output
178
    :param progress: The progress to display
179
    :param show_text: If true, show text as well as spinner
180
    :param output: The output to write to
181
182
    >>> spinner(Progress("baloons", 6), show_text=True, output=sys.stdout)
183
    \r- 6 baloons
184
    """
185
    output.write('\r%s' % spinner_str(progress, show_text))
186
649 by Martin Pool
- some cleanups for the progressbar method
187
648 by Martin Pool
- import aaron's progress-indicator code
188
def run_tests():
189
    import doctest
190
    result = doctest.testmod()
191
    if result[1] > 0:
192
        if result[0] == 0:
193
            print "All tests passed"
194
    else:
195
        print "No tests to run"
649 by Martin Pool
- some cleanups for the progressbar method
196
197
198
def demo():
199
    from time import sleep
200
    pb = ProgressBar()
201
    for i in range(100):
202
        pb(Progress('Elephanten', i, 100))
203
        sleep(0.3)
204
    print 'done!'
205
648 by Martin Pool
- import aaron's progress-indicator code
206
if __name__ == "__main__":
649 by Martin Pool
- some cleanups for the progressbar method
207
    demo()