/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3948.2.2 by Martin Pool
Corrections to finishing progress bars
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
17
"""UI abstraction.
18
19
This tells the library how to display things to the user.  Through this
20
layer different applications can choose the style of UI.
21
22
At the moment this layer is almost trivial: the application can just
23
choose the style of progress bar.
24
25
Set the ui_factory member to define the behaviour.  The default
26
displays no output.
27
"""
28
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
29
import os
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
30
import sys
3882.8.12 by Martin Pool
Give a warning, not an error, if a progress bar is not finished in order
31
import warnings
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
32
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
35
import getpass
36
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
37
from bzrlib import (
3260.2.1 by Alexander Belchenko
Don't ask a password if there is no real terminal. (#69851)
38
    errors,
2461.1.2 by Vincent Ladeuil
Take jam's remark into account.
39
    osutils,
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
40
    progress,
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
41
    trace,
1996.3.32 by John Arbash Meinel
from bzrlib.ui lazy import progress, and make progress import lazily
42
    )
43
""")
44
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
45
4503.2.1 by Vincent Ladeuil
Get a bool from a string.
46
_valid_boolean_strings = dict(yes=True, no=False,
47
                              y=True, n=False,
48
                              on=True, off=False,
49
                              true=True, false=False)
50
_valid_boolean_strings['1'] = True
51
_valid_boolean_strings['0'] = False
52
53
54
def bool_from_string(s, accepted_values=None):
55
    """Returns a boolean if the string can be interpreted as such.
56
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'
60
    parameter.
61
62
    :param s: A string that should be interpreted as a boolean. It should be of
63
        type string or unicode.
64
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
67
        version of 's'.
68
69
    :return: True or False for accepted strings, None otherwise.
70
    """
71
    if accepted_values is None:
72
        accepted_values = _valid_boolean_strings
73
    val = None
74
    if type(s) in (str, unicode):
75
        try:
76
            val = accepted_values[s.lower()]
77
        except KeyError:
78
            pass
79
    return val
80
81
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
82
class UIFactory(object):
83
    """UI abstraction.
84
85
    This tells the library how to display things to the user.  Through this
86
    layer different applications can choose the style of UI.
87
    """
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
88
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
89
    def __init__(self):
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
90
        self._task_stack = []
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
91
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
92
    def get_password(self, prompt='', **kwargs):
93
        """Prompt the user for a password.
94
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
98
                       they so choose.
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
99
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
103
                 transported as is.
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
104
        """
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
105
        raise NotImplementedError(self.get_password)
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
106
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
107
    def nested_progress_bar(self):
108
        """Return a nested progress bar.
109
2095.4.5 by mbp at sourcefrog
Use regular progress-bar classes, not a special mechanism
110
        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.
111
        bar.finished().
112
        """
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
113
        if self._task_stack:
3882.8.3 by Martin Pool
Move display of transport throughput into TextProgressView
114
            t = progress.ProgressTask(self._task_stack[-1], self)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
115
        else:
3882.8.3 by Martin Pool
Move display of transport throughput into TextProgressView
116
            t = progress.ProgressTask(None, self)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
117
        self._task_stack.append(t)
118
        return t
119
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
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"
124
                % (task,))
125
        elif task != self._task_stack[-1]:
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
126
            warnings.warn("%r is not the active task %r"
3948.2.2 by Martin Pool
Corrections to finishing progress bars
127
                % (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
128
        else:
129
            del self._task_stack[-1]
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
130
        if not self._task_stack:
3948.2.5 by Martin Pool
rename to _progress_all_finished
131
            self._progress_all_finished()
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
132
3948.2.5 by Martin Pool
rename to _progress_all_finished
133
    def _progress_all_finished(self):
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
134
        """Called when the top-level progress task finished"""
135
        pass
136
137
    def _progress_updated(self, task):
138
        """Called by the ProgressTask when it changes.
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
139
3948.2.7 by Martin Pool
pep8
140
        Should be specialized to draw the progress.
141
        """
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
142
        pass
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
143
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
144
    def clear_term(self):
145
        """Prepare the terminal for output.
146
147
        This will, for example, clear text progress bars, and leave the
3948.2.7 by Martin Pool
pep8
148
        cursor at the leftmost position.
149
        """
3948.2.2 by Martin Pool
Corrections to finishing progress bars
150
        pass
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
151
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
152
    def get_boolean(self, prompt):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
153
        """Get a boolean question answered from the user.
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
154
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.
158
        """
159
        raise NotImplementedError(self.get_boolean)
160
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
161
    def recommend_upgrade(self,
162
        current_format_name,
163
        basedir):
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
164
        # this should perhaps be in the TextUIFactory and the default can do
165
        # nothing
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
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"
170
            "  bzr upgrade %s",
171
            current_format_name,
172
            basedir)
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
173
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
174
    def report_transport_activity(self, transport, byte_count, direction):
175
        """Called by transports as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
176
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
177
        This may update a progress bar, spinner, or similar display.
178
        By default it does nothing.
179
        """
180
        pass
181
182
2461.1.1 by Vincent Ladeuil
Fix 110204 by letting TestUIFactory encode password prompt.
183
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
184
class CLIUIFactory(UIFactory):
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
185
    """Common behaviour for command line UI factories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
186
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
187
    This is suitable for dumb terminals that can't repaint existing text."""
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
188
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
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
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
194
4503.2.5 by Vincent Ladeuil
ui.get_boolean can also use bool_from_string.
195
    _accepted_boolean_strings = dict(y=True, n=False, yes=True, no=False)
196
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
197
    def get_boolean(self, prompt):
198
        while True:
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
199
            self.prompt(prompt + "? [y/n]: ")
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
200
            line = self.stdin.readline()
4503.2.5 by Vincent Ladeuil
ui.get_boolean can also use bool_from_string.
201
            line = line.rstrip('\n')
202
            val = bool_from_string(line, self._accepted_boolean_strings)
203
            if val is not None:
204
                return val
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
205
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
206
    def get_non_echoed_password(self):
4237.2.2 by Vincent Ladeuil
Don't presume we have a tty.
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('')
212
        else:
213
            # echo doesn't make sense without a terminal
214
            password = self.stdin.readline()
215
            if not password:
216
                password = None
217
            elif password[-1] == '\n':
218
                password = password[:-1]
219
        return password
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
220
221
    def get_password(self, prompt='', **kwargs):
222
        """Prompt the user for a password.
223
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
227
                       they so choose.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
228
        :return: The password string, return None if the user
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
229
                 canceled the request.
230
        """
231
        prompt += ': '
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
232
        self.prompt(prompt, **kwargs)
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
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?
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
235
        return self.get_non_echoed_password()
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
236
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
237
    def get_username(self, prompt, **kwargs):
4222.2.10 by Jelmer Vernooij
Fix docstring.
238
        """Prompt the user for a username.
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
239
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
243
                       they so choose.
4222.2.2 by Jelmer Vernooij
Review from vila: Deal with UTF8 strings in prompts, fix typo.
244
        :return: The username string, return None if the user
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
245
                 canceled the request.
246
        """
247
        prompt += ': '
4222.2.9 by Jelmer Vernooij
Merge bzr.dev, including Vincents NotATerminal patch.
248
        self.prompt(prompt, **kwargs)
4222.2.11 by Jelmer Vernooij
Review feedback from vila: cope with stdin.readline() returning None, fix consistency in tests.
249
        username = self.stdin.readline()
250
        if not username:
251
            username = None
252
        elif username[-1] == '\n':
253
            username = username[:-1]
254
        return username
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
255
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
256
    def prompt(self, prompt, **kwargs):
4300.3.2 by Martin Pool
Review tweak to comments
257
        """Emit prompt on the CLI.
258
        
259
        :param kwargs: Dictionary of arguments to insert into the prompt,
260
            to allow UIs to reformat the prompt.
261
        """
4300.3.1 by Martin Pool
Fix string expansion in TextUIFactory.prompt
262
        if kwargs:
4300.3.2 by Martin Pool
Review tweak to comments
263
            # See <https://launchpad.net/bugs/365891>
4300.3.1 by Martin Pool
Fix string expansion in TextUIFactory.prompt
264
            prompt = prompt % kwargs
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
265
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
266
        self.clear_term()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
267
        self.stderr.write(prompt)
3945.1.1 by Vincent Ladeuil
Restore a working UI implementation suitable for emacs shells.
268
269
    def note(self, msg):
270
        """Write an already-formatted message."""
271
        self.stdout.write(msg + '\n')
3882.7.10 by Martin Pool
CLIUIFactory implements (as stubs) progress methods
272
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
273
274
class SilentUIFactory(CLIUIFactory):
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
275
    """A UI Factory which never prints anything.
276
277
    This is the default UI, if another one is never registered.
278
    """
1594.1.1 by Robert Collins
Introduce new bzr progress bar api. ui_factory.nested_progress_bar.
279
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
280
    def __init__(self):
281
        CLIUIFactory.__init__(self)
282
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
283
    def get_password(self, prompt='', **kwargs):
284
        return None
285
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
286
    def get_username(self, prompt='', **kwargs):
287
        return None
288
4237.2.1 by Vincent Ladeuil
Stop requiring a tty for CLIUIFactory and derivatives.
289
    def prompt(self, prompt, **kwargs):
3945.1.1 by Vincent Ladeuil
Restore a working UI implementation suitable for emacs shells.
290
        pass
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
291
3882.8.4 by Martin Pool
All UI factories should support note()
292
    def note(self, msg):
293
        pass
294
3882.8.2 by Martin Pool
ProgressTask holds a reference to the ui that displays it
295
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
296
def clear_decorator(func, *args, **kwargs):
297
    """Decorator that clears the term"""
298
    ui_factory.clear_term()
299
    func(*args, **kwargs)
300
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
301
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
302
ui_factory = SilentUIFactory()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
303
"""IMPORTANT: never import this symbol directly. ONLY ever access it as
1534.5.9 by Robert Collins
Advise users running upgrade on a checkout to also run it on the branch.
304
ui.ui_factory."""
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
305
306
307
def make_ui_for_terminal(stdin, stdout, stderr):
308
    """Construct and return a suitable UIFactory for a text mode program.
309
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
310
    If stdout is a smart terminal, this gets a smart UIFactory with
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
311
    progress indicators, etc.  If it's a dumb terminal, just plain text output.
312
    """
3945.1.3 by Vincent Ladeuil
Restore line eaten by a gremlin.
313
    cls = None
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
314
    isatty = getattr(stdin, 'isatty', None)
315
    if isatty is None:
316
        cls = CLIUIFactory
317
    elif not isatty():
318
        cls = CLIUIFactory
4086.2.3 by Alexander Belchenko
Remove the check for no $TERM setting, as win32 doesn't have $TERM
319
    elif os.environ.get('TERM') in ('dumb', ''):
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
320
        # e.g. emacs compile window
321
        cls = CLIUIFactory
3945.1.1 by Vincent Ladeuil
Restore a working UI implementation suitable for emacs shells.
322
    # User may know better, otherwise default to TextUIFactory
323
    if (   os.environ.get('BZR_USE_TEXT_UI', None) is not None
324
        or cls is None):
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
325
        from bzrlib.ui.text import TextUIFactory
326
        cls = TextUIFactory
327
    return cls(stdin=stdin, stdout=stdout, stderr=stderr)