1
# Copyright (C) 2005-2011 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.
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
40
from bzrlib.ui import (
46
class _ChooseUI(object):
48
""" Helper class for choose implementation.
51
def __init__(self, ui, msg, choices, default):
54
self._build_alternatives(msg, choices, default)
56
def _setup_mode(self):
57
"""Setup input mode (line-based, char-based) and echo-back.
59
Line-based input is used if the BZR_TEXTUI_INPUT environment
60
variable is set to 'line-based', or if there is no controlling
63
if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
64
self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
65
self.line_based = False
68
self.line_based = True
69
self.echo_back = not self.ui.stdin.isatty()
71
def _build_alternatives(self, msg, choices, default):
72
"""Parse choices string.
74
Setup final prompt and the lists of choices and associated
79
self.alternatives = {}
80
choices = choices.split('\n')
81
if default is not None and default not in range(0, len(choices)):
82
raise ValueError("invalid default index")
84
name = c.replace('&', '').lower()
85
choice = (name, index)
86
if name in self.alternatives:
87
raise ValueError("duplicated choice: %s" % name)
88
self.alternatives[name] = choice
89
shortcut = c.find('&')
90
if -1 != shortcut and (shortcut + 1) < len(c):
92
help += '[' + c[shortcut + 1] + ']'
93
help += c[(shortcut + 2):]
94
shortcut = c[shortcut + 1]
96
c = c.replace('&', '')
98
help = '[%s]%s' % (shortcut, c[1:])
99
shortcut = shortcut.lower()
100
if shortcut in self.alternatives:
101
raise ValueError("duplicated shortcut: %s" % shortcut)
102
self.alternatives[shortcut] = choice
103
# Add redirections for default.
105
self.alternatives[''] = choice
106
self.alternatives['\r'] = choice
107
help_list.append(help)
110
self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
113
line = self.ui.stdin.readline()
119
char = osutils.getchar()
120
if char == chr(3): # INTR
121
raise KeyboardInterrupt
122
if char == chr(4): # EOF (^d, C-d)
127
"""Keep asking the user until a valid choice is made.
130
getchoice = self._getline
132
getchoice = self._getchar
136
if 1 == iter or self.line_based:
137
self.ui.prompt(self.prompt)
141
self.ui.stderr.write('\n')
143
except KeyboardInterrupt:
144
self.ui.stderr.write('\n')
145
raise KeyboardInterrupt
146
choice = choice.lower()
147
if choice not in self.alternatives:
148
# Not a valid choice, keep on asking.
150
name, index = self.alternatives[choice]
152
self.ui.stderr.write(name + '\n')
156
class TextUIFactory(UIFactory):
157
"""A UI factory for Text user interefaces."""
163
"""Create a TextUIFactory.
165
super(TextUIFactory, self).__init__()
166
# TODO: there's no good reason not to pass all three streams, maybe we
167
# should deprecate the default values...
171
# paints progress, network activity, etc
172
self._progress_view = self.make_progress_view()
174
def choose(self, msg, choices, default=None):
175
"""Prompt the user for a list of alternatives.
177
Support both line-based and char-based editing.
179
In line-based mode, both the shortcut and full choice name are valid
180
answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
181
'YES ' are all valid input lines for choosing 'yes'.
183
An empty line, when in line-based mode, or pressing enter in char-based
184
mode will select the default choice (if any).
186
Choice is echoed back if:
187
- input is char-based; which means a controlling terminal is available,
188
and osutils.getchar is used
189
- input is line-based, and no controlling terminal is available
192
choose_ui = _ChooseUI(self, msg, choices, default)
193
return choose_ui.interact()
195
def be_quiet(self, state):
196
if state and not self._quiet:
198
UIFactory.be_quiet(self, state)
199
self._progress_view = self.make_progress_view()
201
def clear_term(self):
202
"""Prepare the terminal for output.
204
This will, clear any progress bars, and leave the cursor at the
205
leftmost position."""
206
# XXX: If this is preparing to write to stdout, but that's for example
207
# directed into a file rather than to the terminal, and the progress
208
# bar _is_ going to the terminal, we shouldn't need
209
# to clear it. We might need to separately check for the case of
210
self._progress_view.clear()
212
def get_integer(self, prompt):
215
line = self.stdin.readline()
221
def get_non_echoed_password(self):
222
isatty = getattr(self.stdin, 'isatty', None)
223
if isatty is not None and isatty():
224
# getpass() ensure the password is not echoed and other
225
# cross-platform niceties
226
password = getpass.getpass('')
228
# echo doesn't make sense without a terminal
229
password = self.stdin.readline()
232
elif password[-1] == '\n':
233
password = password[:-1]
236
def get_password(self, prompt=u'', **kwargs):
237
"""Prompt the user for a password.
239
:param prompt: The prompt to present the user
240
:param kwargs: Arguments which will be expanded into the prompt.
241
This lets front ends display different things if
243
:return: The password string, return None if the user
244
canceled the request.
247
self.prompt(prompt, **kwargs)
248
# There's currently no way to say 'i decline to enter a password'
249
# as opposed to 'my password is empty' -- does it matter?
250
return self.get_non_echoed_password()
252
def get_username(self, prompt, **kwargs):
253
"""Prompt the user for a username.
255
:param prompt: The prompt to present the user
256
:param kwargs: Arguments which will be expanded into the prompt.
257
This lets front ends display different things if
259
:return: The username string, return None if the user
260
canceled the request.
263
self.prompt(prompt, **kwargs)
264
username = self.stdin.readline()
267
elif username[-1] == '\n':
268
username = username[:-1]
271
def make_progress_view(self):
272
"""Construct and return a new ProgressView subclass for this UI.
274
# with --quiet, never any progress view
275
# <https://bugs.launchpad.net/bzr/+bug/320035>. Otherwise if the
276
# user specifically requests either text or no progress bars, always
277
# do that. otherwise, guess based on $TERM and tty presence.
279
return NullProgressView()
280
elif os.environ.get('BZR_PROGRESS_BAR') == 'text':
281
return TextProgressView(self.stderr)
282
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
283
return NullProgressView()
284
elif progress._supports_progress(self.stderr):
285
return TextProgressView(self.stderr)
287
return NullProgressView()
289
def _make_output_stream_explicit(self, encoding, encoding_type):
290
if encoding_type == 'exact':
291
# force sys.stdout to be binary stream on win32;
292
# NB: this leaves the file set in that mode; may cause problems if
293
# one process tries to do binary and then text output
294
if sys.platform == 'win32':
295
fileno = getattr(self.stdout, 'fileno', None)
298
msvcrt.setmode(fileno(), os.O_BINARY)
299
return TextUIOutputStream(self, self.stdout)
301
encoded_stdout = codecs.getwriter(encoding)(self.stdout,
302
errors=encoding_type)
303
# For whatever reason codecs.getwriter() does not advertise its encoding
304
# it just returns the encoding of the wrapped file, which is completely
305
# bogus. So set the attribute, so we can find the correct encoding later.
306
encoded_stdout.encoding = encoding
307
return TextUIOutputStream(self, encoded_stdout)
310
"""Write an already-formatted message, clearing the progress bar if necessary."""
312
self.stdout.write(msg + '\n')
314
def prompt(self, prompt, **kwargs):
315
"""Emit prompt on the CLI.
317
:param kwargs: Dictionary of arguments to insert into the prompt,
318
to allow UIs to reformat the prompt.
320
if type(prompt) != unicode:
321
raise ValueError("prompt %r not a unicode string" % prompt)
323
# See <https://launchpad.net/bugs/365891>
324
prompt = prompt % kwargs
325
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
328
self.stderr.write(prompt)
330
def report_transport_activity(self, transport, byte_count, direction):
331
"""Called by transports as they do IO.
333
This may update a progress bar, spinner, or similar display.
334
By default it does nothing.
336
self._progress_view.show_transport_activity(transport,
337
direction, byte_count)
339
def log_transport_activity(self, display=False):
340
"""See UIFactory.log_transport_activity()"""
341
log = getattr(self._progress_view, 'log_transport_activity', None)
345
def show_error(self, msg):
347
self.stderr.write("bzr: error: %s\n" % msg)
349
def show_message(self, msg):
352
def show_warning(self, msg):
354
if isinstance(msg, unicode):
355
te = osutils.get_terminal_encoding()
356
msg = msg.encode(te, 'replace')
357
self.stderr.write("bzr: warning: %s\n" % msg)
359
def _progress_updated(self, task):
360
"""A task has been updated and wants to be displayed.
362
if not self._task_stack:
363
warnings.warn("%r updated but no tasks are active" %
365
elif task != self._task_stack[-1]:
366
# We used to check it was the top task, but it's hard to always
367
# get this right and it's not necessarily useful: any actual
368
# problems will be evident in use
369
#warnings.warn("%r is not the top progress task %r" %
370
# (task, self._task_stack[-1]))
372
self._progress_view.show_progress(task)
374
def _progress_all_finished(self):
375
self._progress_view.clear()
377
def show_user_warning(self, warning_id, **message_args):
378
"""Show a text message to the user.
380
Explicitly not for warnings about bzr apis, deprecations or internals.
382
# eventually trace.warning should migrate here, to avoid logging and
383
# be easier to test; that has a lot of test fallout so for now just
384
# new code can call this
385
if warning_id not in self.suppressed_warnings:
386
self.stderr.write(self.format_user_warning(warning_id, message_args) +
390
class TextProgressView(object):
391
"""Display of progress bar and other information on a tty.
393
This shows one line of text, including possibly a network indicator, spinner,
394
progress bar, message, etc.
396
One instance of this is created and held by the UI, and fed updates when a
397
task wants to be painted.
399
Transports feed data to this through the ui_factory object.
401
The Progress views can comprise a tree with _parent_task pointers, but
402
this only prints the stack from the nominated current task up to the root.
405
def __init__(self, term_file):
406
self._term_file = term_file
407
# true when there's output on the screen we may need to clear
408
self._have_output = False
409
self._last_transport_msg = ''
411
# time we last repainted the screen
412
self._last_repaint = 0
413
# time we last got information about transport activity
414
self._transport_update_time = 0
415
self._last_task = None
416
self._total_byte_count = 0
417
self._bytes_since_update = 0
418
self._bytes_by_direction = {'unknown': 0, 'read': 0, 'write': 0}
419
self._first_byte_time = None
421
# force the progress bar to be off, as at the moment it doesn't
422
# correspond reliably to overall command progress
423
self.enable_bar = False
425
def _avail_width(self):
426
# we need one extra space for terminals that wrap on last char
427
w = osutils.terminal_width()
433
def _show_line(self, s):
434
# sys.stderr.write("progress %r\n" % s)
435
width = self._avail_width()
436
if width is not None:
437
s = '%-*.*s' % (width, width, s)
438
self._term_file.write('\r' + s + '\r')
441
if self._have_output:
443
self._have_output = False
445
def _render_bar(self):
446
# return a string for the progress bar itself
447
if self.enable_bar and (
448
(self._last_task is None) or self._last_task.show_bar):
449
# If there's no task object, we show space for the bar anyhow.
450
# That's because most invocations of bzr will end showing progress
451
# at some point, though perhaps only after doing some initial IO.
452
# It looks better to draw the progress bar initially rather than
453
# to have what looks like an incomplete progress bar.
454
spin_str = r'/-\|'[self._spin_pos % 4]
457
if self._last_task is None:
458
completion_fraction = 0
461
completion_fraction = \
462
self._last_task._overall_completion_fraction() or 0
463
if (completion_fraction < self._fraction and 'progress' in
465
import pdb;pdb.set_trace()
466
self._fraction = completion_fraction
467
markers = int(round(float(cols) * completion_fraction)) - 1
468
bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
470
elif (self._last_task is None) or self._last_task.show_spinner:
471
# The last task wanted just a spinner, no bar
472
spin_str = r'/-\|'[self._spin_pos % 4]
474
return spin_str + ' '
478
def _format_task(self, task):
479
"""Format task-specific parts of progress bar.
481
:returns: (text_part, counter_part) both unicode strings.
483
if not task.show_count:
485
elif task.current_cnt is not None and task.total_cnt is not None:
486
s = ' %d/%d' % (task.current_cnt, task.total_cnt)
487
elif task.current_cnt is not None:
488
s = ' %d' % (task.current_cnt)
491
# compose all the parent messages
494
while t._parent_task:
500
def _render_line(self):
501
bar_string = self._render_bar()
503
task_part, counter_part = self._format_task(self._last_task)
505
task_part = counter_part = ''
506
if self._last_task and not self._last_task.show_transport_activity:
509
trans = self._last_transport_msg
510
# the bar separates the transport activity from the message, so even
511
# if there's no bar or spinner, we must show something if both those
513
if (task_part or trans) and not bar_string:
515
# preferentially truncate the task message if we don't have enough
517
avail_width = self._avail_width()
518
if avail_width is not None:
519
# if terminal avail_width is unknown, don't truncate
520
current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
521
gap = current_len - avail_width
523
task_part = task_part[:-gap-2] + '..'
524
s = trans + bar_string + task_part + counter_part
525
if avail_width is not None:
526
if len(s) < avail_width:
527
s = s.ljust(avail_width)
528
elif len(s) > avail_width:
533
s = self._render_line()
535
self._have_output = True
537
def show_progress(self, task):
538
"""Called by the task object when it has changed.
540
:param task: The top task object; its parents are also included
543
must_update = task is not self._last_task
544
self._last_task = task
546
if (not must_update) and (now < self._last_repaint + task.update_latency):
548
if now > self._transport_update_time + 10:
549
# no recent activity; expire it
550
self._last_transport_msg = ''
551
self._last_repaint = now
554
def show_transport_activity(self, transport, direction, byte_count):
555
"""Called by transports via the ui_factory, as they do IO.
557
This may update a progress bar, spinner, or similar display.
558
By default it does nothing.
560
# XXX: there should be a transport activity model, and that too should
561
# be seen by the progress view, rather than being poked in here.
562
self._total_byte_count += byte_count
563
self._bytes_since_update += byte_count
564
if self._first_byte_time is None:
565
# Note that this isn't great, as technically it should be the time
566
# when the bytes started transferring, not when they completed.
567
# However, we usually start with a small request anyway.
568
self._first_byte_time = time.time()
569
if direction in self._bytes_by_direction:
570
self._bytes_by_direction[direction] += byte_count
572
self._bytes_by_direction['unknown'] += byte_count
573
if 'no_activity' in debug.debug_flags:
574
# Can be used as a workaround if
575
# <https://launchpad.net/bugs/321935> reappears and transport
576
# activity is cluttering other output. However, thanks to
577
# TextUIOutputStream this shouldn't be a problem any more.
580
if self._total_byte_count < 2000:
581
# a little resistance at first, so it doesn't stay stuck at 0
582
# while connecting...
584
if self._transport_update_time is None:
585
self._transport_update_time = now
586
elif now >= (self._transport_update_time + 0.5):
587
# guard against clock stepping backwards, and don't update too
589
rate = (self._bytes_since_update
590
/ (now - self._transport_update_time))
591
# using base-10 units (see HACKING.txt).
592
msg = ("%6dkB %5dkB/s " %
593
(self._total_byte_count / 1000, int(rate) / 1000,))
594
self._transport_update_time = now
595
self._last_repaint = now
596
self._bytes_since_update = 0
597
self._last_transport_msg = msg
600
def _format_bytes_by_direction(self):
601
if self._first_byte_time is None:
604
transfer_time = time.time() - self._first_byte_time
605
if transfer_time < 0.001:
606
transfer_time = 0.001
607
bps = self._total_byte_count / transfer_time
609
# using base-10 units (see HACKING.txt).
610
msg = ('Transferred: %.0fkB'
611
' (%.1fkB/s r:%.0fkB w:%.0fkB'
612
% (self._total_byte_count / 1000.,
614
self._bytes_by_direction['read'] / 1000.,
615
self._bytes_by_direction['write'] / 1000.,
617
if self._bytes_by_direction['unknown'] > 0:
618
msg += ' u:%.0fkB)' % (
619
self._bytes_by_direction['unknown'] / 1000.
625
def log_transport_activity(self, display=False):
626
msg = self._format_bytes_by_direction()
628
if display and self._total_byte_count > 0:
630
self._term_file.write(msg + '\n')
633
class TextUIOutputStream(object):
634
"""Decorates an output stream so that the terminal is cleared before writing.
636
This is supposed to ensure that the progress bar does not conflict with bulk
639
# XXX: this does not handle the case of writing part of a line, then doing
640
# progress bar output: the progress bar will probably write over it.
641
# one option is just to buffer that text until we have a full line;
642
# another is to save and restore it
644
# XXX: might need to wrap more methods
646
def __init__(self, ui_factory, wrapped_stream):
647
self.ui_factory = ui_factory
648
self.wrapped_stream = wrapped_stream
649
# this does no transcoding, but it must expose the underlying encoding
650
# because some callers need to know what can be written - see for
651
# example unescape_for_display.
652
self.encoding = getattr(wrapped_stream, 'encoding', None)
655
self.ui_factory.clear_term()
656
self.wrapped_stream.flush()
658
def write(self, to_write):
659
self.ui_factory.clear_term()
660
self.wrapped_stream.write(to_write)
662
def writelines(self, lines):
663
self.ui_factory.clear_term()
664
self.wrapped_stream.writelines(lines)