/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/ui/text.py

  • Committer: Martin Pool
  • Date: 2009-09-23 04:54:41 UTC
  • mto: This revision was merged to the branch mainline in revision 4745.
  • Revision ID: mbp@sourcefrog.net-20090923045441-80j9qcur76c9xjor
Start adding tests.per_uifactory

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
"""Text UI, write output to the console.
 
19
"""
 
20
 
 
21
import getpass
 
22
import os
 
23
import sys
 
24
import time
 
25
import warnings
 
26
 
 
27
from bzrlib.lazy_import import lazy_import
 
28
lazy_import(globals(), """
 
29
from bzrlib import (
 
30
    debug,
 
31
    progress,
 
32
    osutils,
 
33
    symbol_versioning,
 
34
    )
 
35
 
 
36
""")
 
37
 
 
38
from bzrlib.ui import (
 
39
    UIFactory,
 
40
    NullProgressView,
 
41
    )
 
42
 
 
43
 
 
44
class TextUIFactory(UIFactory):
 
45
    """A UI factory for Text user interefaces."""
 
46
 
 
47
    def __init__(self,
 
48
                 stdin=None,
 
49
                 stdout=None,
 
50
                 stderr=None):
 
51
        """Create a TextUIFactory.
 
52
        """
 
53
        super(TextUIFactory, self).__init__()
 
54
        # TODO: there's no good reason not to pass all three streams, maybe we
 
55
        # should deprecate the default values...
 
56
        self.stdin = stdin
 
57
        self.stdout = stdout
 
58
        self.stderr = stderr
 
59
        # paints progress, network activity, etc
 
60
        self._progress_view = self.make_progress_view()
 
61
        
 
62
    def clear_term(self):
 
63
        """Prepare the terminal for output.
 
64
 
 
65
        This will, clear any progress bars, and leave the cursor at the
 
66
        leftmost position."""
 
67
        # XXX: If this is preparing to write to stdout, but that's for example
 
68
        # directed into a file rather than to the terminal, and the progress
 
69
        # bar _is_ going to the terminal, we shouldn't need
 
70
        # to clear it.  We might need to separately check for the case of
 
71
        self._progress_view.clear()
 
72
 
 
73
    def get_boolean(self, prompt):
 
74
        while True:
 
75
            self.prompt(prompt + "? [y/n]: ")
 
76
            line = self.stdin.readline().lower()
 
77
            if line in ('y\n', 'yes\n'):
 
78
                return True
 
79
            elif line in ('n\n', 'no\n'):
 
80
                return False
 
81
            elif line in ('', None):
 
82
                # end-of-file; possibly should raise an error here instead
 
83
                return None
 
84
 
 
85
    def get_non_echoed_password(self):
 
86
        isatty = getattr(self.stdin, 'isatty', None)
 
87
        if isatty is not None and isatty():
 
88
            # getpass() ensure the password is not echoed and other
 
89
            # cross-platform niceties
 
90
            password = getpass.getpass('')
 
91
        else:
 
92
            # echo doesn't make sense without a terminal
 
93
            password = self.stdin.readline()
 
94
            if not password:
 
95
                password = None
 
96
            elif password[-1] == '\n':
 
97
                password = password[:-1]
 
98
        return password
 
99
 
 
100
    def get_password(self, prompt='', **kwargs):
 
101
        """Prompt the user for a password.
 
102
 
 
103
        :param prompt: The prompt to present the user
 
104
        :param kwargs: Arguments which will be expanded into the prompt.
 
105
                       This lets front ends display different things if
 
106
                       they so choose.
 
107
        :return: The password string, return None if the user
 
108
                 canceled the request.
 
109
        """
 
110
        prompt += ': '
 
111
        self.prompt(prompt, **kwargs)
 
112
        # There's currently no way to say 'i decline to enter a password'
 
113
        # as opposed to 'my password is empty' -- does it matter?
 
114
        return self.get_non_echoed_password()
 
115
 
 
116
    def get_username(self, prompt, **kwargs):
 
117
        """Prompt the user for a username.
 
118
 
 
119
        :param prompt: The prompt to present the user
 
120
        :param kwargs: Arguments which will be expanded into the prompt.
 
121
                       This lets front ends display different things if
 
122
                       they so choose.
 
123
        :return: The username string, return None if the user
 
124
                 canceled the request.
 
125
        """
 
126
        prompt += ': '
 
127
        self.prompt(prompt, **kwargs)
 
128
        username = self.stdin.readline()
 
129
        if not username:
 
130
            username = None
 
131
        elif username[-1] == '\n':
 
132
            username = username[:-1]
 
133
        return username
 
134
 
 
135
    def make_progress_view(self):
 
136
        """Construct and return a new ProgressView subclass for this UI.
 
137
        """
 
138
        # if the user specifically requests either text or no progress bars,
 
139
        # always do that.  otherwise, guess based on $TERM and tty presence.
 
140
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
 
141
            return TextProgressView(self.stderr)
 
142
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
 
143
            return NullProgressView()
 
144
        elif progress._supports_progress(self.stderr):
 
145
            return TextProgressView(self.stderr)
 
146
        else:
 
147
            return NullProgressView()
 
148
 
 
149
    def note(self, msg):
 
150
        """Write an already-formatted message, clearing the progress bar if necessary."""
 
151
        self.clear_term()
 
152
        self.stdout.write(msg + '\n')
 
153
 
 
154
    def prompt(self, prompt, **kwargs):
 
155
        """Emit prompt on the CLI.
 
156
        
 
157
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
158
            to allow UIs to reformat the prompt.
 
159
        """
 
160
        if kwargs:
 
161
            # See <https://launchpad.net/bugs/365891>
 
162
            prompt = prompt % kwargs
 
163
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
164
        self.clear_term()
 
165
        self.stderr.write(prompt)
 
166
 
 
167
    def report_transport_activity(self, transport, byte_count, direction):
 
168
        """Called by transports as they do IO.
 
169
 
 
170
        This may update a progress bar, spinner, or similar display.
 
171
        By default it does nothing.
 
172
        """
 
173
        self._progress_view.show_transport_activity(transport,
 
174
            direction, byte_count)
 
175
 
 
176
    def _progress_updated(self, task):
 
177
        """A task has been updated and wants to be displayed.
 
178
        """
 
179
        if not self._task_stack:
 
180
            warnings.warn("%r updated but no tasks are active" %
 
181
                (task,))
 
182
        elif task != self._task_stack[-1]:
 
183
            warnings.warn("%r is not the top progress task %r" %
 
184
                (task, self._task_stack[-1]))
 
185
        self._progress_view.show_progress(task)
 
186
 
 
187
    def _progress_all_finished(self):
 
188
        self._progress_view.clear()
 
189
 
 
190
 
 
191
class TextProgressView(object):
 
192
    """Display of progress bar and other information on a tty.
 
193
 
 
194
    This shows one line of text, including possibly a network indicator, spinner,
 
195
    progress bar, message, etc.
 
196
 
 
197
    One instance of this is created and held by the UI, and fed updates when a
 
198
    task wants to be painted.
 
199
 
 
200
    Transports feed data to this through the ui_factory object.
 
201
 
 
202
    The Progress views can comprise a tree with _parent_task pointers, but
 
203
    this only prints the stack from the nominated current task up to the root.
 
204
    """
 
205
 
 
206
    def __init__(self, term_file):
 
207
        self._term_file = term_file
 
208
        # true when there's output on the screen we may need to clear
 
209
        self._have_output = False
 
210
        # XXX: We could listen for SIGWINCH and update the terminal width...
 
211
        # https://launchpad.net/bugs/316357
 
212
        self._width = osutils.terminal_width()
 
213
        self._last_transport_msg = ''
 
214
        self._spin_pos = 0
 
215
        # time we last repainted the screen
 
216
        self._last_repaint = 0
 
217
        # time we last got information about transport activity
 
218
        self._transport_update_time = 0
 
219
        self._last_task = None
 
220
        self._total_byte_count = 0
 
221
        self._bytes_since_update = 0
 
222
        self._fraction = 0
 
223
 
 
224
    def _show_line(self, s):
 
225
        # sys.stderr.write("progress %r\n" % s)
 
226
        n = self._width - 1
 
227
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
 
228
 
 
229
    def clear(self):
 
230
        if self._have_output:
 
231
            self._show_line('')
 
232
        self._have_output = False
 
233
 
 
234
    def _render_bar(self):
 
235
        # return a string for the progress bar itself
 
236
        if (self._last_task is None) or self._last_task.show_bar:
 
237
            # If there's no task object, we show space for the bar anyhow.
 
238
            # That's because most invocations of bzr will end showing progress
 
239
            # at some point, though perhaps only after doing some initial IO.
 
240
            # It looks better to draw the progress bar initially rather than
 
241
            # to have what looks like an incomplete progress bar.
 
242
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
243
            self._spin_pos += 1
 
244
            cols = 20
 
245
            if self._last_task is None:
 
246
                completion_fraction = 0
 
247
                self._fraction = 0
 
248
            else:
 
249
                completion_fraction = \
 
250
                    self._last_task._overall_completion_fraction() or 0
 
251
            if (completion_fraction < self._fraction and 'progress' in
 
252
                debug.debug_flags):
 
253
                import pdb;pdb.set_trace()
 
254
            self._fraction = completion_fraction
 
255
            markers = int(round(float(cols) * completion_fraction)) - 1
 
256
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
 
257
            return bar_str
 
258
        elif self._last_task.show_spinner:
 
259
            # The last task wanted just a spinner, no bar
 
260
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
261
            self._spin_pos += 1
 
262
            return spin_str + ' '
 
263
        else:
 
264
            return ''
 
265
 
 
266
    def _format_task(self, task):
 
267
        if not task.show_count:
 
268
            s = ''
 
269
        elif task.current_cnt is not None and task.total_cnt is not None:
 
270
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
 
271
        elif task.current_cnt is not None:
 
272
            s = ' %d' % (task.current_cnt)
 
273
        else:
 
274
            s = ''
 
275
        # compose all the parent messages
 
276
        t = task
 
277
        m = task.msg
 
278
        while t._parent_task:
 
279
            t = t._parent_task
 
280
            if t.msg:
 
281
                m = t.msg + ':' + m
 
282
        return m + s
 
283
 
 
284
    def _render_line(self):
 
285
        bar_string = self._render_bar()
 
286
        if self._last_task:
 
287
            task_msg = self._format_task(self._last_task)
 
288
        else:
 
289
            task_msg = ''
 
290
        if self._last_task and not self._last_task.show_transport_activity:
 
291
            trans = ''
 
292
        else:
 
293
            trans = self._last_transport_msg
 
294
            if trans:
 
295
                trans += ' | '
 
296
        return (bar_string + trans + task_msg)
 
297
 
 
298
    def _repaint(self):
 
299
        s = self._render_line()
 
300
        self._show_line(s)
 
301
        self._have_output = True
 
302
 
 
303
    def show_progress(self, task):
 
304
        """Called by the task object when it has changed.
 
305
        
 
306
        :param task: The top task object; its parents are also included 
 
307
            by following links.
 
308
        """
 
309
        must_update = task is not self._last_task
 
310
        self._last_task = task
 
311
        now = time.time()
 
312
        if (not must_update) and (now < self._last_repaint + task.update_latency):
 
313
            return
 
314
        if now > self._transport_update_time + 10:
 
315
            # no recent activity; expire it
 
316
            self._last_transport_msg = ''
 
317
        self._last_repaint = now
 
318
        self._repaint()
 
319
 
 
320
    def show_transport_activity(self, transport, direction, byte_count):
 
321
        """Called by transports via the ui_factory, as they do IO.
 
322
 
 
323
        This may update a progress bar, spinner, or similar display.
 
324
        By default it does nothing.
 
325
        """
 
326
        # XXX: Probably there should be a transport activity model, and that
 
327
        # too should be seen by the progress view, rather than being poked in
 
328
        # here.
 
329
        if not self._have_output:
 
330
            # As a workaround for <https://launchpad.net/bugs/321935> we only
 
331
            # show transport activity when there's already a progress bar
 
332
            # shown, which time the application code is expected to know to
 
333
            # clear off the progress bar when it's going to send some other
 
334
            # output.  Eventually it would be nice to have that automatically
 
335
            # synchronized.
 
336
            return
 
337
        self._total_byte_count += byte_count
 
338
        self._bytes_since_update += byte_count
 
339
        now = time.time()
 
340
        if self._total_byte_count < 2000:
 
341
            # a little resistance at first, so it doesn't stay stuck at 0
 
342
            # while connecting...
 
343
            return
 
344
        if self._transport_update_time is None:
 
345
            self._transport_update_time = now
 
346
        elif now >= (self._transport_update_time + 0.5):
 
347
            # guard against clock stepping backwards, and don't update too
 
348
            # often
 
349
            rate = self._bytes_since_update / (now - self._transport_update_time)
 
350
            msg = ("%6dKB %5dKB/s" %
 
351
                    (self._total_byte_count>>10, int(rate)>>10,))
 
352
            self._transport_update_time = now
 
353
            self._last_repaint = now
 
354
            self._bytes_since_update = 0
 
355
            self._last_transport_msg = msg
 
356
            self._repaint()