14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Text UI, write output to the console."""
18
"""Text UI, write output to the console.
19
from __future__ import absolute_import
28
from bzrlib.lazy_import import lazy_import
26
from ..lazy_import import lazy_import
29
27
lazy_import(globals(), """
40
from bzrlib.osutils import watch_sigwinch
42
from bzrlib.ui import (
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 BRZ_TEXTUI_INPUT environment
62
variable is set to 'line-based', or if there is no controlling
65
if os.environ.get('BRZ_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)
126
return char.decode("ascii", "replace")
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(u'\n')
145
except KeyboardInterrupt:
146
self.ui.stderr.write(u'\n')
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 + u'\n')
158
opt_progress_bar = config.Option(
159
'progress_bar', help='Progress bar type.',
160
default_from_env=['BRZ_PROGRESS_BAR'], default=None,
48
164
class TextUIFactory(UIFactory):
49
"""A UI factory for Text user interefaces."""
165
"""A UI factory for Text user interfaces."""
55
"""Create a TextUIFactory.
167
def __init__(self, stdin, stdout, stderr):
168
"""Create a TextUIFactory."""
57
169
super(TextUIFactory, self).__init__()
58
# TODO: there's no good reason not to pass all three streams, maybe we
59
# should deprecate the default values...
60
170
self.stdin = stdin
61
171
self.stdout = stdout
62
172
self.stderr = stderr
63
173
# paints progress, network activity, etc
64
174
self._progress_view = self.make_progress_view()
65
# hook up the signals to watch for terminal size changes
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
194
choose_ui = _ChooseUI(self, msg, choices, default)
195
return choose_ui.interact()
68
197
def be_quiet(self, state):
69
198
if state and not self._quiet:
149
267
username = self.stdin.readline()
152
elif username[-1] == '\n':
153
username = username[:-1]
271
if username[-1] == '\n':
272
username = username[:-1]
156
275
def make_progress_view(self):
157
276
"""Construct and return a new ProgressView subclass for this UI.
159
278
# with --quiet, never any progress view
160
# <https://bugs.edge.launchpad.net/bzr/+bug/320035>. Otherwise if the
279
# <https://bugs.launchpad.net/bzr/+bug/320035>. Otherwise if the
161
280
# user specifically requests either text or no progress bars, always
162
281
# do that. otherwise, guess based on $TERM and tty presence.
163
282
if self.is_quiet():
164
283
return NullProgressView()
165
elif os.environ.get('BZR_PROGRESS_BAR') == 'text':
166
return TextProgressView(self.stderr)
167
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
168
return NullProgressView()
169
elif progress._supports_progress(self.stderr):
170
return TextProgressView(self.stderr)
172
return NullProgressView()
284
pb_type = config.GlobalStack().get('progress_bar')
285
if pb_type == 'none': # Explicit requirement
286
return NullProgressView()
287
if (pb_type == 'text' # Explicit requirement
288
or progress._supports_progress(self.stderr)): # Guess
289
return TextProgressView(self.stderr)
290
# No explicit requirement and no successful guess
291
return NullProgressView()
174
293
def _make_output_stream_explicit(self, encoding, encoding_type):
175
if encoding_type == 'exact':
176
# force sys.stdout to be binary stream on win32;
177
# NB: this leaves the file set in that mode; may cause problems if
178
# one process tries to do binary and then text output
179
if sys.platform == 'win32':
180
fileno = getattr(self.stdout, 'fileno', None)
183
msvcrt.setmode(fileno(), os.O_BINARY)
184
return TextUIOutputStream(self, self.stdout)
186
encoded_stdout = codecs.getwriter(encoding)(self.stdout,
187
errors=encoding_type)
188
# For whatever reason codecs.getwriter() does not advertise its encoding
189
# it just returns the encoding of the wrapped file, which is completely
190
# bogus. So set the attribute, so we can find the correct encoding later.
191
encoded_stdout.encoding = encoding
192
return TextUIOutputStream(self, encoded_stdout)
294
return TextUIOutputStream(self, self.stdout, encoding, encoding_type)
194
296
def note(self, msg):
195
297
"""Write an already-formatted message, clearing the progress bar if necessary."""
262
366
# be easier to test; that has a lot of test fallout so for now just
263
367
# new code can call this
264
368
if warning_id not in self.suppressed_warnings:
265
self.stderr.write(self.format_user_warning(warning_id, message_args) +
369
warning = self.format_user_warning(warning_id, message_args)
370
self.stderr.write(warning + '\n')
373
def pad_to_width(line, width, encoding_hint='ascii'):
374
"""Truncate or pad unicode line to width.
376
This is best-effort for now, and strings containing control codes or
377
non-ascii text may be cut and padded incorrectly.
379
s = line.encode(encoding_hint, 'replace')
380
return (b'%-*.*s' % (width, width, s)).decode(encoding_hint)
269
383
class TextProgressView(object):
270
384
"""Display of progress bar and other information on a tty.
272
This shows one line of text, including possibly a network indicator, spinner,
273
progress bar, message, etc.
386
This shows one line of text, including possibly a network indicator,
387
spinner, progress bar, message, etc.
275
389
One instance of this is created and held by the UI, and fed updates when a
276
390
task wants to be painted.
364
491
t = t._parent_task
366
493
m = t.msg + ':' + m
369
496
def _render_line(self):
370
497
bar_string = self._render_bar()
371
498
if self._last_task:
372
task_msg = self._format_task(self._last_task)
499
task_part, counter_part = self._format_task(self._last_task)
501
task_part = counter_part = ''
375
502
if self._last_task and not self._last_task.show_transport_activity:
378
505
trans = self._last_transport_msg
381
return (bar_string + trans + task_msg)
506
# the bar separates the transport activity from the message, so even
507
# if there's no bar or spinner, we must show something if both those
509
if (task_part or trans) and not bar_string:
511
# preferentially truncate the task message if we don't have enough
513
avail_width = self._avail_width()
514
if avail_width is not None:
515
# if terminal avail_width is unknown, don't truncate
516
current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
517
# GZ 2017-04-22: Should measure and truncate task_part properly
518
gap = current_len - avail_width
520
task_part = task_part[:-gap-2] + '..'
521
s = trans + bar_string + task_part + counter_part
522
if avail_width is not None:
523
if len(s) < avail_width:
524
s = s.ljust(avail_width)
525
elif len(s) > avail_width:
383
529
def _repaint(self):
384
530
s = self._render_line()
481
627
self._term_file.write(msg + '\n')
630
def _get_stream_encoding(stream):
631
encoding = config.GlobalStack().get('output_encoding')
633
encoding = getattr(stream, "encoding", None)
635
encoding = osutils.get_terminal_encoding(trace=True)
639
def _unwrap_stream(stream):
640
inner = getattr(stream, "buffer", None)
642
inner = getattr(stream, "stream", None)
646
def _wrap_in_stream(stream, encoding=None, errors='replace'):
648
encoding = _get_stream_encoding(stream)
649
encoded_stream = codecs.getreader(encoding)(stream, errors=errors)
650
encoded_stream.encoding = encoding
651
return encoded_stream
654
def _wrap_out_stream(stream, encoding=None, errors='replace'):
656
encoding = _get_stream_encoding(stream)
657
encoded_stream = codecs.getwriter(encoding)(stream, errors=errors)
658
encoded_stream.encoding = encoding
659
return encoded_stream
484
662
class TextUIOutputStream(object):
485
"""Decorates an output stream so that the terminal is cleared before writing.
487
This is supposed to ensure that the progress bar does not conflict with bulk
663
"""Decorates stream to interact better with progress and change encoding.
665
Before writing to the wrapped stream, progress is cleared. Callers must
666
ensure bulk output is terminated with a newline so progress won't overwrite
669
Additionally, the encoding and errors behaviour of the underlying stream
670
can be changed at this point. If errors is set to 'exact' raw bytes may be
671
written to the underlying stream.
490
# XXX: this does not handle the case of writing part of a line, then doing
491
# progress bar output: the progress bar will probably write over it.
492
# one option is just to buffer that text until we have a full line;
493
# another is to save and restore it
495
# XXX: might need to wrap more methods
497
def __init__(self, ui_factory, wrapped_stream):
674
def __init__(self, ui_factory, stream, encoding=None, errors='strict'):
498
675
self.ui_factory = ui_factory
499
self.wrapped_stream = wrapped_stream
500
# this does no transcoding, but it must expose the underlying encoding
501
# because some callers need to know what can be written - see for
502
# example unescape_for_display.
503
self.encoding = getattr(wrapped_stream, 'encoding', None)
676
# GZ 2017-05-21: Clean up semantics when callers are made saner.
677
inner = _unwrap_stream(stream)
678
self.raw_stream = None
679
if errors == "exact":
681
self.raw_stream = inner
683
self.wrapped_stream = stream
685
encoding = _get_stream_encoding(stream)
687
self.wrapped_stream = _wrap_out_stream(inner, encoding, errors)
689
encoding = self.wrapped_stream.encoding
690
self.encoding = encoding
693
def _write(self, to_write):
694
if isinstance(to_write, bytes):
696
to_write = to_write.decode(self.encoding, self.errors)
697
except UnicodeDecodeError:
698
self.raw_stream.write(to_write)
700
self.wrapped_stream.write(to_write)
506
703
self.ui_factory.clear_term()