~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Robey Pointer
  • Date: 2006-07-12 16:29:39 UTC
  • mto: This revision was merged to the branch mainline in revision 1861.
  • Revision ID: robey@lag.net-20060712162939-7d27143c632e3b3a
change the warning message for a 'whoami' with no email address, on jam's recommendation

Show diffs side-by-side

added added

removed removed

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