/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: Jonathan Lange
  • Date: 2009-12-09 09:20:42 UTC
  • mfrom: (4881 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4907.
  • Revision ID: jml@canonical.com-20091209092042-s2zgqcf8f39yzxpj
Merge trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
 
 
19
18
"""Text UI, write output to the console.
20
19
"""
21
20
 
 
21
import codecs
 
22
import getpass
22
23
import os
23
24
import sys
24
25
import time
27
28
from bzrlib.lazy_import import lazy_import
28
29
lazy_import(globals(), """
29
30
from bzrlib import (
 
31
    debug,
30
32
    progress,
31
33
    osutils,
32
34
    symbol_versioning,
34
36
 
35
37
""")
36
38
 
37
 
from bzrlib.ui import CLIUIFactory
38
 
 
39
 
 
40
 
class TextUIFactory(CLIUIFactory):
 
39
from bzrlib.ui import (
 
40
    UIFactory,
 
41
    NullProgressView,
 
42
    )
 
43
 
 
44
 
 
45
class TextUIFactory(UIFactory):
41
46
    """A UI factory for Text user interefaces."""
42
47
 
43
48
    def __init__(self,
44
 
                 bar_type=None,
45
49
                 stdin=None,
46
50
                 stdout=None,
47
51
                 stderr=None):
48
52
        """Create a TextUIFactory.
49
 
 
50
 
        :param bar_type: The type of progress bar to create. It defaults to
51
 
                         letting the bzrlib.progress.ProgressBar factory auto
52
 
                         select.   Deprecated.
53
53
        """
54
 
        super(TextUIFactory, self).__init__(stdin=stdin,
55
 
                stdout=stdout, stderr=stderr)
56
 
        if bar_type:
57
 
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 11, 0))
58
 
                % "bar_type parameter")
 
54
        super(TextUIFactory, self).__init__()
 
55
        # TODO: there's no good reason not to pass all three streams, maybe we
 
56
        # should deprecate the default values...
 
57
        self.stdin = stdin
 
58
        self.stdout = stdout
 
59
        self.stderr = stderr
59
60
        # paints progress, network activity, etc
60
 
        self._progress_view = self._make_progress_view()
 
61
        self._progress_view = self.make_progress_view()
61
62
        
62
63
    def clear_term(self):
63
64
        """Prepare the terminal for output.
70
71
        # to clear it.  We might need to separately check for the case of
71
72
        self._progress_view.clear()
72
73
 
73
 
    def _make_progress_view(self):
74
 
        if os.environ.get('BZR_PROGRESS_BAR') in ('text', None, ''):
75
 
            return TextProgressView(self.stderr)
76
 
        else:
77
 
            return NullProgressView()
 
74
    def get_boolean(self, prompt):
 
75
        while True:
 
76
            self.prompt(prompt + "? [y/n]: ")
 
77
            line = self.stdin.readline().lower()
 
78
            if line in ('y\n', 'yes\n'):
 
79
                return True
 
80
            elif line in ('n\n', 'no\n'):
 
81
                return False
 
82
            elif line in ('', None):
 
83
                # end-of-file; possibly should raise an error here instead
 
84
                return None
 
85
 
 
86
    def get_non_echoed_password(self):
 
87
        isatty = getattr(self.stdin, 'isatty', None)
 
88
        if isatty is not None and isatty():
 
89
            # getpass() ensure the password is not echoed and other
 
90
            # cross-platform niceties
 
91
            password = getpass.getpass('')
 
92
        else:
 
93
            # echo doesn't make sense without a terminal
 
94
            password = self.stdin.readline()
 
95
            if not password:
 
96
                password = None
 
97
            elif password[-1] == '\n':
 
98
                password = password[:-1]
 
99
        return password
 
100
 
 
101
    def get_password(self, prompt='', **kwargs):
 
102
        """Prompt the user for a password.
 
103
 
 
104
        :param prompt: The prompt to present the user
 
105
        :param kwargs: Arguments which will be expanded into the prompt.
 
106
                       This lets front ends display different things if
 
107
                       they so choose.
 
108
        :return: The password string, return None if the user
 
109
                 canceled the request.
 
110
        """
 
111
        prompt += ': '
 
112
        self.prompt(prompt, **kwargs)
 
113
        # There's currently no way to say 'i decline to enter a password'
 
114
        # as opposed to 'my password is empty' -- does it matter?
 
115
        return self.get_non_echoed_password()
 
116
 
 
117
    def get_username(self, prompt, **kwargs):
 
118
        """Prompt the user for a username.
 
119
 
 
120
        :param prompt: The prompt to present the user
 
121
        :param kwargs: Arguments which will be expanded into the prompt.
 
122
                       This lets front ends display different things if
 
123
                       they so choose.
 
124
        :return: The username string, return None if the user
 
125
                 canceled the request.
 
126
        """
 
127
        prompt += ': '
 
128
        self.prompt(prompt, **kwargs)
 
129
        username = self.stdin.readline()
 
130
        if not username:
 
131
            username = None
 
132
        elif username[-1] == '\n':
 
133
            username = username[:-1]
 
134
        return username
 
135
 
 
136
    def make_progress_view(self):
 
137
        """Construct and return a new ProgressView subclass for this UI.
 
138
        """
 
139
        # if the user specifically requests either text or no progress bars,
 
140
        # always do that.  otherwise, guess based on $TERM and tty presence.
 
141
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
 
142
            return TextProgressView(self.stderr)
 
143
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
 
144
            return NullProgressView()
 
145
        elif progress._supports_progress(self.stderr):
 
146
            return TextProgressView(self.stderr)
 
147
        else:
 
148
            return NullProgressView()
 
149
 
 
150
    def _make_output_stream_explicit(self, encoding, encoding_type):
 
151
        if encoding_type == 'exact':
 
152
            # force sys.stdout to be binary stream on win32; 
 
153
            # NB: this leaves the file set in that mode; may cause problems if
 
154
            # one process tries to do binary and then text output
 
155
            if sys.platform == 'win32':
 
156
                fileno = getattr(self.stdout, 'fileno', None)
 
157
                if fileno:
 
158
                    import msvcrt
 
159
                    msvcrt.setmode(fileno(), os.O_BINARY)
 
160
            return TextUIOutputStream(self, self.stdout)
 
161
        else:
 
162
            encoded_stdout = codecs.getwriter(encoding)(self.stdout,
 
163
                errors=encoding_type)
 
164
            # For whatever reason codecs.getwriter() does not advertise its encoding
 
165
            # it just returns the encoding of the wrapped file, which is completely
 
166
            # bogus. So set the attribute, so we can find the correct encoding later.
 
167
            encoded_stdout.encoding = encoding
 
168
            return TextUIOutputStream(self, encoded_stdout)
78
169
 
79
170
    def note(self, msg):
80
171
        """Write an already-formatted message, clearing the progress bar if necessary."""
81
172
        self.clear_term()
82
173
        self.stdout.write(msg + '\n')
83
174
 
 
175
    def prompt(self, prompt, **kwargs):
 
176
        """Emit prompt on the CLI.
 
177
        
 
178
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
179
            to allow UIs to reformat the prompt.
 
180
        """
 
181
        if kwargs:
 
182
            # See <https://launchpad.net/bugs/365891>
 
183
            prompt = prompt % kwargs
 
184
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
185
        self.clear_term()
 
186
        self.stderr.write(prompt)
 
187
 
84
188
    def report_transport_activity(self, transport, byte_count, direction):
85
189
        """Called by transports as they do IO.
86
190
 
90
194
        self._progress_view.show_transport_activity(transport,
91
195
            direction, byte_count)
92
196
 
 
197
    def show_error(self, msg):
 
198
        self.clear_term()
 
199
        self.stderr.write("bzr: error: %s\n" % msg)
 
200
 
 
201
    def show_message(self, msg):
 
202
        self.note(msg)
 
203
 
 
204
    def show_warning(self, msg):
 
205
        self.clear_term()
 
206
        self.stderr.write("bzr: warning: %s\n" % msg)
 
207
 
93
208
    def _progress_updated(self, task):
94
209
        """A task has been updated and wants to be displayed.
95
210
        """
105
220
        self._progress_view.clear()
106
221
 
107
222
 
108
 
class NullProgressView(object):
109
 
    """Soak up and ignore progress information."""
110
 
 
111
 
    def clear(self):
112
 
        pass
113
 
 
114
 
    def show_progress(self, task):
115
 
        pass
116
 
 
117
 
    def show_transport_activity(self, transport, direction, byte_count):
118
 
        pass
119
 
    
120
 
 
121
223
class TextProgressView(object):
122
224
    """Display of progress bar and other information on a tty.
123
225
 
149
251
        self._last_task = None
150
252
        self._total_byte_count = 0
151
253
        self._bytes_since_update = 0
 
254
        self._fraction = 0
152
255
 
153
256
    def _show_line(self, s):
154
 
        n = self._width - 1
155
 
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
 
257
        # sys.stderr.write("progress %r\n" % s)
 
258
        if self._width is not None:
 
259
            n = self._width - 1
 
260
            s = '%-*.*s' % (n, n, s)
 
261
        self._term_file.write('\r' + s + '\r')
156
262
 
157
263
    def clear(self):
158
264
        if self._have_output:
172
278
            cols = 20
173
279
            if self._last_task is None:
174
280
                completion_fraction = 0
 
281
                self._fraction = 0
175
282
            else:
176
283
                completion_fraction = \
177
284
                    self._last_task._overall_completion_fraction() or 0
 
285
            if (completion_fraction < self._fraction and 'progress' in
 
286
                debug.debug_flags):
 
287
                import pdb;pdb.set_trace()
 
288
            self._fraction = completion_fraction
178
289
            markers = int(round(float(cols) * completion_fraction)) - 1
179
290
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
180
291
            return bar_str
210
321
            task_msg = self._format_task(self._last_task)
211
322
        else:
212
323
            task_msg = ''
213
 
        trans = self._last_transport_msg
214
 
        if trans:
215
 
            trans += ' | '
 
324
        if self._last_task and not self._last_task.show_transport_activity:
 
325
            trans = ''
 
326
        else:
 
327
            trans = self._last_transport_msg
 
328
            if trans:
 
329
                trans += ' | '
216
330
        return (bar_string + trans + task_msg)
217
331
 
218
332
    def _repaint(self):
229
343
        must_update = task is not self._last_task
230
344
        self._last_task = task
231
345
        now = time.time()
232
 
        if (not must_update) and (now < self._last_repaint + 0.1):
 
346
        if (not must_update) and (now < self._last_repaint + task.update_latency):
233
347
            return
234
348
        if now > self._transport_update_time + 10:
235
349
            # no recent activity; expire it
257
371
        self._total_byte_count += byte_count
258
372
        self._bytes_since_update += byte_count
259
373
        now = time.time()
 
374
        if self._total_byte_count < 2000:
 
375
            # a little resistance at first, so it doesn't stay stuck at 0
 
376
            # while connecting...
 
377
            return
260
378
        if self._transport_update_time is None:
261
379
            self._transport_update_time = now
262
380
        elif now >= (self._transport_update_time + 0.5):
270
388
            self._bytes_since_update = 0
271
389
            self._last_transport_msg = msg
272
390
            self._repaint()
 
391
 
 
392
 
 
393
class TextUIOutputStream(object):
 
394
    """Decorates an output stream so that the terminal is cleared before writing.
 
395
 
 
396
    This is supposed to ensure that the progress bar does not conflict with bulk
 
397
    text output.
 
398
    """
 
399
    # XXX: this does not handle the case of writing part of a line, then doing
 
400
    # progress bar output: the progress bar will probably write over it.
 
401
    # one option is just to buffer that text until we have a full line;
 
402
    # another is to save and restore it
 
403
 
 
404
    # XXX: might need to wrap more methods
 
405
 
 
406
    def __init__(self, ui_factory, wrapped_stream):
 
407
        self.ui_factory = ui_factory
 
408
        self.wrapped_stream = wrapped_stream
 
409
        # this does no transcoding, but it must expose the underlying encoding
 
410
        # because some callers need to know what can be written - see for
 
411
        # example unescape_for_display.
 
412
        self.encoding = getattr(wrapped_stream, 'encoding', None)
 
413
 
 
414
    def flush(self):
 
415
        self.ui_factory.clear_term()
 
416
        self.wrapped_stream.flush()
 
417
 
 
418
    def write(self, to_write):
 
419
        self.ui_factory.clear_term()
 
420
        self.wrapped_stream.write(to_write)
 
421
 
 
422
    def writelines(self, lines):
 
423
        self.ui_factory.clear_term()
 
424
        self.wrapped_stream.writelines(lines)