~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Vincent Ladeuil
  • Date: 2009-12-14 15:51:36 UTC
  • mto: (4894.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4895.
  • Revision ID: v.ladeuil+lp@free.fr-20091214155136-rf4nkqvxda9oiw4u
Cleanup tests and tweak the text displayed.

* bzrlib/tests/blackbox/test_update.py:
Fix imports and replace the assertContainsRe with assertEqualDiff
to make the test clearer, more robust and easier to debug.

* bzrlib/tests/commands/test_update.py: 
Fix imports.

* bzrlib/tests/blackbox/test_filtered_view_ops.py: 
Fix imports and strange accesses to base class methods.
(TestViewTreeOperations.test_view_on_update): Avoid os.chdir()
call, simplify string matching assertions.

* bzrlib/builtins.py:
(cmd_update.run): Fix spurious space, get rid of the final '/' for
the base path, don't add a final period (it's a legal char in a
path and would be annoying for people that like to copy/paste).

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 show_error(self, msg):
 
177
        self.clear_term()
 
178
        self.stderr.write("bzr: error: %s\n" % msg)
 
179
 
 
180
    def show_message(self, msg):
 
181
        self.note(msg)
 
182
 
 
183
    def show_warning(self, msg):
 
184
        self.clear_term()
 
185
        self.stderr.write("bzr: warning: %s\n" % msg)
 
186
 
 
187
    def _progress_updated(self, task):
 
188
        """A task has been updated and wants to be displayed.
 
189
        """
 
190
        if not self._task_stack:
 
191
            warnings.warn("%r updated but no tasks are active" %
 
192
                (task,))
 
193
        elif task != self._task_stack[-1]:
 
194
            warnings.warn("%r is not the top progress task %r" %
 
195
                (task, self._task_stack[-1]))
 
196
        self._progress_view.show_progress(task)
 
197
 
 
198
    def _progress_all_finished(self):
 
199
        self._progress_view.clear()
 
200
 
 
201
 
 
202
class TextProgressView(object):
 
203
    """Display of progress bar and other information on a tty.
 
204
 
 
205
    This shows one line of text, including possibly a network indicator, spinner,
 
206
    progress bar, message, etc.
 
207
 
 
208
    One instance of this is created and held by the UI, and fed updates when a
 
209
    task wants to be painted.
 
210
 
 
211
    Transports feed data to this through the ui_factory object.
 
212
 
 
213
    The Progress views can comprise a tree with _parent_task pointers, but
 
214
    this only prints the stack from the nominated current task up to the root.
 
215
    """
 
216
 
 
217
    def __init__(self, term_file):
 
218
        self._term_file = term_file
 
219
        # true when there's output on the screen we may need to clear
 
220
        self._have_output = False
 
221
        # XXX: We could listen for SIGWINCH and update the terminal width...
 
222
        # https://launchpad.net/bugs/316357
 
223
        self._width = osutils.terminal_width()
 
224
        self._last_transport_msg = ''
 
225
        self._spin_pos = 0
 
226
        # time we last repainted the screen
 
227
        self._last_repaint = 0
 
228
        # time we last got information about transport activity
 
229
        self._transport_update_time = 0
 
230
        self._last_task = None
 
231
        self._total_byte_count = 0
 
232
        self._bytes_since_update = 0
 
233
        self._fraction = 0
 
234
 
 
235
    def _show_line(self, s):
 
236
        # sys.stderr.write("progress %r\n" % s)
 
237
        if self._width is not None:
 
238
            n = self._width - 1
 
239
            s = '%-*.*s' % (n, n, s)
 
240
        self._term_file.write('\r' + s + '\r')
 
241
 
 
242
    def clear(self):
 
243
        if self._have_output:
 
244
            self._show_line('')
 
245
        self._have_output = False
 
246
 
 
247
    def _render_bar(self):
 
248
        # return a string for the progress bar itself
 
249
        if (self._last_task is None) or self._last_task.show_bar:
 
250
            # If there's no task object, we show space for the bar anyhow.
 
251
            # That's because most invocations of bzr will end showing progress
 
252
            # at some point, though perhaps only after doing some initial IO.
 
253
            # It looks better to draw the progress bar initially rather than
 
254
            # to have what looks like an incomplete progress bar.
 
255
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
256
            self._spin_pos += 1
 
257
            cols = 20
 
258
            if self._last_task is None:
 
259
                completion_fraction = 0
 
260
                self._fraction = 0
 
261
            else:
 
262
                completion_fraction = \
 
263
                    self._last_task._overall_completion_fraction() or 0
 
264
            if (completion_fraction < self._fraction and 'progress' in
 
265
                debug.debug_flags):
 
266
                import pdb;pdb.set_trace()
 
267
            self._fraction = completion_fraction
 
268
            markers = int(round(float(cols) * completion_fraction)) - 1
 
269
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
 
270
            return bar_str
 
271
        elif self._last_task.show_spinner:
 
272
            # The last task wanted just a spinner, no bar
 
273
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
274
            self._spin_pos += 1
 
275
            return spin_str + ' '
 
276
        else:
 
277
            return ''
 
278
 
 
279
    def _format_task(self, task):
 
280
        if not task.show_count:
 
281
            s = ''
 
282
        elif task.current_cnt is not None and task.total_cnt is not None:
 
283
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
 
284
        elif task.current_cnt is not None:
 
285
            s = ' %d' % (task.current_cnt)
 
286
        else:
 
287
            s = ''
 
288
        # compose all the parent messages
 
289
        t = task
 
290
        m = task.msg
 
291
        while t._parent_task:
 
292
            t = t._parent_task
 
293
            if t.msg:
 
294
                m = t.msg + ':' + m
 
295
        return m + s
 
296
 
 
297
    def _render_line(self):
 
298
        bar_string = self._render_bar()
 
299
        if self._last_task:
 
300
            task_msg = self._format_task(self._last_task)
 
301
        else:
 
302
            task_msg = ''
 
303
        if self._last_task and not self._last_task.show_transport_activity:
 
304
            trans = ''
 
305
        else:
 
306
            trans = self._last_transport_msg
 
307
            if trans:
 
308
                trans += ' | '
 
309
        return (bar_string + trans + task_msg)
 
310
 
 
311
    def _repaint(self):
 
312
        s = self._render_line()
 
313
        self._show_line(s)
 
314
        self._have_output = True
 
315
 
 
316
    def show_progress(self, task):
 
317
        """Called by the task object when it has changed.
 
318
        
 
319
        :param task: The top task object; its parents are also included 
 
320
            by following links.
 
321
        """
 
322
        must_update = task is not self._last_task
 
323
        self._last_task = task
 
324
        now = time.time()
 
325
        if (not must_update) and (now < self._last_repaint + task.update_latency):
 
326
            return
 
327
        if now > self._transport_update_time + 10:
 
328
            # no recent activity; expire it
 
329
            self._last_transport_msg = ''
 
330
        self._last_repaint = now
 
331
        self._repaint()
 
332
 
 
333
    def show_transport_activity(self, transport, direction, byte_count):
 
334
        """Called by transports via the ui_factory, as they do IO.
 
335
 
 
336
        This may update a progress bar, spinner, or similar display.
 
337
        By default it does nothing.
 
338
        """
 
339
        # XXX: Probably there should be a transport activity model, and that
 
340
        # too should be seen by the progress view, rather than being poked in
 
341
        # here.
 
342
        if not self._have_output:
 
343
            # As a workaround for <https://launchpad.net/bugs/321935> we only
 
344
            # show transport activity when there's already a progress bar
 
345
            # shown, which time the application code is expected to know to
 
346
            # clear off the progress bar when it's going to send some other
 
347
            # output.  Eventually it would be nice to have that automatically
 
348
            # synchronized.
 
349
            return
 
350
        self._total_byte_count += byte_count
 
351
        self._bytes_since_update += byte_count
 
352
        now = time.time()
 
353
        if self._total_byte_count < 2000:
 
354
            # a little resistance at first, so it doesn't stay stuck at 0
 
355
            # while connecting...
 
356
            return
 
357
        if self._transport_update_time is None:
 
358
            self._transport_update_time = now
 
359
        elif now >= (self._transport_update_time + 0.5):
 
360
            # guard against clock stepping backwards, and don't update too
 
361
            # often
 
362
            rate = self._bytes_since_update / (now - self._transport_update_time)
 
363
            msg = ("%6dKB %5dKB/s" %
 
364
                    (self._total_byte_count>>10, int(rate)>>10,))
 
365
            self._transport_update_time = now
 
366
            self._last_repaint = now
 
367
            self._bytes_since_update = 0
 
368
            self._last_transport_msg = msg
 
369
            self._repaint()