~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/__init__.py

Fix lock test failures by taking lock breaking into account.

* tests/test_lockdir.py:
(TestLockDir.test_43_break): Release the lock after breaking and
acquiring it.

* tests/__init__.py:
(TestCase._check_locks): Consider lock breaks as releases.
(TestCase._track_locks, TestCase._lock_broken): Also track broken locks.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
2
 
 
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
 
 
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
 
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
16
 
19
17
"""UI abstraction.
20
18
 
28
26
displays no output.
29
27
"""
30
28
 
31
 
 
32
 
 
33
 
 
34
 
 
35
 
import bzrlib.progress
36
 
 
37
 
 
38
 
class TextUIFactory(object):
39
 
    def progress_bar(self):
40
 
 
41
 
        # this in turn is abstract, and creates either a tty or dots
42
 
        # bar depending on what we think of the terminal
43
 
        return bzrlib.progress.ProgressBar()
44
 
 
45
 
 
46
 
class SilentUIFactory(object):
47
 
    def progress_bar(self):
48
 
        return bzrlib.progress.DummyProgress()
 
29
import os
 
30
import sys
 
31
import warnings
 
32
 
 
33
from bzrlib.lazy_import import lazy_import
 
34
lazy_import(globals(), """
 
35
import getpass
 
36
 
 
37
from bzrlib import (
 
38
    errors,
 
39
    osutils,
 
40
    progress,
 
41
    trace,
 
42
    )
 
43
""")
 
44
 
 
45
 
 
46
class UIFactory(object):
 
47
    """UI abstraction.
 
48
 
 
49
    This tells the library how to display things to the user.  Through this
 
50
    layer different applications can choose the style of UI.
 
51
    """
 
52
 
 
53
    def __init__(self):
 
54
        self._task_stack = []
 
55
 
 
56
    def get_password(self, prompt='', **kwargs):
 
57
        """Prompt the user for a password.
 
58
 
 
59
        :param prompt: The prompt to present the user
 
60
        :param kwargs: Arguments which will be expanded into the prompt.
 
61
                       This lets front ends display different things if
 
62
                       they so choose.
 
63
 
 
64
        :return: The password string, return None if the user canceled the
 
65
                 request. Note that we do not touch the encoding, users may
 
66
                 have whatever they see fit and the password should be
 
67
                 transported as is.
 
68
        """
 
69
        raise NotImplementedError(self.get_password)
 
70
 
 
71
    def nested_progress_bar(self):
 
72
        """Return a nested progress bar.
 
73
 
 
74
        When the bar has been finished with, it should be released by calling
 
75
        bar.finished().
 
76
        """
 
77
        if self._task_stack:
 
78
            t = progress.ProgressTask(self._task_stack[-1], self)
 
79
        else:
 
80
            t = progress.ProgressTask(None, self)
 
81
        self._task_stack.append(t)
 
82
        return t
 
83
 
 
84
    def _progress_finished(self, task):
 
85
        """Called by the ProgressTask when it finishes"""
 
86
        if not self._task_stack:
 
87
            warnings.warn("%r finished but nothing is active"
 
88
                % (task,))
 
89
        elif task != self._task_stack[-1]:
 
90
            warnings.warn("%r is not the active task %r"
 
91
                % (task, self._task_stack[-1]))
 
92
        else:
 
93
            del self._task_stack[-1]
 
94
        if not self._task_stack:
 
95
            self._progress_all_finished()
 
96
 
 
97
    def _progress_all_finished(self):
 
98
        """Called when the top-level progress task finished"""
 
99
        pass
 
100
 
 
101
    def _progress_updated(self, task):
 
102
        """Called by the ProgressTask when it changes.
 
103
 
 
104
        Should be specialized to draw the progress.
 
105
        """
 
106
        pass
 
107
 
 
108
    def clear_term(self):
 
109
        """Prepare the terminal for output.
 
110
 
 
111
        This will, for example, clear text progress bars, and leave the
 
112
        cursor at the leftmost position.
 
113
        """
 
114
        pass
 
115
 
 
116
    def get_boolean(self, prompt):
 
117
        """Get a boolean question answered from the user.
 
118
 
 
119
        :param prompt: a message to prompt the user with. Should be a single
 
120
        line without terminating \n.
 
121
        :return: True or False for y/yes or n/no.
 
122
        """
 
123
        raise NotImplementedError(self.get_boolean)
 
124
 
 
125
    def recommend_upgrade(self,
 
126
        current_format_name,
 
127
        basedir):
 
128
        # this should perhaps be in the TextUIFactory and the default can do
 
129
        # nothing
 
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"
 
134
            "  bzr upgrade %s",
 
135
            current_format_name,
 
136
            basedir)
 
137
 
 
138
    def report_transport_activity(self, transport, byte_count, direction):
 
139
        """Called by transports as they do IO.
 
140
 
 
141
        This may update a progress bar, spinner, or similar display.
 
142
        By default it does nothing.
 
143
        """
 
144
        pass
 
145
 
 
146
 
 
147
 
 
148
class CLIUIFactory(UIFactory):
 
149
    """Common behaviour for command line UI factories.
 
150
 
 
151
    This is suitable for dumb terminals that can't repaint existing text."""
 
152
 
 
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
 
158
 
 
159
    def get_boolean(self, prompt):
 
160
        # FIXME: make a regexp and handle case variations as well.
 
161
        while True:
 
162
            self.prompt(prompt + "? [y/n]: ")
 
163
            line = self.stdin.readline()
 
164
            if line in ('y\n', 'yes\n'):
 
165
                return True
 
166
            if line in ('n\n', 'no\n'):
 
167
                return False
 
168
 
 
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('')
 
175
        else:
 
176
            # echo doesn't make sense without a terminal
 
177
            password = self.stdin.readline()
 
178
            if not password:
 
179
                password = None
 
180
            elif password[-1] == '\n':
 
181
                password = password[:-1]
 
182
        return password
 
183
 
 
184
    def get_password(self, prompt='', **kwargs):
 
185
        """Prompt the user for a password.
 
186
 
 
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
 
190
                       they so choose.
 
191
        :return: The password string, return None if the user
 
192
                 canceled the request.
 
193
        """
 
194
        prompt += ': '
 
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()
 
199
 
 
200
    def get_username(self, prompt, **kwargs):
 
201
        """Prompt the user for a username.
 
202
 
 
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
 
206
                       they so choose.
 
207
        :return: The username string, return None if the user
 
208
                 canceled the request.
 
209
        """
 
210
        prompt += ': '
 
211
        self.prompt(prompt, **kwargs)
 
212
        username = self.stdin.readline()
 
213
        if not username:
 
214
            username = None
 
215
        elif username[-1] == '\n':
 
216
            username = username[:-1]
 
217
        return username
 
218
 
 
219
    def prompt(self, prompt, **kwargs):
 
220
        """Emit prompt on the CLI.
 
221
        
 
222
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
223
            to allow UIs to reformat the prompt.
 
224
        """
 
225
        if kwargs:
 
226
            # See <https://launchpad.net/bugs/365891>
 
227
            prompt = prompt % kwargs
 
228
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
229
        self.clear_term()
 
230
        self.stdout.write(prompt)
 
231
 
 
232
    def note(self, msg):
 
233
        """Write an already-formatted message."""
 
234
        self.stdout.write(msg + '\n')
 
235
 
 
236
 
 
237
class SilentUIFactory(CLIUIFactory):
 
238
    """A UI Factory which never prints anything.
 
239
 
 
240
    This is the default UI, if another one is never registered.
 
241
    """
 
242
 
 
243
    def __init__(self):
 
244
        CLIUIFactory.__init__(self)
 
245
 
 
246
    def get_password(self, prompt='', **kwargs):
 
247
        return None
 
248
 
 
249
    def get_username(self, prompt='', **kwargs):
 
250
        return None
 
251
 
 
252
    def prompt(self, prompt, **kwargs):
 
253
        pass
 
254
 
 
255
    def note(self, msg):
 
256
        pass
 
257
 
 
258
 
 
259
def clear_decorator(func, *args, **kwargs):
 
260
    """Decorator that clears the term"""
 
261
    ui_factory.clear_term()
 
262
    func(*args, **kwargs)
49
263
 
50
264
 
51
265
ui_factory = SilentUIFactory()
 
266
"""IMPORTANT: never import this symbol directly. ONLY ever access it as
 
267
ui.ui_factory."""
 
268
 
 
269
 
 
270
def make_ui_for_terminal(stdin, stdout, stderr):
 
271
    """Construct and return a suitable UIFactory for a text mode program.
 
272
 
 
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.
 
275
    """
 
276
    cls = None
 
277
    isatty = getattr(stdin, 'isatty', None)
 
278
    if isatty is None:
 
279
        cls = CLIUIFactory
 
280
    elif not isatty():
 
281
        cls = CLIUIFactory
 
282
    elif os.environ.get('TERM') in ('dumb', ''):
 
283
        # e.g. emacs compile window
 
284
        cls = CLIUIFactory
 
285
    # User may know better, otherwise default to TextUIFactory
 
286
    if (   os.environ.get('BZR_USE_TEXT_UI', None) is not None
 
287
        or cls is None):
 
288
        from bzrlib.ui.text import TextUIFactory
 
289
        cls = TextUIFactory
 
290
    return cls(stdin=stdin, stdout=stdout, stderr=stderr)