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,
46
165
class TextUIFactory(UIFactory):
47
"""A UI factory for Text user interefaces."""
166
"""A UI factory for Text user interfaces."""
49
168
def __init__(self,
61
180
# paints progress, network activity, etc
62
181
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()
64
204
def be_quiet(self, state):
65
205
if state and not self._quiet:
78
218
# to clear it. We might need to separately check for the case of
79
219
self._progress_view.clear()
81
def get_boolean(self, prompt):
83
self.prompt(prompt + "? [y/n]: ")
84
line = self.stdin.readline().lower()
85
if line in ('y\n', 'yes\n'):
87
elif line in ('n\n', 'no\n'):
89
elif line in ('', None):
90
# end-of-file; possibly should raise an error here instead
93
221
def get_integer(self, prompt):
95
223
self.prompt(prompt)
158
291
# do that. otherwise, guess based on $TERM and tty presence.
159
292
if self.is_quiet():
160
293
return NullProgressView()
161
elif os.environ.get('BZR_PROGRESS_BAR') == 'text':
162
return TextProgressView(self.stderr)
163
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
164
return NullProgressView()
165
elif progress._supports_progress(self.stderr):
166
return TextProgressView(self.stderr)
168
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()
170
303
def _make_output_stream_explicit(self, encoding, encoding_type):
171
304
if encoding_type == 'exact':
204
337
# See <https://launchpad.net/bugs/365891>
205
338
prompt = prompt % kwargs
206
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
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')
207
346
self.clear_term()
208
348
self.stderr.write(prompt)
210
350
def report_transport_activity(self, transport, byte_count, direction):
282
422
this only prints the stack from the nominated current task up to the root.
285
def __init__(self, term_file):
425
def __init__(self, term_file, encoding=None, errors="replace"):
286
426
self._term_file = term_file
428
self._encoding = getattr(term_file, "encoding", None) or "ascii"
430
self._encoding = encoding
431
self._encoding_errors = errors
287
432
# true when there's output on the screen we may need to clear
288
433
self._have_output = False
289
434
self._last_transport_msg = ''