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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
18
"""Text UI, write output to the console.
21
from __future__ import absolute_import
24
27
from bzrlib.lazy_import import lazy_import
25
28
lazy_import(globals(), """
28
33
from bzrlib import (
34
from bzrlib.symbol_versioning import (
42
from bzrlib.ui import (
38
from bzrlib.ui import CLIUIFactory
41
class TextUIFactory(CLIUIFactory):
48
class _ChooseUI(object):
50
""" Helper class for choose implementation.
53
def __init__(self, ui, msg, choices, default):
56
self._build_alternatives(msg, choices, default)
58
def _setup_mode(self):
59
"""Setup input mode (line-based, char-based) and echo-back.
61
Line-based input is used if the BZR_TEXTUI_INPUT environment
62
variable is set to 'line-based', or if there is no controlling
65
if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
66
self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
67
self.line_based = False
70
self.line_based = True
71
self.echo_back = not self.ui.stdin.isatty()
73
def _build_alternatives(self, msg, choices, default):
74
"""Parse choices string.
76
Setup final prompt and the lists of choices and associated
81
self.alternatives = {}
82
choices = choices.split('\n')
83
if default is not None and default not in range(0, len(choices)):
84
raise ValueError("invalid default index")
86
name = c.replace('&', '').lower()
87
choice = (name, index)
88
if name in self.alternatives:
89
raise ValueError("duplicated choice: %s" % name)
90
self.alternatives[name] = choice
91
shortcut = c.find('&')
92
if -1 != shortcut and (shortcut + 1) < len(c):
94
help += '[' + c[shortcut + 1] + ']'
95
help += c[(shortcut + 2):]
96
shortcut = c[shortcut + 1]
98
c = c.replace('&', '')
100
help = '[%s]%s' % (shortcut, c[1:])
101
shortcut = shortcut.lower()
102
if shortcut in self.alternatives:
103
raise ValueError("duplicated shortcut: %s" % shortcut)
104
self.alternatives[shortcut] = choice
105
# Add redirections for default.
107
self.alternatives[''] = choice
108
self.alternatives['\r'] = choice
109
help_list.append(help)
112
self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
115
line = self.ui.stdin.readline()
121
char = osutils.getchar()
122
if char == chr(3): # INTR
123
raise KeyboardInterrupt
124
if char == chr(4): # EOF (^d, C-d)
129
"""Keep asking the user until a valid choice is made.
132
getchoice = self._getline
134
getchoice = self._getchar
138
if 1 == iter or self.line_based:
139
self.ui.prompt(self.prompt)
143
self.ui.stderr.write('\n')
145
except KeyboardInterrupt:
146
self.ui.stderr.write('\n')
147
raise KeyboardInterrupt
148
choice = choice.lower()
149
if choice not in self.alternatives:
150
# Not a valid choice, keep on asking.
152
name, index = self.alternatives[choice]
154
self.ui.stderr.write(name + '\n')
158
class TextUIFactory(UIFactory):
42
159
"""A UI factory for Text user interefaces."""
44
161
def __init__(self,
48
165
"""Create a TextUIFactory.
50
:param bar_type: The type of progress bar to create. It defaults to
51
letting the bzrlib.progress.ProgressBar factory auto
54
167
super(TextUIFactory, self).__init__()
55
self._bar_type = bar_type
57
self.stdout = sys.stdout
61
self.stderr = sys.stderr
65
def prompt(self, prompt):
66
"""Emit prompt on the CLI."""
67
self.stdout.write(prompt)
69
@deprecated_method(zero_eight)
70
def progress_bar(self):
71
"""See UIFactory.nested_progress_bar()."""
72
# this in turn is abstract, and creates either a tty or dots
73
# bar depending on what we think of the terminal
74
return progress.ProgressBar()
76
def nested_progress_bar(self):
77
"""Return a nested progress bar.
79
The actual bar type returned depends on the progress module which
80
may return a tty or dots bar depending on the terminal.
168
# TODO: there's no good reason not to pass all three streams, maybe we
169
# should deprecate the default values...
173
# paints progress, network activity, etc
174
self._progress_view = self.make_progress_view()
176
def choose(self, msg, choices, default=None):
177
"""Prompt the user for a list of alternatives.
179
Support both line-based and char-based editing.
181
In line-based mode, both the shortcut and full choice name are valid
182
answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
183
'YES ' are all valid input lines for choosing 'yes'.
185
An empty line, when in line-based mode, or pressing enter in char-based
186
mode will select the default choice (if any).
188
Choice is echoed back if:
189
- input is char-based; which means a controlling terminal is available,
190
and osutils.getchar is used
191
- input is line-based, and no controlling terminal is available
82
if self._progress_bar_stack is None:
83
self._progress_bar_stack = progress.ProgressBarStack(
85
return self._progress_bar_stack.get_nested()
194
choose_ui = _ChooseUI(self, msg, choices, default)
195
return choose_ui.interact()
197
def be_quiet(self, state):
198
if state and not self._quiet:
200
UIFactory.be_quiet(self, state)
201
self._progress_view = self.make_progress_view()
87
203
def clear_term(self):
88
204
"""Prepare the terminal for output.
90
206
This will, clear any progress bars, and leave the cursor at the
91
207
leftmost position."""
92
if self._progress_bar_stack is None:
94
overall_pb = self._progress_bar_stack.bottom()
95
if overall_pb is not None:
208
# XXX: If this is preparing to write to stdout, but that's for example
209
# directed into a file rather than to the terminal, and the progress
210
# bar _is_ going to the terminal, we shouldn't need
211
# to clear it. We might need to separately check for the case of
212
self._progress_view.clear()
214
def get_integer(self, prompt):
217
line = self.stdin.readline()
223
def get_non_echoed_password(self):
224
isatty = getattr(self.stdin, 'isatty', None)
225
if isatty is not None and isatty():
226
# getpass() ensure the password is not echoed and other
227
# cross-platform niceties
228
password = getpass.getpass('')
230
# echo doesn't make sense without a terminal
231
password = self.stdin.readline()
234
elif password[-1] == '\n':
235
password = password[:-1]
238
def get_password(self, prompt=u'', **kwargs):
239
"""Prompt the user for a password.
241
:param prompt: The prompt to present the user
242
:param kwargs: Arguments which will be expanded into the prompt.
243
This lets front ends display different things if
245
:return: The password string, return None if the user
246
canceled the request.
249
self.prompt(prompt, **kwargs)
250
# There's currently no way to say 'i decline to enter a password'
251
# as opposed to 'my password is empty' -- does it matter?
252
return self.get_non_echoed_password()
254
def get_username(self, prompt, **kwargs):
255
"""Prompt the user for a username.
257
:param prompt: The prompt to present the user
258
:param kwargs: Arguments which will be expanded into the prompt.
259
This lets front ends display different things if
261
:return: The username string, return None if the user
262
canceled the request.
265
self.prompt(prompt, **kwargs)
266
username = self.stdin.readline()
269
elif username[-1] == '\n':
270
username = username[:-1]
273
def make_progress_view(self):
274
"""Construct and return a new ProgressView subclass for this UI.
276
# with --quiet, never any progress view
277
# <https://bugs.launchpad.net/bzr/+bug/320035>. Otherwise if the
278
# user specifically requests either text or no progress bars, always
279
# do that. otherwise, guess based on $TERM and tty presence.
281
return NullProgressView()
282
elif os.environ.get('BZR_PROGRESS_BAR') == 'text':
283
return TextProgressView(self.stderr)
284
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
285
return NullProgressView()
286
elif progress._supports_progress(self.stderr):
287
return TextProgressView(self.stderr)
289
return NullProgressView()
291
def _make_output_stream_explicit(self, encoding, encoding_type):
292
if encoding_type == 'exact':
293
# force sys.stdout to be binary stream on win32;
294
# NB: this leaves the file set in that mode; may cause problems if
295
# one process tries to do binary and then text output
296
if sys.platform == 'win32':
297
fileno = getattr(self.stdout, 'fileno', None)
300
msvcrt.setmode(fileno(), os.O_BINARY)
301
return TextUIOutputStream(self, self.stdout)
303
encoded_stdout = codecs.getwriter(encoding)(self.stdout,
304
errors=encoding_type)
305
# For whatever reason codecs.getwriter() does not advertise its encoding
306
# it just returns the encoding of the wrapped file, which is completely
307
# bogus. So set the attribute, so we can find the correct encoding later.
308
encoded_stdout.encoding = encoding
309
return TextUIOutputStream(self, encoded_stdout)
312
"""Write an already-formatted message, clearing the progress bar if necessary."""
314
self.stdout.write(msg + '\n')
316
def prompt(self, prompt, **kwargs):
317
"""Emit prompt on the CLI.
319
:param kwargs: Dictionary of arguments to insert into the prompt,
320
to allow UIs to reformat the prompt.
322
if type(prompt) != unicode:
323
raise ValueError("prompt %r not a unicode string" % prompt)
325
# See <https://launchpad.net/bugs/365891>
326
prompt = prompt % kwargs
327
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
330
self.stderr.write(prompt)
332
def report_transport_activity(self, transport, byte_count, direction):
333
"""Called by transports as they do IO.
335
This may update a progress bar, spinner, or similar display.
336
By default it does nothing.
338
self._progress_view.show_transport_activity(transport,
339
direction, byte_count)
341
def log_transport_activity(self, display=False):
342
"""See UIFactory.log_transport_activity()"""
343
log = getattr(self._progress_view, 'log_transport_activity', None)
347
def show_error(self, msg):
349
self.stderr.write("bzr: error: %s\n" % msg)
351
def show_message(self, msg):
354
def show_warning(self, msg):
356
if isinstance(msg, unicode):
357
te = osutils.get_terminal_encoding()
358
msg = msg.encode(te, 'replace')
359
self.stderr.write("bzr: warning: %s\n" % msg)
361
def _progress_updated(self, task):
362
"""A task has been updated and wants to be displayed.
364
if not self._task_stack:
365
warnings.warn("%r updated but no tasks are active" %
367
elif task != self._task_stack[-1]:
368
# We used to check it was the top task, but it's hard to always
369
# get this right and it's not necessarily useful: any actual
370
# problems will be evident in use
371
#warnings.warn("%r is not the top progress task %r" %
372
# (task, self._task_stack[-1]))
374
self._progress_view.show_progress(task)
376
def _progress_all_finished(self):
377
self._progress_view.clear()
379
def show_user_warning(self, warning_id, **message_args):
380
"""Show a text message to the user.
382
Explicitly not for warnings about bzr apis, deprecations or internals.
384
# eventually trace.warning should migrate here, to avoid logging and
385
# be easier to test; that has a lot of test fallout so for now just
386
# new code can call this
387
if warning_id not in self.suppressed_warnings:
388
self.stderr.write(self.format_user_warning(warning_id, message_args) +
392
class TextProgressView(object):
393
"""Display of progress bar and other information on a tty.
395
This shows one line of text, including possibly a network indicator, spinner,
396
progress bar, message, etc.
398
One instance of this is created and held by the UI, and fed updates when a
399
task wants to be painted.
401
Transports feed data to this through the ui_factory object.
403
The Progress views can comprise a tree with _parent_task pointers, but
404
this only prints the stack from the nominated current task up to the root.
407
def __init__(self, term_file, encoding=None, errors="replace"):
408
self._term_file = term_file
410
self._encoding = getattr(term_file, "encoding", None) or "ascii"
412
self._encoding = encoding
413
self._encoding_errors = errors
414
# true when there's output on the screen we may need to clear
415
self._have_output = False
416
self._last_transport_msg = ''
418
# time we last repainted the screen
419
self._last_repaint = 0
420
# time we last got information about transport activity
421
self._transport_update_time = 0
422
self._last_task = None
423
self._total_byte_count = 0
424
self._bytes_since_update = 0
425
self._bytes_by_direction = {'unknown': 0, 'read': 0, 'write': 0}
426
self._first_byte_time = None
428
# force the progress bar to be off, as at the moment it doesn't
429
# correspond reliably to overall command progress
430
self.enable_bar = False
432
def _avail_width(self):
433
# we need one extra space for terminals that wrap on last char
434
w = osutils.terminal_width()
440
def _show_line(self, u):
441
s = u.encode(self._encoding, self._encoding_errors)
442
width = self._avail_width()
443
if width is not None:
444
# GZ 2012-03-28: Counting bytes is wrong for calculating width of
445
# text but better than counting codepoints.
446
s = '%-*.*s' % (width, width, s)
447
self._term_file.write('\r' + s + '\r')
450
if self._have_output:
452
self._have_output = False
454
def _render_bar(self):
455
# return a string for the progress bar itself
456
if self.enable_bar and (
457
(self._last_task is None) or self._last_task.show_bar):
458
# If there's no task object, we show space for the bar anyhow.
459
# That's because most invocations of bzr will end showing progress
460
# at some point, though perhaps only after doing some initial IO.
461
# It looks better to draw the progress bar initially rather than
462
# to have what looks like an incomplete progress bar.
463
spin_str = r'/-\|'[self._spin_pos % 4]
466
if self._last_task is None:
467
completion_fraction = 0
470
completion_fraction = \
471
self._last_task._overall_completion_fraction() or 0
472
if (completion_fraction < self._fraction and 'progress' in
474
import pdb;pdb.set_trace()
475
self._fraction = completion_fraction
476
markers = int(round(float(cols) * completion_fraction)) - 1
477
bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
479
elif (self._last_task is None) or self._last_task.show_spinner:
480
# The last task wanted just a spinner, no bar
481
spin_str = r'/-\|'[self._spin_pos % 4]
483
return spin_str + ' '
487
def _format_task(self, task):
488
"""Format task-specific parts of progress bar.
490
:returns: (text_part, counter_part) both unicode strings.
492
if not task.show_count:
494
elif task.current_cnt is not None and task.total_cnt is not None:
495
s = ' %d/%d' % (task.current_cnt, task.total_cnt)
496
elif task.current_cnt is not None:
497
s = ' %d' % (task.current_cnt)
500
# compose all the parent messages
503
while t._parent_task:
509
def _render_line(self):
510
bar_string = self._render_bar()
512
task_part, counter_part = self._format_task(self._last_task)
514
task_part = counter_part = ''
515
if self._last_task and not self._last_task.show_transport_activity:
518
trans = self._last_transport_msg
519
# the bar separates the transport activity from the message, so even
520
# if there's no bar or spinner, we must show something if both those
522
if (task_part or trans) and not bar_string:
524
# preferentially truncate the task message if we don't have enough
526
avail_width = self._avail_width()
527
if avail_width is not None:
528
# if terminal avail_width is unknown, don't truncate
529
current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
530
gap = current_len - avail_width
532
task_part = task_part[:-gap-2] + '..'
533
s = trans + bar_string + task_part + counter_part
534
if avail_width is not None:
535
if len(s) < avail_width:
536
s = s.ljust(avail_width)
537
elif len(s) > avail_width:
542
s = self._render_line()
544
self._have_output = True
546
def show_progress(self, task):
547
"""Called by the task object when it has changed.
549
:param task: The top task object; its parents are also included
552
must_update = task is not self._last_task
553
self._last_task = task
555
if (not must_update) and (now < self._last_repaint + task.update_latency):
557
if now > self._transport_update_time + 10:
558
# no recent activity; expire it
559
self._last_transport_msg = ''
560
self._last_repaint = now
563
def show_transport_activity(self, transport, direction, byte_count):
564
"""Called by transports via the ui_factory, as they do IO.
566
This may update a progress bar, spinner, or similar display.
567
By default it does nothing.
569
# XXX: there should be a transport activity model, and that too should
570
# be seen by the progress view, rather than being poked in here.
571
self._total_byte_count += byte_count
572
self._bytes_since_update += byte_count
573
if self._first_byte_time is None:
574
# Note that this isn't great, as technically it should be the time
575
# when the bytes started transferring, not when they completed.
576
# However, we usually start with a small request anyway.
577
self._first_byte_time = time.time()
578
if direction in self._bytes_by_direction:
579
self._bytes_by_direction[direction] += byte_count
581
self._bytes_by_direction['unknown'] += byte_count
582
if 'no_activity' in debug.debug_flags:
583
# Can be used as a workaround if
584
# <https://launchpad.net/bugs/321935> reappears and transport
585
# activity is cluttering other output. However, thanks to
586
# TextUIOutputStream this shouldn't be a problem any more.
589
if self._total_byte_count < 2000:
590
# a little resistance at first, so it doesn't stay stuck at 0
591
# while connecting...
593
if self._transport_update_time is None:
594
self._transport_update_time = now
595
elif now >= (self._transport_update_time + 0.5):
596
# guard against clock stepping backwards, and don't update too
598
rate = (self._bytes_since_update
599
/ (now - self._transport_update_time))
600
# using base-10 units (see HACKING.txt).
601
msg = ("%6dkB %5dkB/s " %
602
(self._total_byte_count / 1000, int(rate) / 1000,))
603
self._transport_update_time = now
604
self._last_repaint = now
605
self._bytes_since_update = 0
606
self._last_transport_msg = msg
609
def _format_bytes_by_direction(self):
610
if self._first_byte_time is None:
613
transfer_time = time.time() - self._first_byte_time
614
if transfer_time < 0.001:
615
transfer_time = 0.001
616
bps = self._total_byte_count / transfer_time
618
# using base-10 units (see HACKING.txt).
619
msg = ('Transferred: %.0fkB'
620
' (%.1fkB/s r:%.0fkB w:%.0fkB'
621
% (self._total_byte_count / 1000.,
623
self._bytes_by_direction['read'] / 1000.,
624
self._bytes_by_direction['write'] / 1000.,
626
if self._bytes_by_direction['unknown'] > 0:
627
msg += ' u:%.0fkB)' % (
628
self._bytes_by_direction['unknown'] / 1000.
634
def log_transport_activity(self, display=False):
635
msg = self._format_bytes_by_direction()
637
if display and self._total_byte_count > 0:
639
self._term_file.write(msg + '\n')
642
class TextUIOutputStream(object):
643
"""Decorates an output stream so that the terminal is cleared before writing.
645
This is supposed to ensure that the progress bar does not conflict with bulk
648
# XXX: this does not handle the case of writing part of a line, then doing
649
# progress bar output: the progress bar will probably write over it.
650
# one option is just to buffer that text until we have a full line;
651
# another is to save and restore it
653
# XXX: might need to wrap more methods
655
def __init__(self, ui_factory, wrapped_stream):
656
self.ui_factory = ui_factory
657
self.wrapped_stream = wrapped_stream
658
# this does no transcoding, but it must expose the underlying encoding
659
# because some callers need to know what can be written - see for
660
# example unescape_for_display.
661
self.encoding = getattr(wrapped_stream, 'encoding', None)
664
self.ui_factory.clear_term()
665
self.wrapped_stream.flush()
667
def write(self, to_write):
668
self.ui_factory.clear_term()
669
self.wrapped_stream.write(to_write)
671
def writelines(self, lines):
672
self.ui_factory.clear_term()
673
self.wrapped_stream.writelines(lines)