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
46
class UIFactory(object):
131
47
"""UI abstraction.
133
49
This tells the library how to display things to the user. Through this
134
50
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
53
def __init__(self):
167
54
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):
56
def get_password(self, prompt='', **kwargs):
215
57
"""Prompt the user for a password.
217
:param prompt: The prompt to present the user (must be unicode)
59
:param prompt: The prompt to present the user
218
60
:param kwargs: Arguments which will be expanded into the prompt.
219
61
This lets front ends display different things if
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
323
116
def get_boolean(self, prompt):
324
117
"""Get a boolean question answered from the user.
326
119
:param prompt: a message to prompt the user with. Should be a single
327
line without terminating \\n.
120
line without terminating \n.
328
121
:return: True or False for y/yes or n/no.
330
123
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)
125
def recommend_upgrade(self,
128
# this should perhaps be in the TextUIFactory and the default can do
130
trace.warning("%s is deprecated "
131
"and a better format is available.\n"
132
"It is recommended that you upgrade by "
133
"running the command\n"
359
138
def report_transport_activity(self, transport, byte_count, direction):
360
139
"""Called by transports as they do IO.
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.
148
class CLIUIFactory(UIFactory):
149
"""Common behaviour for command line UI factories.
151
This is suitable for dumb terminals that can't repaint existing text."""
153
def __init__(self, stdin=None, stdout=None, stderr=None):
154
UIFactory.__init__(self)
155
self.stdin = stdin or sys.stdin
156
self.stdout = stdout or sys.stdout
157
self.stderr = stderr or sys.stderr
159
def get_boolean(self, prompt):
161
self.prompt(prompt + "? [y/n]: ")
162
line = self.stdin.readline()
164
if line in ('y\n', 'yes\n'):
166
if line in ('n\n', 'no\n'):
169
def get_non_echoed_password(self):
170
isatty = getattr(self.stdin, 'isatty', None)
171
if isatty is not None and isatty():
172
# getpass() ensure the password is not echoed and other
173
# cross-platform niceties
174
password = getpass.getpass('')
176
# echo doesn't make sense without a terminal
177
password = self.stdin.readline()
180
elif password[-1] == '\n':
181
password = password[:-1]
184
def get_password(self, prompt='', **kwargs):
185
"""Prompt the user for a password.
187
:param prompt: The prompt to present the user
188
:param kwargs: Arguments which will be expanded into the prompt.
189
This lets front ends display different things if
191
:return: The password string, return None if the user
192
canceled the request.
195
self.prompt(prompt, **kwargs)
196
# There's currently no way to say 'i decline to enter a password'
197
# as opposed to 'my password is empty' -- does it matter?
198
return self.get_non_echoed_password()
200
def get_username(self, prompt, **kwargs):
201
"""Prompt the user for a username.
203
:param prompt: The prompt to present the user
204
:param kwargs: Arguments which will be expanded into the prompt.
205
This lets front ends display different things if
207
:return: The username string, return None if the user
208
canceled the request.
211
self.prompt(prompt, **kwargs)
212
username = self.stdin.readline()
215
elif username[-1] == '\n':
216
username = username[:-1]
219
def prompt(self, prompt, **kwargs):
220
"""Emit prompt on the CLI.
401
The message should not have an error prefix or trailing newline. That
402
will be added by the factory if appropriate.
222
:param kwargs: Dictionary of arguments to insert into the prompt,
223
to allow UIs to reformat the prompt.
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):
226
# See <https://launchpad.net/bugs/365891>
227
prompt = prompt % kwargs
228
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
230
self.stderr.write(prompt)
233
"""Write an already-formatted message."""
234
self.stdout.write(msg + '\n')
237
class SilentUIFactory(CLIUIFactory):
426
238
"""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
240
This is the default UI, if another one is never registered.
435
243
def __init__(self):
436
UIFactory.__init__(self)
244
CLIUIFactory.__init__(self)
246
def get_password(self, prompt='', **kwargs):
249
def get_username(self, prompt='', **kwargs):
252
def prompt(self, prompt, **kwargs):
438
255
def note(self, msg):
441
def get_username(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"
259
def clear_decorator(func, *args, **kwargs):
260
"""Decorator that clears the term"""
261
ui_factory.clear_term()
262
func(*args, **kwargs)
487
265
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.
266
"""IMPORTANT: never import this symbol directly. ONLY ever access it as
492
270
def make_ui_for_terminal(stdin, stdout, stderr):
493
271
"""Construct and return a suitable UIFactory for a text mode program.
273
If stdout is a smart terminal, this gets a smart UIFactory with
274
progress indicators, etc. If it's a dumb terminal, just plain text output.
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):
277
isatty = getattr(stdin, 'isatty', None)
282
elif os.environ.get('TERM') in ('dumb', ''):
283
# e.g. emacs compile window
285
# User may know better, otherwise default to TextUIFactory
286
if ( os.environ.get('BZR_USE_TEXT_UI', None) is not None
288
from bzrlib.ui.text import TextUIFactory
290
return cls(stdin=stdin, stdout=stdout, stderr=stderr)