/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/ui/__init__.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-10-14 08:51:44 UTC
  • mfrom: (4711.1.8 ui-factory)
  • Revision ID: pqm@pqm.ubuntu.com-20091014085144-t3bcnsw7rvm7b6ge
(mbp) Add UIFactory.show_error, show_message, show_warning;
        and improve tests and docstring.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Abstraction for interacting with the user.
 
18
 
 
19
Applications can choose different types of UI, and they deal with displaying
 
20
messages or progress to the user, and with gathering different types of input.
 
21
 
 
22
Several levels are supported, and you can also register new factories such as
 
23
for a GUI.
 
24
 
 
25
bzrlib.ui.UIFactory
 
26
    Semi-abstract base class
 
27
 
 
28
bzrlib.ui.SilentUIFactory
 
29
    Produces no output and cannot take any input; useful for programs using
 
30
    bzrlib in batch mode or for programs such as loggerhead.
 
31
 
 
32
bzrlib.ui.CannedInputUIFactory
 
33
    For use in testing; the input values to be returned are provided 
 
34
    at construction.
 
35
 
 
36
bzrlib.ui.text.TextUIFactory
 
37
    Standard text command-line interface, with stdin, stdout, stderr.
 
38
    May make more or less advanced use of them, eg in drawing progress bars,
 
39
    depending on the detected capabilities of the terminal.
 
40
    GUIs may choose to subclass this so that unimplemented methods fall
 
41
    back to working through the terminal.
 
42
"""
 
43
 
 
44
 
 
45
import os
 
46
import sys
 
47
import warnings
 
48
 
 
49
from bzrlib.lazy_import import lazy_import
 
50
lazy_import(globals(), """
 
51
import getpass
 
52
 
 
53
from bzrlib import (
 
54
    errors,
 
55
    osutils,
 
56
    progress,
 
57
    trace,
 
58
    )
 
59
""")
 
60
from bzrlib.symbol_versioning import (
 
61
    deprecated_function,
 
62
    deprecated_in,
 
63
    deprecated_method,
 
64
    )
 
65
 
 
66
 
 
67
_valid_boolean_strings = dict(yes=True, no=False,
 
68
                              y=True, n=False,
 
69
                              on=True, off=False,
 
70
                              true=True, false=False)
 
71
_valid_boolean_strings['1'] = True
 
72
_valid_boolean_strings['0'] = False
 
73
 
 
74
 
 
75
def bool_from_string(s, accepted_values=None):
 
76
    """Returns a boolean if the string can be interpreted as such.
 
77
 
 
78
    Interpret case insensitive strings as booleans. The default values
 
79
    includes: 'yes', 'no, 'y', 'n', 'true', 'false', '0', '1', 'on',
 
80
    'off'. Alternative values can be provided with the 'accepted_values'
 
81
    parameter.
 
82
 
 
83
    :param s: A string that should be interpreted as a boolean. It should be of
 
84
        type string or unicode.
 
85
 
 
86
    :param accepted_values: An optional dict with accepted strings as keys and
 
87
        True/False as values. The strings will be tested against a lowered
 
88
        version of 's'.
 
89
 
 
90
    :return: True or False for accepted strings, None otherwise.
 
91
    """
 
92
    if accepted_values is None:
 
93
        accepted_values = _valid_boolean_strings
 
94
    val = None
 
95
    if type(s) in (str, unicode):
 
96
        try:
 
97
            val = accepted_values[s.lower()]
 
98
        except KeyError:
 
99
            pass
 
100
    return val
 
101
 
 
102
 
 
103
class UIFactory(object):
 
104
    """UI abstraction.
 
105
 
 
106
    This tells the library how to display things to the user.  Through this
 
107
    layer different applications can choose the style of UI.
 
108
    """
 
109
 
 
110
    def __init__(self):
 
111
        self._task_stack = []
 
112
 
 
113
    def get_password(self, prompt='', **kwargs):
 
114
        """Prompt the user for a password.
 
115
 
 
116
        :param prompt: The prompt to present the user
 
117
        :param kwargs: Arguments which will be expanded into the prompt.
 
118
                       This lets front ends display different things if
 
119
                       they so choose.
 
120
 
 
121
        :return: The password string, return None if the user canceled the
 
122
                 request. Note that we do not touch the encoding, users may
 
123
                 have whatever they see fit and the password should be
 
124
                 transported as is.
 
125
        """
 
126
        raise NotImplementedError(self.get_password)
 
127
 
 
128
    def nested_progress_bar(self):
 
129
        """Return a nested progress bar.
 
130
 
 
131
        When the bar has been finished with, it should be released by calling
 
132
        bar.finished().
 
133
        """
 
134
        if self._task_stack:
 
135
            t = progress.ProgressTask(self._task_stack[-1], self)
 
136
        else:
 
137
            t = progress.ProgressTask(None, self)
 
138
        self._task_stack.append(t)
 
139
        return t
 
140
 
 
141
    def _progress_finished(self, task):
 
142
        """Called by the ProgressTask when it finishes"""
 
143
        if not self._task_stack:
 
144
            warnings.warn("%r finished but nothing is active"
 
145
                % (task,))
 
146
        elif task != self._task_stack[-1]:
 
147
            warnings.warn("%r is not the active task %r"
 
148
                % (task, self._task_stack[-1]))
 
149
        else:
 
150
            del self._task_stack[-1]
 
151
        if not self._task_stack:
 
152
            self._progress_all_finished()
 
153
 
 
154
    def _progress_all_finished(self):
 
155
        """Called when the top-level progress task finished"""
 
156
        pass
 
157
 
 
158
    def _progress_updated(self, task):
 
159
        """Called by the ProgressTask when it changes.
 
160
 
 
161
        Should be specialized to draw the progress.
 
162
        """
 
163
        pass
 
164
 
 
165
    def clear_term(self):
 
166
        """Prepare the terminal for output.
 
167
 
 
168
        This will, for example, clear text progress bars, and leave the
 
169
        cursor at the leftmost position.
 
170
        """
 
171
        pass
 
172
 
 
173
    def get_boolean(self, prompt):
 
174
        """Get a boolean question answered from the user.
 
175
 
 
176
        :param prompt: a message to prompt the user with. Should be a single
 
177
        line without terminating \n.
 
178
        :return: True or False for y/yes or n/no.
 
179
        """
 
180
        raise NotImplementedError(self.get_boolean)
 
181
 
 
182
    def make_progress_view(self):
 
183
        """Construct a new ProgressView object for this UI.
 
184
 
 
185
        Application code should normally not call this but instead
 
186
        nested_progress_bar().
 
187
        """
 
188
        return NullProgressView()
 
189
 
 
190
    def recommend_upgrade(self,
 
191
        current_format_name,
 
192
        basedir):
 
193
        # this should perhaps be in the TextUIFactory and the default can do
 
194
        # nothing
 
195
        trace.warning("%s is deprecated "
 
196
            "and a better format is available.\n"
 
197
            "It is recommended that you upgrade by "
 
198
            "running the command\n"
 
199
            "  bzr upgrade %s",
 
200
            current_format_name,
 
201
            basedir)
 
202
 
 
203
    def report_transport_activity(self, transport, byte_count, direction):
 
204
        """Called by transports as they do IO.
 
205
 
 
206
        This may update a progress bar, spinner, or similar display.
 
207
        By default it does nothing.
 
208
        """
 
209
        pass
 
210
 
 
211
    def show_error(self, msg):
 
212
        """Show an error message (not an exception) to the user.
 
213
        
 
214
        The message should not have an error prefix or trailing newline.  That
 
215
        will be added by the factory if appropriate. 
 
216
        """
 
217
        raise NotImplementedError(self.show_error)
 
218
 
 
219
    def show_message(self, msg):
 
220
        """Show a message to the user."""
 
221
        raise NotImplementedError(self.show_message)
 
222
 
 
223
    def show_warning(self, msg):
 
224
        """Show a warning to the user."""
 
225
        raise NotImplementedError(self.show_warning)
 
226
 
 
227
 
 
228
 
 
229
class CLIUIFactory(UIFactory):
 
230
    """Deprecated in favor of TextUIFactory."""
 
231
 
 
232
    @deprecated_method(deprecated_in((1, 18, 0)))
 
233
    def __init__(self, stdin=None, stdout=None, stderr=None):
 
234
        UIFactory.__init__(self)
 
235
        self.stdin = stdin or sys.stdin
 
236
        self.stdout = stdout or sys.stdout
 
237
        self.stderr = stderr or sys.stderr
 
238
 
 
239
    _accepted_boolean_strings = dict(y=True, n=False, yes=True, no=False)
 
240
 
 
241
    def get_boolean(self, prompt):
 
242
        while True:
 
243
            self.prompt(prompt + "? [y/n]: ")
 
244
            line = self.stdin.readline()
 
245
            line = line.rstrip('\n')
 
246
            val = bool_from_string(line, self._accepted_boolean_strings)
 
247
            if val is not None:
 
248
                return val
 
249
 
 
250
    def get_non_echoed_password(self):
 
251
        isatty = getattr(self.stdin, 'isatty', None)
 
252
        if isatty is not None and isatty():
 
253
            # getpass() ensure the password is not echoed and other
 
254
            # cross-platform niceties
 
255
            password = getpass.getpass('')
 
256
        else:
 
257
            # echo doesn't make sense without a terminal
 
258
            password = self.stdin.readline()
 
259
            if not password:
 
260
                password = None
 
261
            elif password[-1] == '\n':
 
262
                password = password[:-1]
 
263
        return password
 
264
 
 
265
    def get_password(self, prompt='', **kwargs):
 
266
        """Prompt the user for a password.
 
267
 
 
268
        :param prompt: The prompt to present the user
 
269
        :param kwargs: Arguments which will be expanded into the prompt.
 
270
                       This lets front ends display different things if
 
271
                       they so choose.
 
272
        :return: The password string, return None if the user
 
273
                 canceled the request.
 
274
        """
 
275
        prompt += ': '
 
276
        self.prompt(prompt, **kwargs)
 
277
        # There's currently no way to say 'i decline to enter a password'
 
278
        # as opposed to 'my password is empty' -- does it matter?
 
279
        return self.get_non_echoed_password()
 
280
 
 
281
    def get_username(self, prompt, **kwargs):
 
282
        """Prompt the user for a username.
 
283
 
 
284
        :param prompt: The prompt to present the user
 
285
        :param kwargs: Arguments which will be expanded into the prompt.
 
286
                       This lets front ends display different things if
 
287
                       they so choose.
 
288
        :return: The username string, return None if the user
 
289
                 canceled the request.
 
290
        """
 
291
        prompt += ': '
 
292
        self.prompt(prompt, **kwargs)
 
293
        username = self.stdin.readline()
 
294
        if not username:
 
295
            username = None
 
296
        elif username[-1] == '\n':
 
297
            username = username[:-1]
 
298
        return username
 
299
 
 
300
    def prompt(self, prompt, **kwargs):
 
301
        """Emit prompt on the CLI.
 
302
        
 
303
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
304
            to allow UIs to reformat the prompt.
 
305
        """
 
306
        if kwargs:
 
307
            # See <https://launchpad.net/bugs/365891>
 
308
            prompt = prompt % kwargs
 
309
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
310
        self.clear_term()
 
311
        self.stderr.write(prompt)
 
312
 
 
313
    def note(self, msg):
 
314
        """Write an already-formatted message."""
 
315
        self.stdout.write(msg + '\n')
 
316
 
 
317
 
 
318
class SilentUIFactory(UIFactory):
 
319
    """A UI Factory which never prints anything.
 
320
 
 
321
    This is the default UI, if another one is never registered by a program
 
322
    using bzrlib, and it's also active for example inside 'bzr serve'.
 
323
 
 
324
    Methods that try to read from the user raise an error; methods that do
 
325
    output do nothing.
 
326
    """
 
327
 
 
328
    def __init__(self):
 
329
        UIFactory.__init__(self)
 
330
 
 
331
    def note(self, msg):
 
332
        pass
 
333
 
 
334
    def get_username(self, prompt, **kwargs):
 
335
        return None
 
336
 
 
337
    def show_error(self, msg):
 
338
        pass
 
339
 
 
340
    def show_message(self, msg):
 
341
        pass
 
342
 
 
343
    def show_warning(self, msg):
 
344
        pass
 
345
 
 
346
 
 
347
class CannedInputUIFactory(SilentUIFactory):
 
348
    """A silent UI that return canned input."""
 
349
 
 
350
    def __init__(self, responses):
 
351
        self.responses = responses
 
352
 
 
353
    def __repr__(self):
 
354
        return "%s(%r)" % (self.__class__.__name__, self.responses)
 
355
 
 
356
    def get_boolean(self, prompt):
 
357
        return self.responses.pop(0)
 
358
 
 
359
    def get_password(self, prompt='', **kwargs):
 
360
        return self.responses.pop(0)
 
361
 
 
362
    def get_username(self, prompt, **kwargs):
 
363
        return self.responses.pop(0)
 
364
    
 
365
    def assert_all_input_consumed(self):
 
366
        if self.responses:
 
367
            raise AssertionError("expected all input in %r to be consumed"
 
368
                % (self,))
 
369
 
 
370
 
 
371
@deprecated_function(deprecated_in((1, 18, 0)))
 
372
def clear_decorator(func, *args, **kwargs):
 
373
    """Decorator that clears the term"""
 
374
    ui_factory.clear_term()
 
375
    func(*args, **kwargs)
 
376
 
 
377
 
 
378
ui_factory = SilentUIFactory()
 
379
# IMPORTANT: never import this symbol directly. ONLY ever access it as
 
380
# ui.ui_factory, so that you refer to the current value.
 
381
 
 
382
 
 
383
def make_ui_for_terminal(stdin, stdout, stderr):
 
384
    """Construct and return a suitable UIFactory for a text mode program.
 
385
    """
 
386
    # this is now always TextUIFactory, which in turn decides whether it
 
387
    # should display progress bars etc
 
388
    from bzrlib.ui.text import TextUIFactory
 
389
    return TextUIFactory(stdin, stdout, stderr)
 
390
 
 
391
 
 
392
class NullProgressView(object):
 
393
    """Soak up and ignore progress information."""
 
394
 
 
395
    def clear(self):
 
396
        pass
 
397
 
 
398
    def show_progress(self, task):
 
399
        pass
 
400
 
 
401
    def show_transport_activity(self, transport, direction, byte_count):
 
402
        pass