49
class _ChooseUI(object):
51
""" Helper class for choose implementation.
54
def __init__(self, ui, msg, choices, default):
57
self._build_alternatives(msg, choices, default)
59
def _setup_mode(self):
60
"""Setup input mode (line-based, char-based) and echo-back.
62
Line-based input is used if the BZR_TEXTUI_INPUT environment
63
variable is set to 'line-based', or if there is no controlling
66
if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
67
self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
68
self.line_based = False
71
self.line_based = True
72
self.echo_back = not self.ui.stdin.isatty()
74
def _build_alternatives(self, msg, choices, default):
75
"""Parse choices string.
77
Setup final prompt and the lists of choices and associated
82
self.alternatives = {}
83
choices = choices.split('\n')
84
if default is not None and default not in range(0, len(choices)):
85
raise ValueError("invalid default index")
87
name = c.replace('&', '').lower()
88
choice = (name, index)
89
if name in self.alternatives:
90
raise ValueError("duplicated choice: %s" % name)
91
self.alternatives[name] = choice
92
shortcut = c.find('&')
93
if -1 != shortcut and (shortcut + 1) < len(c):
95
help += '[' + c[shortcut + 1] + ']'
96
help += c[(shortcut + 2):]
97
shortcut = c[shortcut + 1]
99
c = c.replace('&', '')
101
help = '[%s]%s' % (shortcut, c[1:])
102
shortcut = shortcut.lower()
103
if shortcut in self.alternatives:
104
raise ValueError("duplicated shortcut: %s" % shortcut)
105
self.alternatives[shortcut] = choice
106
# Add redirections for default.
108
self.alternatives[''] = choice
109
self.alternatives['\r'] = choice
110
help_list.append(help)
113
self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
116
line = self.ui.stdin.readline()
122
char = osutils.getchar()
123
if char == chr(3): # INTR
124
raise KeyboardInterrupt
125
if char == chr(4): # EOF (^d, C-d)
130
"""Keep asking the user until a valid choice is made.
133
getchoice = self._getline
135
getchoice = self._getchar
139
if 1 == iter or self.line_based:
140
self.ui.prompt(self.prompt)
144
self.ui.stderr.write('\n')
146
except KeyboardInterrupt:
147
self.ui.stderr.write('\n')
148
raise KeyboardInterrupt
149
choice = choice.lower()
150
if choice not in self.alternatives:
151
# Not a valid choice, keep on asking.
153
name, index = self.alternatives[choice]
155
self.ui.stderr.write(name + '\n')
159
opt_progress_bar = config.Option(
160
'progress_bar', help='Progress bar type.',
161
default_from_env=['BZR_PROGRESS_BAR'], default=None,
165
46
class TextUIFactory(UIFactory):
166
"""A UI factory for Text user interfaces."""
47
"""A UI factory for Text user interefaces."""
168
49
def __init__(self,
179
60
self.stderr = stderr
180
61
# paints progress, network activity, etc
181
62
self._progress_view = self.make_progress_view()
183
def choose(self, msg, choices, default=None):
184
"""Prompt the user for a list of alternatives.
186
Support both line-based and char-based editing.
188
In line-based mode, both the shortcut and full choice name are valid
189
answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
190
'YES ' are all valid input lines for choosing 'yes'.
192
An empty line, when in line-based mode, or pressing enter in char-based
193
mode will select the default choice (if any).
195
Choice is echoed back if:
196
- input is char-based; which means a controlling terminal is available,
197
and osutils.getchar is used
198
- input is line-based, and no controlling terminal is available
201
choose_ui = _ChooseUI(self, msg, choices, default)
202
return choose_ui.interact()
204
def be_quiet(self, state):
205
if state and not self._quiet:
207
UIFactory.be_quiet(self, state)
208
self._progress_view = self.make_progress_view()
210
64
def clear_term(self):
211
65
"""Prepare the terminal for output.
218
72
# to clear it. We might need to separately check for the case of
219
73
self._progress_view.clear()
75
def get_boolean(self, prompt):
77
self.prompt(prompt + "? [y/n]: ")
78
line = self.stdin.readline().lower()
79
if line in ('y\n', 'yes\n'):
81
elif line in ('n\n', 'no\n'):
83
elif line in ('', None):
84
# end-of-file; possibly should raise an error here instead
221
87
def get_integer(self, prompt):
223
89
self.prompt(prompt)
276
139
username = self.stdin.readline()
280
username = username.decode(self.stdin.encoding)
281
if username[-1] == '\n':
282
username = username[:-1]
142
elif username[-1] == '\n':
143
username = username[:-1]
285
146
def make_progress_view(self):
286
147
"""Construct and return a new ProgressView subclass for this UI.
288
# with --quiet, never any progress view
289
# <https://bugs.launchpad.net/bzr/+bug/320035>. Otherwise if the
290
# user specifically requests either text or no progress bars, always
291
# do that. otherwise, guess based on $TERM and tty presence.
293
return NullProgressView()
294
pb_type = config.GlobalStack().get('progress_bar')
295
if pb_type == 'none': # Explicit requirement
296
return NullProgressView()
297
if (pb_type == 'text' # Explicit requirement
298
or progress._supports_progress(self.stderr)): # Guess
299
return TextProgressView(self.stderr)
300
# No explicit requirement and no successful guess
301
return NullProgressView()
149
# if the user specifically requests either text or no progress bars,
150
# always do that. otherwise, guess based on $TERM and tty presence.
151
if os.environ.get('BZR_PROGRESS_BAR') == 'text':
152
return TextProgressView(self.stderr)
153
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
154
return NullProgressView()
155
elif progress._supports_progress(self.stderr):
156
return TextProgressView(self.stderr)
158
return NullProgressView()
303
160
def _make_output_stream_explicit(self, encoding, encoding_type):
304
161
if encoding_type == 'exact':
331
188
:param kwargs: Dictionary of arguments to insert into the prompt,
332
189
to allow UIs to reformat the prompt.
334
if type(prompt) != unicode:
335
raise ValueError("prompt %r not a unicode string" % prompt)
337
192
# See <https://launchpad.net/bugs/365891>
338
193
prompt = prompt % kwargs
340
prompt = prompt.encode(self.stderr.encoding)
341
except (UnicodeError, AttributeError):
342
# If stderr has no encoding attribute or can't properly encode,
343
# fallback to terminal encoding for robustness (better display
344
# something to the user than aborting with a traceback).
345
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
194
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
346
195
self.clear_term()
348
196
self.stderr.write(prompt)
350
198
def report_transport_activity(self, transport, byte_count, direction):
383
228
warnings.warn("%r updated but no tasks are active" %
385
230
elif task != self._task_stack[-1]:
386
# We used to check it was the top task, but it's hard to always
387
# get this right and it's not necessarily useful: any actual
388
# problems will be evident in use
389
#warnings.warn("%r is not the top progress task %r" %
390
# (task, self._task_stack[-1]))
231
warnings.warn("%r is not the top progress task %r" %
232
(task, self._task_stack[-1]))
392
233
self._progress_view.show_progress(task)
394
235
def _progress_all_finished(self):
395
236
self._progress_view.clear()
397
def show_user_warning(self, warning_id, **message_args):
398
"""Show a text message to the user.
400
Explicitly not for warnings about bzr apis, deprecations or internals.
402
# eventually trace.warning should migrate here, to avoid logging and
403
# be easier to test; that has a lot of test fallout so for now just
404
# new code can call this
405
if warning_id not in self.suppressed_warnings:
406
self.stderr.write(self.format_user_warning(warning_id, message_args) +
410
239
class TextProgressView(object):
411
240
"""Display of progress bar and other information on a tty.
422
251
this only prints the stack from the nominated current task up to the root.
425
def __init__(self, term_file, encoding=None, errors="replace"):
254
def __init__(self, term_file):
426
255
self._term_file = term_file
428
self._encoding = getattr(term_file, "encoding", None) or "ascii"
430
self._encoding = encoding
431
self._encoding_errors = errors
432
256
# true when there's output on the screen we may need to clear
433
257
self._have_output = False
434
258
self._last_transport_msg = ''
447
271
# correspond reliably to overall command progress
448
272
self.enable_bar = False
450
def _avail_width(self):
451
# we need one extra space for terminals that wrap on last char
452
w = osutils.terminal_width()
458
def _show_line(self, u):
459
s = u.encode(self._encoding, self._encoding_errors)
460
width = self._avail_width()
274
def _show_line(self, s):
275
# sys.stderr.write("progress %r\n" % s)
276
width = osutils.terminal_width()
461
277
if width is not None:
462
# GZ 2012-03-28: Counting bytes is wrong for calculating width of
463
# text but better than counting codepoints.
278
# we need one extra space for terminals that wrap on last char
464
280
s = '%-*.*s' % (width, width, s)
465
281
self._term_file.write('\r' + s + '\r')
522
334
t = t._parent_task
524
336
m = t.msg + ':' + m
527
339
def _render_line(self):
528
340
bar_string = self._render_bar()
529
341
if self._last_task:
530
task_part, counter_part = self._format_task(self._last_task)
342
task_msg = self._format_task(self._last_task)
532
task_part = counter_part = ''
533
345
if self._last_task and not self._last_task.show_transport_activity:
536
348
trans = self._last_transport_msg
537
# the bar separates the transport activity from the message, so even
538
# if there's no bar or spinner, we must show something if both those
540
if (task_part or trans) and not bar_string:
542
# preferentially truncate the task message if we don't have enough
544
avail_width = self._avail_width()
545
if avail_width is not None:
546
# if terminal avail_width is unknown, don't truncate
547
current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
548
gap = current_len - avail_width
550
task_part = task_part[:-gap-2] + '..'
551
s = trans + bar_string + task_part + counter_part
552
if avail_width is not None:
553
if len(s) < avail_width:
554
s = s.ljust(avail_width)
555
elif len(s) > avail_width:
351
return (bar_string + trans + task_msg)
559
353
def _repaint(self):
560
354
s = self._render_line()
613
407
elif now >= (self._transport_update_time + 0.5):
614
408
# guard against clock stepping backwards, and don't update too
616
rate = (self._bytes_since_update
617
/ (now - self._transport_update_time))
618
# using base-10 units (see HACKING.txt).
619
msg = ("%6dkB %5dkB/s " %
620
(self._total_byte_count / 1000, int(rate) / 1000,))
410
rate = self._bytes_since_update / (now - self._transport_update_time)
411
msg = ("%6dKB %5dKB/s" %
412
(self._total_byte_count>>10, int(rate)>>10,))
621
413
self._transport_update_time = now
622
414
self._last_repaint = now
623
415
self._bytes_since_update = 0
633
425
transfer_time = 0.001
634
426
bps = self._total_byte_count / transfer_time
636
# using base-10 units (see HACKING.txt).
637
msg = ('Transferred: %.0fkB'
638
' (%.1fkB/s r:%.0fkB w:%.0fkB'
639
% (self._total_byte_count / 1000.,
641
self._bytes_by_direction['read'] / 1000.,
642
self._bytes_by_direction['write'] / 1000.,
428
msg = ('Transferred: %.0fKiB'
429
' (%.1fK/s r:%.0fK w:%.0fK'
430
% (self._total_byte_count / 1024.,
432
self._bytes_by_direction['read'] / 1024.,
433
self._bytes_by_direction['write'] / 1024.,
644
435
if self._bytes_by_direction['unknown'] > 0:
645
msg += ' u:%.0fkB)' % (
646
self._bytes_by_direction['unknown'] / 1000.
436
msg += ' u:%.0fK)' % (
437
self._bytes_by_direction['unknown'] / 1024.