58
_valid_boolean_strings = dict(yes=True, no=False,
61
true=True, false=False)
62
_valid_boolean_strings['1'] = True
63
_valid_boolean_strings['0'] = False
66
def bool_from_string(s, accepted_values=None):
67
"""Returns a boolean if the string can be interpreted as such.
69
Interpret case insensitive strings as booleans. The default values
70
includes: 'yes', 'no, 'y', 'n', 'true', 'false', '0', '1', 'on',
71
'off'. Alternative values can be provided with the 'accepted_values'
74
:param s: A string that should be interpreted as a boolean. It should be of
75
type string or unicode.
77
:param accepted_values: An optional dict with accepted strings as keys and
78
True/False as values. The strings will be tested against a lowered
81
:return: True or False for accepted strings, None otherwise.
83
if accepted_values is None:
84
accepted_values = _valid_boolean_strings
86
if type(s) in (str, unicode):
88
val = accepted_values[s.lower()]
94
class ConfirmationUserInterfacePolicy(object):
95
"""Wrapper for a UIFactory that allows or denies all confirmed actions."""
97
def __init__(self, wrapped_ui, default_answer, specific_answers):
98
"""Generate a proxy UI that does no confirmations.
100
:param wrapped_ui: Underlying UIFactory.
101
:param default_answer: Bool for whether requests for
102
confirmation from the user should be noninteractively accepted or
104
:param specific_answers: Map from confirmation_id to bool answer.
106
self.wrapped_ui = wrapped_ui
107
self.default_answer = default_answer
108
self.specific_answers = specific_answers
110
def __getattr__(self, name):
111
return getattr(self.wrapped_ui, name)
114
return '%s(%r, %r, %r)' % (
115
self.__class__.__name__,
118
self.specific_answers)
120
def confirm_action(self, prompt, confirmation_id, prompt_kwargs):
121
if confirmation_id in self.specific_answers:
122
return self.specific_answers[confirmation_id]
123
elif self.default_answer is not None:
124
return self.default_answer
126
return self.wrapped_ui.confirm_action(
127
prompt, confirmation_id, prompt_kwargs)
130
44
class UIFactory(object):
131
45
"""UI abstraction.
133
47
This tells the library how to display things to the user. Through this
134
48
layer different applications can choose the style of UI.
136
UI Factories are also context managers, for some syntactic sugar some users
139
:ivar suppressed_warnings: Identifiers for user warnings that should
143
_user_warning_templates = dict(
144
cross_format_fetch=("Doing on-the-fly conversion from "
145
"%(from_format)s to %(to_format)s.\n"
146
"This may take some time. Upgrade the repositories to the "
147
"same format for better performance."
149
experimental_format_fetch=("Fetching into experimental format "
151
"This format may be unreliable or change in the future "
152
"without an upgrade path.\n"),
154
"The command 'bzr %(deprecated_name)s' "
155
"has been deprecated in bzr %(deprecated_in_version)s. "
156
"Please use 'bzr %(recommended_name)s' instead."),
157
recommend_upgrade=("%(current_format_name)s is deprecated "
158
"and a better format is available.\n"
159
"It is recommended that you upgrade by "
160
"running the command\n"
161
" bzr upgrade %(basedir)s"),
163
u"Stole dead lock %(lock_url)s %(other_holder_info)s."),
166
51
def __init__(self):
167
self._task_stack = []
168
self.suppressed_warnings = set()
172
"""Context manager entry support.
174
Override in a concrete factory class if initialisation before use is
177
return self # This is bound to the 'as' clause in a with statement.
179
def __exit__(self, exc_type, exc_val, exc_tb):
180
"""Context manager exit support.
182
Override in a concrete factory class if more cleanup than a simple
183
self.clear_term() is needed when the UIFactory is finished with.
186
return False # propogate exceptions.
188
def be_quiet(self, state):
189
"""Tell the UI to be more quiet, or not.
191
Typically this suppresses progress bars; the application may also look
192
at ui_factory.is_quiet().
196
def confirm_action(self, prompt, confirmation_id, prompt_kwargs):
197
"""Seek user confirmation for an action.
199
If the UI is noninteractive, or the user does not want to be asked
200
about this action, True is returned, indicating bzr should just
203
The confirmation id allows the user to configure certain actions to
204
always be confirmed or always denied, and for UIs to specialize the
205
display of particular confirmations.
207
:param prompt: Suggested text to display to the user.
208
:param prompt_kwargs: A dictionary of arguments that can be
209
string-interpolated into the prompt.
210
:param confirmation_id: Unique string identifier for the confirmation.
212
return self.get_boolean(prompt % prompt_kwargs)
214
def get_password(self, prompt=u'', **kwargs):
52
super(UIFactory, self).__init__()
53
self._progress_bar_stack = None
55
def get_password(self, prompt='', **kwargs):
215
56
"""Prompt the user for a password.
217
:param prompt: The prompt to present the user (must be unicode)
58
:param prompt: The prompt to present the user
218
59
:param kwargs: Arguments which will be expanded into the prompt.
219
60
This lets front ends display different things if
227
68
raise NotImplementedError(self.get_password)
232
def make_output_stream(self, encoding=None, encoding_type=None):
233
"""Get a stream for sending out bulk text data.
235
This is used for commands that produce bulk text, such as log or diff
236
output, as opposed to user interaction. This should work even for
237
non-interactive user interfaces. Typically this goes to a decorated
238
version of stdout, but in a GUI it might be appropriate to send it to a
239
window displaying the text.
241
:param encoding: Unicode encoding for output; if not specified
242
uses the configured 'output_encoding' if any; otherwise the
244
(See get_terminal_encoding.)
246
:param encoding_type: How to handle encoding errors:
247
replace/strict/escape/exact. Default is replace.
249
# XXX: is the caller supposed to close the resulting object?
251
encoding = config.GlobalStack().get('output_encoding')
253
encoding = osutils.get_terminal_encoding(trace=True)
254
if encoding_type is None:
255
encoding_type = 'replace'
256
out_stream = self._make_output_stream_explicit(encoding, encoding_type)
259
def _make_output_stream_explicit(self, encoding, encoding_type):
260
raise NotImplementedError("%s doesn't support make_output_stream"
261
% (self.__class__.__name__))
263
70
def nested_progress_bar(self):
264
71
"""Return a nested progress bar.
266
73
When the bar has been finished with, it should be released by calling
270
t = progress.ProgressTask(self._task_stack[-1], self)
272
t = progress.ProgressTask(None, self)
273
self._task_stack.append(t)
276
def _progress_finished(self, task):
277
"""Called by the ProgressTask when it finishes"""
278
if not self._task_stack:
279
warnings.warn("%r finished but nothing is active"
281
if task in self._task_stack:
282
self._task_stack.remove(task)
284
warnings.warn("%r is not in active stack %r"
285
% (task, self._task_stack))
286
if not self._task_stack:
287
self._progress_all_finished()
289
def _progress_all_finished(self):
290
"""Called when the top-level progress task finished"""
293
def _progress_updated(self, task):
294
"""Called by the ProgressTask when it changes.
296
Should be specialized to draw the progress.
76
raise NotImplementedError(self.nested_progress_bar)
300
78
def clear_term(self):
301
79
"""Prepare the terminal for output.
303
81
This will, for example, clear text progress bars, and leave the
304
cursor at the leftmost position.
308
def format_user_warning(self, warning_id, message_args):
310
template = self._user_warning_templates[warning_id]
312
fail = "bzr warning: %r, %r" % (warning_id, message_args)
313
warnings.warn("no template for warning: " + fail) # so tests will fail etc
316
return template % message_args
317
except ValueError, e:
318
fail = "bzr unprintable warning: %r, %r, %s" % (
319
warning_id, message_args, e)
320
warnings.warn(fail) # so tests will fail etc
82
cursor at the leftmost position."""
83
raise NotImplementedError(self.clear_term)
323
85
def get_boolean(self, prompt):
324
"""Get a boolean question answered from the user.
86
"""Get a boolean question answered from the user.
326
88
:param prompt: a message to prompt the user with. Should be a single
327
line without terminating \\n.
89
line without terminating \n.
328
90
:return: True or False for y/yes or n/no.
330
92
raise NotImplementedError(self.get_boolean)
332
def get_integer(self, prompt):
333
"""Get an integer from the user.
335
:param prompt: a message to prompt the user with. Could be a multi-line
336
prompt but without a terminating \\n.
338
:return: A signed integer.
340
raise NotImplementedError(self.get_integer)
342
def make_progress_view(self):
343
"""Construct a new ProgressView object for this UI.
345
Application code should normally not call this but instead
346
nested_progress_bar().
348
return NullProgressView()
350
def recommend_upgrade(self, current_format_name, basedir):
351
"""Recommend the user upgrade a control directory.
353
:param current_format_name: Description of the current format
354
:param basedir: Location of the control dir
356
self.show_user_warning('recommend_upgrade',
357
current_format_name=current_format_name, basedir=basedir)
359
def report_transport_activity(self, transport, byte_count, direction):
360
"""Called by transports as they do IO.
362
This may update a progress bar, spinner, or similar display.
363
By default it does nothing.
367
def log_transport_activity(self, display=False):
368
"""Write out whatever transport activity has been measured.
370
Implementations are allowed to do nothing, but it is useful if they can
371
write a line to the log file.
373
:param display: If False, only log to disk, if True also try to display
374
a message to the user.
377
# Default implementation just does nothing
380
def show_user_warning(self, warning_id, **message_args):
381
"""Show a warning to the user.
383
This is specifically for things that are under the user's control (eg
384
outdated formats), not for internal program warnings like deprecated
387
This can be overridden by UIFactory subclasses to show it in some
388
appropriate way; the default UIFactory is noninteractive and does
389
nothing. format_user_warning maps it to a string, though other
390
presentations can be used for particular UIs.
392
:param warning_id: An identifier like 'cross_format_fetch' used to
393
check if the message is suppressed and to look up the string.
394
:param message_args: Arguments to be interpolated into the message.
398
def show_error(self, msg):
399
"""Show an error message (not an exception) to the user.
401
The message should not have an error prefix or trailing newline. That
402
will be added by the factory if appropriate.
404
raise NotImplementedError(self.show_error)
406
def show_message(self, msg):
407
"""Show a message to the user."""
408
raise NotImplementedError(self.show_message)
410
def show_warning(self, msg):
411
"""Show a warning to the user."""
412
raise NotImplementedError(self.show_warning)
415
class NoninteractiveUIFactory(UIFactory):
416
"""Base class for UIs with no user."""
418
def confirm_action(self, prompt, confirmation_id, prompt_kwargs):
422
return '%s()' % (self.__class__.__name__, )
425
class SilentUIFactory(NoninteractiveUIFactory):
94
def recommend_upgrade(self,
97
# this should perhaps be in the TextUIFactory and the default can do
99
trace.warning("%s is deprecated "
100
"and a better format is available.\n"
101
"It is recommended that you upgrade by "
102
"running the command\n"
108
class CLIUIFactory(UIFactory):
109
"""Common behaviour for command line UI factories."""
112
super(CLIUIFactory, self).__init__()
113
self.stdin = sys.stdin
115
def get_boolean(self, prompt):
117
# FIXME: make a regexp and handle case variations as well.
119
self.prompt(prompt + "? [y/n]: ")
120
line = self.stdin.readline()
121
if line in ('y\n', 'yes\n'):
123
if line in ('n\n', 'no\n'):
126
def get_non_echoed_password(self, prompt):
127
if not sys.stdin.isatty():
128
raise errors.NotATerminal()
129
encoding = osutils.get_terminal_encoding()
130
return getpass.getpass(prompt.encode(encoding, 'replace'))
132
def get_password(self, prompt='', **kwargs):
133
"""Prompt the user for a password.
135
:param prompt: The prompt to present the user
136
:param kwargs: Arguments which will be expanded into the prompt.
137
This lets front ends display different things if
139
:return: The password string, return None if the user
140
canceled the request.
143
prompt = (prompt % kwargs)
144
# There's currently no way to say 'i decline to enter a password'
145
# as opposed to 'my password is empty' -- does it matter?
146
return self.get_non_echoed_password(prompt)
148
def prompt(self, prompt):
149
"""Emit prompt on the CLI."""
152
class SilentUIFactory(CLIUIFactory):
426
153
"""A UI Factory which never prints anything.
428
This is the default UI, if another one is never registered by a program
429
using bzrlib, and it's also active for example inside 'bzr serve'.
431
Methods that try to read from the user raise an error; methods that do
155
This is the default UI, if another one is never registered.
436
UIFactory.__init__(self)
441
def get_username(self, prompt, **kwargs):
158
def get_password(self, prompt='', **kwargs):
444
def _make_output_stream_explicit(self, encoding, encoding_type):
445
return NullOutputStream(encoding)
447
def show_error(self, msg):
450
def show_message(self, msg):
453
def show_warning(self, msg):
457
class CannedInputUIFactory(SilentUIFactory):
458
"""A silent UI that return canned input."""
460
def __init__(self, responses):
461
self.responses = responses
464
return "%s(%r)" % (self.__class__.__name__, self.responses)
466
def confirm_action(self, prompt, confirmation_id, args):
467
return self.get_boolean(prompt % args)
469
def get_boolean(self, prompt):
470
return self.responses.pop(0)
472
def get_integer(self, prompt):
473
return self.responses.pop(0)
475
def get_password(self, prompt=u'', **kwargs):
476
return self.responses.pop(0)
478
def get_username(self, prompt, **kwargs):
479
return self.responses.pop(0)
481
def assert_all_input_consumed(self):
483
raise AssertionError("expected all input in %r to be consumed"
161
def nested_progress_bar(self):
162
if self._progress_bar_stack is None:
163
self._progress_bar_stack = progress.ProgressBarStack(
164
klass=progress.DummyProgress)
165
return self._progress_bar_stack.get_nested()
167
def clear_term(self):
170
def recommend_upgrade(self, *args):
174
def clear_decorator(func, *args, **kwargs):
175
"""Decorator that clears the term"""
176
ui_factory.clear_term()
177
func(*args, **kwargs)
487
180
ui_factory = SilentUIFactory()
488
# IMPORTANT: never import this symbol directly. ONLY ever access it as
489
# ui.ui_factory, so that you refer to the current value.
492
def make_ui_for_terminal(stdin, stdout, stderr):
493
"""Construct and return a suitable UIFactory for a text mode program.
495
# this is now always TextUIFactory, which in turn decides whether it
496
# should display progress bars etc
497
from bzrlib.ui.text import TextUIFactory
498
return TextUIFactory(stdin, stdout, stderr)
501
class NullProgressView(object):
502
"""Soak up and ignore progress information."""
507
def show_progress(self, task):
510
def show_transport_activity(self, transport, direction, byte_count):
513
def log_transport_activity(self, display=False):
517
class NullOutputStream(object):
518
"""Acts like a file, but discard all output."""
520
def __init__(self, encoding):
521
self.encoding = encoding
523
def write(self, data):
526
def writelines(self, data):
181
"""IMPORTANT: never import this symbol directly. ONLY ever access it as