/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4634.124.7 by Martin Pool
Cross-format fetch should suggest upgrading repos, not branches
1
# Copyright (C) 2005-2010 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
16
4449.3.41 by Martin Pool
UI doc updates suggested by Robert
17
"""Abstraction for interacting with the user.
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
18
4449.3.41 by Martin Pool
UI doc updates suggested by Robert
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.
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
21
4449.3.6 by Martin Pool
Updated bzrlib.ui module docs
22
Several levels are supported, and you can also register new factories such as
23
for a GUI.
24
25
UIFactory
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
26
    Semi-abstract base class
4449.3.6 by Martin Pool
Updated bzrlib.ui module docs
27
28
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.
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
31
4449.3.41 by Martin Pool
UI doc updates suggested by Robert
32
CannedInputUIFactory
33
    For use in testing; the input values to be returned are provided 
34
    at construction.
35
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
36
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.
4449.3.41 by Martin Pool
UI doc updates suggested by Robert
40
    GUIs may choose to subclass this so that unimplemented methods fall
41
    back to working through the terminal.
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
42
"""
43
4449.3.16 by Martin Pool
Commentary on UIs
44
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
45
import os
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
46
import sys
3882.8.12 by Martin Pool
Give a warning, not an error, if a progress bar is not finished in order
47
import warnings
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
48
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
49
from bzrlib.lazy_import import lazy_import
50
lazy_import(globals(), """
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
51
import getpass
52
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
53
from bzrlib import (
3260.2.1 by Alexander Belchenko
Don't ask a password if there is no real terminal. (#69851)
54
    errors,
2461.1.2 by Vincent Ladeuil
Take jam's remark into account.
55
    osutils,
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
56
    progress,
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
57
    trace,
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
58
    )
59
""")
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
60
from bzrlib.symbol_versioning import (
61
    deprecated_function,
62
    deprecated_in,
63
    deprecated_method,
64
    )
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
65
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
66
4503.2.1 by Vincent Ladeuil
Get a bool from a string.
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
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
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.
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
108
4634.144.11 by Martin Pool
Rename squelched to suppressed
109
    :ivar suppressed_warnings: Identifiers for user warnings that should 
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
110
        no be emitted.
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
111
    """
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
112
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
113
    _user_warning_templates = dict(
114
        cross_format_fetch=("Doing on-the-fly conversion from "
115
            "%(from_format)s to %(to_format)s.\n"
116
            "This may take some time. Upgrade the repositories to the "
117
            "same format for better performance."
118
            )
119
        )
120
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
121
    def __init__(self):
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
122
        self._task_stack = []
4634.144.11 by Martin Pool
Rename squelched to suppressed
123
        self.suppressed_warnings = set()
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
124
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
125
    def get_password(self, prompt='', **kwargs):
126
        """Prompt the user for a password.
127
128
        :param prompt: The prompt to present the user
129
        :param kwargs: Arguments which will be expanded into the prompt.
130
                       This lets front ends display different things if
131
                       they so choose.
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
132
133
        :return: The password string, return None if the user canceled the
134
                 request. Note that we do not touch the encoding, users may
135
                 have whatever they see fit and the password should be
136
                 transported as is.
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
137
        """
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
138
        raise NotImplementedError(self.get_password)
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
139
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
140
    def nested_progress_bar(self):
141
        """Return a nested progress bar.
142
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
143
        When the bar has been finished with, it should be released by calling
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
144
        bar.finished().
145
        """
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
146
        if self._task_stack:
3882.8.3 by Martin Pool
Move display of transport throughput into TextProgressView
147
            t = progress.ProgressTask(self._task_stack[-1], self)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
148
        else:
3882.8.3 by Martin Pool
Move display of transport throughput into TextProgressView
149
            t = progress.ProgressTask(None, self)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
150
        self._task_stack.append(t)
151
        return t
152
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
153
    def _progress_finished(self, task):
154
        """Called by the ProgressTask when it finishes"""
155
        if not self._task_stack:
156
            warnings.warn("%r finished but nothing is active"
157
                % (task,))
158
        elif task != self._task_stack[-1]:
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
159
            warnings.warn("%r is not the active task %r"
3948.2.2 by Martin Pool
Corrections to finishing progress bars
160
                % (task, self._task_stack[-1]))
3882.8.12 by Martin Pool
Give a warning, not an error, if a progress bar is not finished in order
161
        else:
162
            del self._task_stack[-1]
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
163
        if not self._task_stack:
3948.2.5 by Martin Pool
rename to _progress_all_finished
164
            self._progress_all_finished()
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
165
3948.2.5 by Martin Pool
rename to _progress_all_finished
166
    def _progress_all_finished(self):
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
167
        """Called when the top-level progress task finished"""
168
        pass
169
170
    def _progress_updated(self, task):
171
        """Called by the ProgressTask when it changes.
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
172
3948.2.7 by Martin Pool
pep8
173
        Should be specialized to draw the progress.
174
        """
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
175
        pass
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
176
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
177
    def clear_term(self):
178
        """Prepare the terminal for output.
179
180
        This will, for example, clear text progress bars, and leave the
3948.2.7 by Martin Pool
pep8
181
        cursor at the leftmost position.
182
        """
3948.2.2 by Martin Pool
Corrections to finishing progress bars
183
        pass
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
184
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
185
    def format_user_warning(self, warning_id, message_args):
186
        try:
187
            template = self._user_warning_templates[warning_id]
188
        except KeyError:
189
            fail = "failed to format warning %r, %r" % (warning_id, message_args)
190
            warnings.warn(fail)   # so tests will fail etc
191
            return fail
192
        try:
193
            return template % message_args
194
        except ValueError, e:
195
            fail = "failed to format warning %r, %r: %s" % (
196
                warning_id, message_args, e)
197
            warnings.warn(fail)   # so tests will fail etc
198
            return fail
199
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
200
    def get_boolean(self, prompt):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
201
        """Get a boolean question answered from the user.
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
202
203
        :param prompt: a message to prompt the user with. Should be a single
204
        line without terminating \n.
205
        :return: True or False for y/yes or n/no.
206
        """
207
        raise NotImplementedError(self.get_boolean)
208
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
209
    def make_progress_view(self):
210
        """Construct a new ProgressView object for this UI.
211
212
        Application code should normally not call this but instead
213
        nested_progress_bar().
214
        """
215
        return NullProgressView()
216
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
217
    def recommend_upgrade(self,
218
        current_format_name,
219
        basedir):
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
220
        # XXX: this should perhaps be in the TextUIFactory and the default can do
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
221
        # nothing
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
222
        #
223
        # XXX: Change to show_user_warning - that will accomplish the previous
224
        # xxx. -- mbp 2010-02-25
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
225
        trace.warning("%s is deprecated "
226
            "and a better format is available.\n"
227
            "It is recommended that you upgrade by "
228
            "running the command\n"
229
            "  bzr upgrade %s",
230
            current_format_name,
231
            basedir)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
232
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
233
    def report_transport_activity(self, transport, byte_count, direction):
234
        """Called by transports as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
235
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
236
        This may update a progress bar, spinner, or similar display.
237
        By default it does nothing.
238
        """
239
        pass
240
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
241
    def show_user_warning(self, warning_id, **message_args):
242
        """Show a warning to the user.
243
244
        This is specifically for things that are under the user's control (eg
245
        outdated formats), not for internal program warnings like deprecated
246
        APIs.
247
248
        This can be overridden by UIFactory subclasses to show it in some 
249
        appropriate way; the default UIFactory is noninteractive and does
250
        nothing.  format_user_warning maps it to a string, though other
251
        presentations can be used for particular UIs.
252
253
        :param warning_id: An identifier like 'cross_format_fetch' used to 
254
            check if the message is suppressed and to look up the string.
255
        :param message_args: Arguments to be interpolated into the message.
256
        """
257
        pass
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
258
4634.144.13 by Martin Pool
Restore UIFactory.warn_cross_format_fetch in case it's used by an API client
259
    def warn_cross_format_fetch(self, from_format, to_format):
260
        """Warn about a potentially slow cross-format transfer.
261
        
262
        This is deprecated in favor of show_user_warning, but retained for api
263
        compatibility in 2.0 and 2.1.
264
        """
265
        self.show_user_warning('cross_format_fetch', from_format=from_format,
266
            to_format=to_format)
267
2461.1.1 by Vincent Ladeuil
Fix 110204 by letting TestUIFactory encode password prompt.
268
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
269
class CLIUIFactory(UIFactory):
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
270
    """Deprecated in favor of TextUIFactory."""
271
4449.3.32 by Martin Pool
Deprecations will actually land in 1.18
272
    @deprecated_method(deprecated_in((1, 18, 0)))
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
273
    def __init__(self, stdin=None, stdout=None, stderr=None):
274
        UIFactory.__init__(self)
275
        self.stdin = stdin or sys.stdin
276
        self.stdout = stdout or sys.stdout
277
        self.stderr = stderr or sys.stderr
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
278
4503.2.5 by Vincent Ladeuil
ui.get_boolean can also use bool_from_string.
279
    _accepted_boolean_strings = dict(y=True, n=False, yes=True, no=False)
280
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
281
    def get_boolean(self, prompt):
282
        while True:
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
283
            self.prompt(prompt + "? [y/n]: ")
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
284
            line = self.stdin.readline()
4503.2.5 by Vincent Ladeuil
ui.get_boolean can also use bool_from_string.
285
            line = line.rstrip('\n')
286
            val = bool_from_string(line, self._accepted_boolean_strings)
287
            if val is not None:
288
                return val
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
289
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
290
    def get_non_echoed_password(self):
4237.2.2 by Vincent Ladeuil
Don't presume we have a tty.
291
        isatty = getattr(self.stdin, 'isatty', None)
292
        if isatty is not None and isatty():
293
            # getpass() ensure the password is not echoed and other
294
            # cross-platform niceties
295
            password = getpass.getpass('')
296
        else:
297
            # echo doesn't make sense without a terminal
298
            password = self.stdin.readline()
299
            if not password:
300
                password = None
301
            elif password[-1] == '\n':
302
                password = password[:-1]
303
        return password
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
304
305
    def get_password(self, prompt='', **kwargs):
306
        """Prompt the user for a password.
307
308
        :param prompt: The prompt to present the user
309
        :param kwargs: Arguments which will be expanded into the prompt.
310
                       This lets front ends display different things if
311
                       they so choose.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
312
        :return: The password string, return None if the user
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
313
                 canceled the request.
314
        """
315
        prompt += ': '
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
316
        self.prompt(prompt, **kwargs)
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
317
        # There's currently no way to say 'i decline to enter a password'
318
        # as opposed to 'my password is empty' -- does it matter?
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
319
        return self.get_non_echoed_password()
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
320
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
321
    def get_username(self, prompt, **kwargs):
4222.2.10 by Jelmer Vernooij
Fix docstring.
322
        """Prompt the user for a username.
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
323
324
        :param prompt: The prompt to present the user
325
        :param kwargs: Arguments which will be expanded into the prompt.
326
                       This lets front ends display different things if
327
                       they so choose.
4222.2.2 by Jelmer Vernooij
Review from vila: Deal with UTF8 strings in prompts, fix typo.
328
        :return: The username string, return None if the user
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
329
                 canceled the request.
330
        """
331
        prompt += ': '
4222.2.9 by Jelmer Vernooij
Merge bzr.dev, including Vincents NotATerminal patch.
332
        self.prompt(prompt, **kwargs)
4222.2.11 by Jelmer Vernooij
Review feedback from vila: cope with stdin.readline() returning None, fix consistency in tests.
333
        username = self.stdin.readline()
334
        if not username:
335
            username = None
336
        elif username[-1] == '\n':
337
            username = username[:-1]
338
        return username
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
339
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
340
    def prompt(self, prompt, **kwargs):
4300.3.2 by Martin Pool
Review tweak to comments
341
        """Emit prompt on the CLI.
342
        
343
        :param kwargs: Dictionary of arguments to insert into the prompt,
344
            to allow UIs to reformat the prompt.
345
        """
4300.3.1 by Martin Pool
Fix string expansion in TextUIFactory.prompt
346
        if kwargs:
4300.3.2 by Martin Pool
Review tweak to comments
347
            # See <https://launchpad.net/bugs/365891>
4300.3.1 by Martin Pool
Fix string expansion in TextUIFactory.prompt
348
            prompt = prompt % kwargs
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
349
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
350
        self.clear_term()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
351
        self.stderr.write(prompt)
3945.1.1 by Vincent Ladeuil
Restore a working UI implementation suitable for emacs shells.
352
353
    def note(self, msg):
354
        """Write an already-formatted message."""
355
        self.stdout.write(msg + '\n')
3882.7.10 by Martin Pool
CLIUIFactory implements (as stubs) progress methods
356
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
357
358
class SilentUIFactory(UIFactory):
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
359
    """A UI Factory which never prints anything.
360
4449.3.29 by Martin Pool
More test UI factories support get_username and get_password
361
    This is the default UI, if another one is never registered by a program
362
    using bzrlib, and it's also active for example inside 'bzr serve'.
363
364
    Methods that try to read from the user raise an error; methods that do
365
    output do nothing.
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
366
    """
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
367
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
368
    def __init__(self):
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
369
        UIFactory.__init__(self)
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
370
3882.8.4 by Martin Pool
All UI factories should support note()
371
    def note(self, msg):
372
        pass
373
4449.3.29 by Martin Pool
More test UI factories support get_username and get_password
374
    def get_username(self, prompt, **kwargs):
375
        return None
376
3882.8.2 by Martin Pool
ProgressTask holds a reference to the ui that displays it
377
4449.3.25 by Martin Pool
Move CannedInputUIFactory to bzrlib.ui for reuse
378
class CannedInputUIFactory(SilentUIFactory):
379
    """A silent UI that return canned input."""
380
381
    def __init__(self, responses):
382
        self.responses = responses
383
4449.3.45 by Martin Pool
Add CannedInputUIFactory.assert_all_input_consumed
384
    def __repr__(self):
385
        return "%s(%r)" % (self.__class__.__name__, self.responses)
386
4449.3.25 by Martin Pool
Move CannedInputUIFactory to bzrlib.ui for reuse
387
    def get_boolean(self, prompt):
4449.3.27 by Martin Pool
More test updates to use CannedInputUIFactory
388
        return self.responses.pop(0)
4449.3.25 by Martin Pool
Move CannedInputUIFactory to bzrlib.ui for reuse
389
4449.3.29 by Martin Pool
More test UI factories support get_username and get_password
390
    def get_password(self, prompt='', **kwargs):
391
        return self.responses.pop(0)
392
393
    def get_username(self, prompt, **kwargs):
394
        return self.responses.pop(0)
4449.3.45 by Martin Pool
Add CannedInputUIFactory.assert_all_input_consumed
395
    
396
    def assert_all_input_consumed(self):
397
        if self.responses:
398
            raise AssertionError("expected all input in %r to be consumed"
399
                % (self,))
4449.3.29 by Martin Pool
More test UI factories support get_username and get_password
400
4449.3.25 by Martin Pool
Move CannedInputUIFactory to bzrlib.ui for reuse
401
4449.3.32 by Martin Pool
Deprecations will actually land in 1.18
402
@deprecated_function(deprecated_in((1, 18, 0)))
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
403
def clear_decorator(func, *args, **kwargs):
404
    """Decorator that clears the term"""
405
    ui_factory.clear_term()
406
    func(*args, **kwargs)
407
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
408
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
409
ui_factory = SilentUIFactory()
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
410
# IMPORTANT: never import this symbol directly. ONLY ever access it as
411
# ui.ui_factory, so that you refer to the current value.
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
412
413
414
def make_ui_for_terminal(stdin, stdout, stderr):
415
    """Construct and return a suitable UIFactory for a text mode program.
416
    """
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
417
    # this is now always TextUIFactory, which in turn decides whether it
418
    # should display progress bars etc
419
    from bzrlib.ui.text import TextUIFactory
420
    return TextUIFactory(stdin, stdout, stderr)
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
421
422
423
class NullProgressView(object):
424
    """Soak up and ignore progress information."""
425
426
    def clear(self):
427
        pass
428
429
    def show_progress(self, task):
430
        pass
431
432
    def show_transport_activity(self, transport, direction, byte_count):
433
        pass