1
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
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.
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.
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
18
"""Text UI, write output to the console.
28
from bzrlib.lazy_import import lazy_import
29
lazy_import(globals(), """
39
from bzrlib.ui import (
45
class TextUIFactory(UIFactory):
46
"""A UI factory for Text user interefaces."""
52
"""Create a TextUIFactory.
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...
60
# paints progress, network activity, etc
61
self._progress_view = self.make_progress_view()
64
"""Prepare the terminal for output.
66
This will, clear any progress bars, and leave the cursor at the
68
# XXX: If this is preparing to write to stdout, but that's for example
69
# directed into a file rather than to the terminal, and the progress
70
# bar _is_ going to the terminal, we shouldn't need
71
# to clear it. We might need to separately check for the case of
72
self._progress_view.clear()
74
def get_boolean(self, prompt):
76
self.prompt(prompt + "? [y/n]: ")
77
line = self.stdin.readline().lower()
78
if line in ('y\n', 'yes\n'):
80
elif line in ('n\n', 'no\n'):
82
elif line in ('', None):
83
# end-of-file; possibly should raise an error here instead
86
def get_integer(self, prompt):
89
line = self.stdin.readline()
95
def get_non_echoed_password(self):
96
isatty = getattr(self.stdin, 'isatty', None)
97
if isatty is not None and isatty():
98
# getpass() ensure the password is not echoed and other
99
# cross-platform niceties
100
password = getpass.getpass('')
102
# echo doesn't make sense without a terminal
103
password = self.stdin.readline()
106
elif password[-1] == '\n':
107
password = password[:-1]
110
def get_password(self, prompt='', **kwargs):
111
"""Prompt the user for a password.
113
:param prompt: The prompt to present the user
114
:param kwargs: Arguments which will be expanded into the prompt.
115
This lets front ends display different things if
117
:return: The password string, return None if the user
118
canceled the request.
121
self.prompt(prompt, **kwargs)
122
# There's currently no way to say 'i decline to enter a password'
123
# as opposed to 'my password is empty' -- does it matter?
124
return self.get_non_echoed_password()
126
def get_username(self, prompt, **kwargs):
127
"""Prompt the user for a username.
129
:param prompt: The prompt to present the user
130
:param kwargs: Arguments which will be expanded into the prompt.
131
This lets front ends display different things if
133
:return: The username string, return None if the user
134
canceled the request.
137
self.prompt(prompt, **kwargs)
138
username = self.stdin.readline()
141
elif username[-1] == '\n':
142
username = username[:-1]
145
def make_progress_view(self):
146
"""Construct and return a new ProgressView subclass for this UI.
148
# if the user specifically requests either text or no progress bars,
149
# always do that. otherwise, guess based on $TERM and tty presence.
150
if os.environ.get('BZR_PROGRESS_BAR') == 'text':
151
return TextProgressView(self.stderr)
152
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
153
return NullProgressView()
154
elif progress._supports_progress(self.stderr):
155
return TextProgressView(self.stderr)
157
return NullProgressView()
159
def _make_output_stream_explicit(self, encoding, encoding_type):
160
if encoding_type == 'exact':
161
# force sys.stdout to be binary stream on win32;
162
# NB: this leaves the file set in that mode; may cause problems if
163
# one process tries to do binary and then text output
164
if sys.platform == 'win32':
165
fileno = getattr(self.stdout, 'fileno', None)
168
msvcrt.setmode(fileno(), os.O_BINARY)
169
return TextUIOutputStream(self, self.stdout)
171
encoded_stdout = codecs.getwriter(encoding)(self.stdout,
172
errors=encoding_type)
173
# For whatever reason codecs.getwriter() does not advertise its encoding
174
# it just returns the encoding of the wrapped file, which is completely
175
# bogus. So set the attribute, so we can find the correct encoding later.
176
encoded_stdout.encoding = encoding
177
return TextUIOutputStream(self, encoded_stdout)
180
"""Write an already-formatted message, clearing the progress bar if necessary."""
182
self.stdout.write(msg + '\n')
184
def prompt(self, prompt, **kwargs):
185
"""Emit prompt on the CLI.
187
:param kwargs: Dictionary of arguments to insert into the prompt,
188
to allow UIs to reformat the prompt.
191
# See <https://launchpad.net/bugs/365891>
192
prompt = prompt % kwargs
193
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
195
self.stderr.write(prompt)
197
def report_transport_activity(self, transport, byte_count, direction):
198
"""Called by transports as they do IO.
200
This may update a progress bar, spinner, or similar display.
201
By default it does nothing.
203
self._progress_view.show_transport_activity(transport,
204
direction, byte_count)
206
def show_error(self, msg):
208
self.stderr.write("bzr: error: %s\n" % msg)
210
def show_message(self, msg):
213
def show_warning(self, msg):
215
self.stderr.write("bzr: warning: %s\n" % msg)
217
def _progress_updated(self, task):
218
"""A task has been updated and wants to be displayed.
220
if not self._task_stack:
221
warnings.warn("%r updated but no tasks are active" %
223
elif task != self._task_stack[-1]:
224
warnings.warn("%r is not the top progress task %r" %
225
(task, self._task_stack[-1]))
226
self._progress_view.show_progress(task)
228
def _progress_all_finished(self):
229
self._progress_view.clear()
232
class TextProgressView(object):
233
"""Display of progress bar and other information on a tty.
235
This shows one line of text, including possibly a network indicator, spinner,
236
progress bar, message, etc.
238
One instance of this is created and held by the UI, and fed updates when a
239
task wants to be painted.
241
Transports feed data to this through the ui_factory object.
243
The Progress views can comprise a tree with _parent_task pointers, but
244
this only prints the stack from the nominated current task up to the root.
247
def __init__(self, term_file):
248
self._term_file = term_file
249
# true when there's output on the screen we may need to clear
250
self._have_output = False
251
# XXX: We could listen for SIGWINCH and update the terminal width...
252
# https://launchpad.net/bugs/316357
253
self._width = osutils.terminal_width()
254
self._last_transport_msg = ''
256
# time we last repainted the screen
257
self._last_repaint = 0
258
# time we last got information about transport activity
259
self._transport_update_time = 0
260
self._last_task = None
261
self._total_byte_count = 0
262
self._bytes_since_update = 0
264
# force the progress bar to be off, as at the moment it doesn't
265
# correspond reliably to overall command progress
266
self.enable_bar = False
268
def _show_line(self, s):
269
# sys.stderr.write("progress %r\n" % s)
270
if self._width is not None:
272
s = '%-*.*s' % (n, n, s)
273
self._term_file.write('\r' + s + '\r')
276
if self._have_output:
278
self._have_output = False
280
def _render_bar(self):
281
# return a string for the progress bar itself
282
if self.enable_bar and (
283
(self._last_task is None) or self._last_task.show_bar):
284
# If there's no task object, we show space for the bar anyhow.
285
# That's because most invocations of bzr will end showing progress
286
# at some point, though perhaps only after doing some initial IO.
287
# It looks better to draw the progress bar initially rather than
288
# to have what looks like an incomplete progress bar.
289
spin_str = r'/-\|'[self._spin_pos % 4]
292
if self._last_task is None:
293
completion_fraction = 0
296
completion_fraction = \
297
self._last_task._overall_completion_fraction() or 0
298
if (completion_fraction < self._fraction and 'progress' in
300
import pdb;pdb.set_trace()
301
self._fraction = completion_fraction
302
markers = int(round(float(cols) * completion_fraction)) - 1
303
bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
305
elif self._last_task.show_spinner:
306
# The last task wanted just a spinner, no bar
307
spin_str = r'/-\|'[self._spin_pos % 4]
309
return spin_str + ' '
313
def _format_task(self, task):
314
if not task.show_count:
316
elif task.current_cnt is not None and task.total_cnt is not None:
317
s = ' %d/%d' % (task.current_cnt, task.total_cnt)
318
elif task.current_cnt is not None:
319
s = ' %d' % (task.current_cnt)
322
# compose all the parent messages
325
while t._parent_task:
331
def _render_line(self):
332
bar_string = self._render_bar()
334
task_msg = self._format_task(self._last_task)
337
if self._last_task and not self._last_task.show_transport_activity:
340
trans = self._last_transport_msg
343
return (bar_string + trans + task_msg)
346
s = self._render_line()
348
self._have_output = True
350
def show_progress(self, task):
351
"""Called by the task object when it has changed.
353
:param task: The top task object; its parents are also included
356
must_update = task is not self._last_task
357
self._last_task = task
359
if (not must_update) and (now < self._last_repaint + task.update_latency):
361
if now > self._transport_update_time + 10:
362
# no recent activity; expire it
363
self._last_transport_msg = ''
364
self._last_repaint = now
367
def show_transport_activity(self, transport, direction, byte_count):
368
"""Called by transports via the ui_factory, as they do IO.
370
This may update a progress bar, spinner, or similar display.
371
By default it does nothing.
373
# XXX: Probably there should be a transport activity model, and that
374
# too should be seen by the progress view, rather than being poked in
376
if not self._have_output:
377
# As a workaround for <https://launchpad.net/bugs/321935> we only
378
# show transport activity when there's already a progress bar
379
# shown, which time the application code is expected to know to
380
# clear off the progress bar when it's going to send some other
381
# output. Eventually it would be nice to have that automatically
384
self._total_byte_count += byte_count
385
self._bytes_since_update += byte_count
387
if self._total_byte_count < 2000:
388
# a little resistance at first, so it doesn't stay stuck at 0
389
# while connecting...
391
if self._transport_update_time is None:
392
self._transport_update_time = now
393
elif now >= (self._transport_update_time + 0.5):
394
# guard against clock stepping backwards, and don't update too
396
rate = self._bytes_since_update / (now - self._transport_update_time)
397
msg = ("%6dKB %5dKB/s" %
398
(self._total_byte_count>>10, int(rate)>>10,))
399
self._transport_update_time = now
400
self._last_repaint = now
401
self._bytes_since_update = 0
402
self._last_transport_msg = msg
406
class TextUIOutputStream(object):
407
"""Decorates an output stream so that the terminal is cleared before writing.
409
This is supposed to ensure that the progress bar does not conflict with bulk
412
# XXX: this does not handle the case of writing part of a line, then doing
413
# progress bar output: the progress bar will probably write over it.
414
# one option is just to buffer that text until we have a full line;
415
# another is to save and restore it
417
# XXX: might need to wrap more methods
419
def __init__(self, ui_factory, wrapped_stream):
420
self.ui_factory = ui_factory
421
self.wrapped_stream = wrapped_stream
422
# this does no transcoding, but it must expose the underlying encoding
423
# because some callers need to know what can be written - see for
424
# example unescape_for_display.
425
self.encoding = getattr(wrapped_stream, 'encoding', None)
428
self.ui_factory.clear_term()
429
self.wrapped_stream.flush()
431
def write(self, to_write):
432
self.ui_factory.clear_term()
433
self.wrapped_stream.write(to_write)
435
def writelines(self, lines):
436
self.ui_factory.clear_term()
437
self.wrapped_stream.writelines(lines)