/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: Robert Collins
  • Date: 2009-08-04 04:36:34 UTC
  • mfrom: (4583 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4593.
  • Revision ID: robertc@robertcollins.net-20090804043634-2iu9wpcgs273i97s
Merge bzr.dev.

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
        :param bar_type: The type of progress bar to create. It defaults to
 
54
                         letting the bzrlib.progress.ProgressBar factory auto
 
55
                         select.   Deprecated.
 
56
        """
 
57
        super(TextUIFactory, self).__init__()
 
58
        # TODO: there's no good reason not to pass all three streams, maybe we
 
59
        # should deprecate the default values...
 
60
        self.stdin = stdin
 
61
        self.stdout = stdout
 
62
        self.stderr = stderr
 
63
        # paints progress, network activity, etc
 
64
        self._progress_view = self.make_progress_view()
 
65
        
 
66
    def clear_term(self):
 
67
        """Prepare the terminal for output.
 
68
 
 
69
        This will, clear any progress bars, and leave the cursor at the
 
70
        leftmost position."""
 
71
        # XXX: If this is preparing to write to stdout, but that's for example
 
72
        # directed into a file rather than to the terminal, and the progress
 
73
        # bar _is_ going to the terminal, we shouldn't need
 
74
        # to clear it.  We might need to separately check for the case of
 
75
        self._progress_view.clear()
 
76
 
 
77
    def get_boolean(self, prompt):
 
78
        while True:
 
79
            self.prompt(prompt + "? [y/n]: ")
 
80
            line = self.stdin.readline().lower()
 
81
            if line in ('y\n', 'yes\n'):
 
82
                return True
 
83
            elif line in ('n\n', 'no\n'):
 
84
                return False
 
85
            elif line in ('', None):
 
86
                # end-of-file; possibly should raise an error here instead
 
87
                return None
 
88
 
 
89
    def get_non_echoed_password(self):
 
90
        isatty = getattr(self.stdin, 'isatty', None)
 
91
        if isatty is not None and isatty():
 
92
            # getpass() ensure the password is not echoed and other
 
93
            # cross-platform niceties
 
94
            password = getpass.getpass('')
 
95
        else:
 
96
            # echo doesn't make sense without a terminal
 
97
            password = self.stdin.readline()
 
98
            if not password:
 
99
                password = None
 
100
            elif password[-1] == '\n':
 
101
                password = password[:-1]
 
102
        return password
 
103
 
 
104
    def get_password(self, prompt='', **kwargs):
 
105
        """Prompt the user for a password.
 
106
 
 
107
        :param prompt: The prompt to present the user
 
108
        :param kwargs: Arguments which will be expanded into the prompt.
 
109
                       This lets front ends display different things if
 
110
                       they so choose.
 
111
        :return: The password string, return None if the user
 
112
                 canceled the request.
 
113
        """
 
114
        prompt += ': '
 
115
        self.prompt(prompt, **kwargs)
 
116
        # There's currently no way to say 'i decline to enter a password'
 
117
        # as opposed to 'my password is empty' -- does it matter?
 
118
        return self.get_non_echoed_password()
 
119
 
 
120
    def get_username(self, prompt, **kwargs):
 
121
        """Prompt the user for a username.
 
122
 
 
123
        :param prompt: The prompt to present the user
 
124
        :param kwargs: Arguments which will be expanded into the prompt.
 
125
                       This lets front ends display different things if
 
126
                       they so choose.
 
127
        :return: The username string, return None if the user
 
128
                 canceled the request.
 
129
        """
 
130
        prompt += ': '
 
131
        self.prompt(prompt, **kwargs)
 
132
        username = self.stdin.readline()
 
133
        if not username:
 
134
            username = None
 
135
        elif username[-1] == '\n':
 
136
            username = username[:-1]
 
137
        return username
 
138
 
 
139
    def make_progress_view(self):
 
140
        """Construct and return a new ProgressView subclass for this UI.
 
141
        """
 
142
        # if the user specifically requests either text or no progress bars,
 
143
        # always do that.  otherwise, guess based on $TERM and tty presence.
 
144
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
 
145
            return TextProgressView(self.stderr)
 
146
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
 
147
            return NullProgressView()
 
148
        elif progress._supports_progress(self.stderr):
 
149
            return TextProgressView(self.stderr)
 
150
        else:
 
151
            return NullProgressView()
 
152
 
 
153
    def note(self, msg):
 
154
        """Write an already-formatted message, clearing the progress bar if necessary."""
 
155
        self.clear_term()
 
156
        self.stdout.write(msg + '\n')
 
157
 
 
158
    def prompt(self, prompt, **kwargs):
 
159
        """Emit prompt on the CLI.
 
160
        
 
161
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
162
            to allow UIs to reformat the prompt.
 
163
        """
 
164
        if kwargs:
 
165
            # See <https://launchpad.net/bugs/365891>
 
166
            prompt = prompt % kwargs
 
167
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
168
        self.clear_term()
 
169
        self.stderr.write(prompt)
 
170
 
 
171
    def report_transport_activity(self, transport, byte_count, direction):
 
172
        """Called by transports as they do IO.
 
173
 
 
174
        This may update a progress bar, spinner, or similar display.
 
175
        By default it does nothing.
 
176
        """
 
177
        self._progress_view.show_transport_activity(transport,
 
178
            direction, byte_count)
 
179
 
 
180
    def _progress_updated(self, task):
 
181
        """A task has been updated and wants to be displayed.
 
182
        """
 
183
        if not self._task_stack:
 
184
            warnings.warn("%r updated but no tasks are active" %
 
185
                (task,))
 
186
        elif task != self._task_stack[-1]:
 
187
            warnings.warn("%r is not the top progress task %r" %
 
188
                (task, self._task_stack[-1]))
 
189
        self._progress_view.show_progress(task)
 
190
 
 
191
    def _progress_all_finished(self):
 
192
        self._progress_view.clear()
 
193
 
 
194
 
 
195
class TextProgressView(object):
 
196
    """Display of progress bar and other information on a tty.
 
197
 
 
198
    This shows one line of text, including possibly a network indicator, spinner,
 
199
    progress bar, message, etc.
 
200
 
 
201
    One instance of this is created and held by the UI, and fed updates when a
 
202
    task wants to be painted.
 
203
 
 
204
    Transports feed data to this through the ui_factory object.
 
205
 
 
206
    The Progress views can comprise a tree with _parent_task pointers, but
 
207
    this only prints the stack from the nominated current task up to the root.
 
208
    """
 
209
 
 
210
    def __init__(self, term_file):
 
211
        self._term_file = term_file
 
212
        # true when there's output on the screen we may need to clear
 
213
        self._have_output = False
 
214
        # XXX: We could listen for SIGWINCH and update the terminal width...
 
215
        # https://launchpad.net/bugs/316357
 
216
        self._width = osutils.terminal_width()
 
217
        self._last_transport_msg = ''
 
218
        self._spin_pos = 0
 
219
        # time we last repainted the screen
 
220
        self._last_repaint = 0
 
221
        # time we last got information about transport activity
 
222
        self._transport_update_time = 0
 
223
        self._last_task = None
 
224
        self._total_byte_count = 0
 
225
        self._bytes_since_update = 0
 
226
        self._fraction = 0
 
227
 
 
228
    def _show_line(self, s):
 
229
        n = self._width - 1
 
230
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
 
231
 
 
232
    def clear(self):
 
233
        if self._have_output:
 
234
            self._show_line('')
 
235
        self._have_output = False
 
236
 
 
237
    def _render_bar(self):
 
238
        # return a string for the progress bar itself
 
239
        if (self._last_task is None) or self._last_task.show_bar:
 
240
            # If there's no task object, we show space for the bar anyhow.
 
241
            # That's because most invocations of bzr will end showing progress
 
242
            # at some point, though perhaps only after doing some initial IO.
 
243
            # It looks better to draw the progress bar initially rather than
 
244
            # to have what looks like an incomplete progress bar.
 
245
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
246
            self._spin_pos += 1
 
247
            cols = 20
 
248
            if self._last_task is None:
 
249
                completion_fraction = 0
 
250
                self._fraction = 0
 
251
            else:
 
252
                completion_fraction = \
 
253
                    self._last_task._overall_completion_fraction() or 0
 
254
            if (completion_fraction < self._fraction and 'progress' in
 
255
                debug.debug_flags):
 
256
                import pdb;pdb.set_trace()
 
257
            self._fraction = completion_fraction
 
258
            markers = int(round(float(cols) * completion_fraction)) - 1
 
259
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
 
260
            return bar_str
 
261
        elif self._last_task.show_spinner:
 
262
            # The last task wanted just a spinner, no bar
 
263
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
264
            self._spin_pos += 1
 
265
            return spin_str + ' '
 
266
        else:
 
267
            return ''
 
268
 
 
269
    def _format_task(self, task):
 
270
        if not task.show_count:
 
271
            s = ''
 
272
        elif task.current_cnt is not None and task.total_cnt is not None:
 
273
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
 
274
        elif task.current_cnt is not None:
 
275
            s = ' %d' % (task.current_cnt)
 
276
        else:
 
277
            s = ''
 
278
        # compose all the parent messages
 
279
        t = task
 
280
        m = task.msg
 
281
        while t._parent_task:
 
282
            t = t._parent_task
 
283
            if t.msg:
 
284
                m = t.msg + ':' + m
 
285
        return m + s
 
286
 
 
287
    def _render_line(self):
 
288
        bar_string = self._render_bar()
 
289
        if self._last_task:
 
290
            task_msg = self._format_task(self._last_task)
 
291
        else:
 
292
            task_msg = ''
 
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 + 0.1):
 
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._transport_update_time is None:
 
341
            self._transport_update_time = now
 
342
        elif now >= (self._transport_update_time + 0.5):
 
343
            # guard against clock stepping backwards, and don't update too
 
344
            # often
 
345
            rate = self._bytes_since_update / (now - self._transport_update_time)
 
346
            msg = ("%6dKB %5dKB/s" %
 
347
                    (self._total_byte_count>>10, int(rate)>>10,))
 
348
            self._transport_update_time = now
 
349
            self._last_repaint = now
 
350
            self._bytes_since_update = 0
 
351
            self._last_transport_msg = msg
 
352
            self._repaint()