/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: Canonical.com Patch Queue Manager
  • Date: 2009-08-05 18:56:37 UTC
  • mfrom: (4580.5.16 1.18-win32-buildbot)
  • Revision ID: pqm@pqm.ubuntu.com-20090805185637-3f0y10upzcdw7e0g
Updates to buildout.cfg etc to have 'make installer-all' start being
        the preferred way to build win32 installer.

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