1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
This tells the library how to display things to the user. Through this
20
layer different applications can choose the style of UI.
22
At the moment this layer is almost trivial: the application can just
23
choose the style of progress bar.
25
Set the ui_factory member to define the behaviour. The default
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
46
_valid_boolean_strings = dict(yes=True, no=False,
49
true=True, false=False)
50
_valid_boolean_strings['1'] = True
51
_valid_boolean_strings['0'] = False
54
def bool_from_string(s, accepted_values=None):
55
"""Returns a boolean if the string can be interpreted as such.
57
Interpret case insensitive strings as booleans. The default values
58
includes: 'yes', 'no, 'y', 'n', 'true', 'false', '0', '1', 'on',
59
'off'. Alternative values can be provided with the 'accepted_values'
62
:param s: A string that should be interpreted as a boolean. It should be of
63
type string or unicode.
65
:param accepted_values: An optional dict with accepted strings as keys and
66
True/False as values. The strings will be tested against a lowered
69
:return: True or False for accepted strings, None otherwise.
71
if accepted_values is None:
72
accepted_values = _valid_boolean_strings
74
if type(s) in (str, unicode):
76
val = accepted_values[s.lower()]
82
class UIFactory(object):
85
This tells the library how to display things to the user. Through this
86
layer different applications can choose the style of UI.
92
def get_password(self, prompt='', **kwargs):
93
"""Prompt the user for a password.
95
:param prompt: The prompt to present the user
96
:param kwargs: Arguments which will be expanded into the prompt.
97
This lets front ends display different things if
100
:return: The password string, return None if the user canceled the
101
request. Note that we do not touch the encoding, users may
102
have whatever they see fit and the password should be
105
raise NotImplementedError(self.get_password)
107
def nested_progress_bar(self):
108
"""Return a nested progress bar.
110
When the bar has been finished with, it should be released by calling
114
t = progress.ProgressTask(self._task_stack[-1], self)
116
t = progress.ProgressTask(None, self)
117
self._task_stack.append(t)
120
def _progress_finished(self, task):
121
"""Called by the ProgressTask when it finishes"""
122
if not self._task_stack:
123
warnings.warn("%r finished but nothing is active"
125
elif task != self._task_stack[-1]:
126
warnings.warn("%r is not the active task %r"
127
% (task, self._task_stack[-1]))
129
del self._task_stack[-1]
130
if not self._task_stack:
131
self._progress_all_finished()
133
def _progress_all_finished(self):
134
"""Called when the top-level progress task finished"""
137
def _progress_updated(self, task):
138
"""Called by the ProgressTask when it changes.
140
Should be specialized to draw the progress.
144
def clear_term(self):
145
"""Prepare the terminal for output.
147
This will, for example, clear text progress bars, and leave the
148
cursor at the leftmost position.
152
def get_boolean(self, prompt):
153
"""Get a boolean question answered from the user.
155
:param prompt: a message to prompt the user with. Should be a single
156
line without terminating \n.
157
:return: True or False for y/yes or n/no.
159
raise NotImplementedError(self.get_boolean)
161
def recommend_upgrade(self,
164
# this should perhaps be in the TextUIFactory and the default can do
166
trace.warning("%s is deprecated "
167
"and a better format is available.\n"
168
"It is recommended that you upgrade by "
169
"running the command\n"
174
def report_transport_activity(self, transport, byte_count, direction):
175
"""Called by transports as they do IO.
177
This may update a progress bar, spinner, or similar display.
178
By default it does nothing.
184
class CLIUIFactory(UIFactory):
185
"""Common behaviour for command line UI factories.
187
This is suitable for dumb terminals that can't repaint existing text."""
189
def __init__(self, stdin=None, stdout=None, stderr=None):
190
UIFactory.__init__(self)
191
self.stdin = stdin or sys.stdin
192
self.stdout = stdout or sys.stdout
193
self.stderr = stderr or sys.stderr
195
_accepted_boolean_strings = dict(y=True, n=False, yes=True, no=False)
197
def get_boolean(self, prompt):
199
self.prompt(prompt + "? [y/n]: ")
200
line = self.stdin.readline()
201
line = line.rstrip('\n')
202
val = bool_from_string(line, self._accepted_boolean_strings)
206
def get_non_echoed_password(self):
207
isatty = getattr(self.stdin, 'isatty', None)
208
if isatty is not None and isatty():
209
# getpass() ensure the password is not echoed and other
210
# cross-platform niceties
211
password = getpass.getpass('')
213
# echo doesn't make sense without a terminal
214
password = self.stdin.readline()
217
elif password[-1] == '\n':
218
password = password[:-1]
221
def get_password(self, prompt='', **kwargs):
222
"""Prompt the user for a password.
224
:param prompt: The prompt to present the user
225
:param kwargs: Arguments which will be expanded into the prompt.
226
This lets front ends display different things if
228
:return: The password string, return None if the user
229
canceled the request.
232
self.prompt(prompt, **kwargs)
233
# There's currently no way to say 'i decline to enter a password'
234
# as opposed to 'my password is empty' -- does it matter?
235
return self.get_non_echoed_password()
237
def get_username(self, prompt, **kwargs):
238
"""Prompt the user for a username.
240
:param prompt: The prompt to present the user
241
:param kwargs: Arguments which will be expanded into the prompt.
242
This lets front ends display different things if
244
:return: The username string, return None if the user
245
canceled the request.
248
self.prompt(prompt, **kwargs)
249
username = self.stdin.readline()
252
elif username[-1] == '\n':
253
username = username[:-1]
256
def prompt(self, prompt, **kwargs):
257
"""Emit prompt on the CLI.
259
:param kwargs: Dictionary of arguments to insert into the prompt,
260
to allow UIs to reformat the prompt.
263
# See <https://launchpad.net/bugs/365891>
264
prompt = prompt % kwargs
265
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
267
self.stderr.write(prompt)
270
"""Write an already-formatted message."""
271
self.stdout.write(msg + '\n')
274
class SilentUIFactory(CLIUIFactory):
275
"""A UI Factory which never prints anything.
277
This is the default UI, if another one is never registered.
281
CLIUIFactory.__init__(self)
283
def get_password(self, prompt='', **kwargs):
286
def get_username(self, prompt='', **kwargs):
289
def prompt(self, prompt, **kwargs):
296
def clear_decorator(func, *args, **kwargs):
297
"""Decorator that clears the term"""
298
ui_factory.clear_term()
299
func(*args, **kwargs)
302
ui_factory = SilentUIFactory()
303
"""IMPORTANT: never import this symbol directly. ONLY ever access it as
307
def make_ui_for_terminal(stdin, stdout, stderr):
308
"""Construct and return a suitable UIFactory for a text mode program.
310
If stdout is a smart terminal, this gets a smart UIFactory with
311
progress indicators, etc. If it's a dumb terminal, just plain text output.
314
isatty = getattr(stdin, 'isatty', None)
319
elif os.environ.get('TERM') in ('dumb', ''):
320
# e.g. emacs compile window
322
# User may know better, otherwise default to TextUIFactory
323
if ( os.environ.get('BZR_USE_TEXT_UI', None) is not None
325
from bzrlib.ui.text import TextUIFactory
327
return cls(stdin=stdin, stdout=stdout, stderr=stderr)