~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/__init__.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-09 20:23:07 UTC
  • mfrom: (4265.1.4 bbc-merge)
  • Revision ID: pqm@pqm.ubuntu.com-20090409202307-n0depb16qepoe21o
(jam) Change _fetch_uses_deltas = False for CHK repos until we can
        write a better fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
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
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
 
 
29
import os
31
30
import sys
 
31
import warnings
32
32
 
33
33
from bzrlib.lazy_import import lazy_import
34
34
lazy_import(globals(), """
35
35
import getpass
36
36
 
37
37
from bzrlib import (
 
38
    errors,
 
39
    osutils,
38
40
    progress,
39
41
    trace,
40
42
    )
41
43
""")
42
44
 
43
 
from bzrlib.symbol_versioning import (deprecated_method, zero_eight)
44
 
 
45
45
 
46
46
class UIFactory(object):
47
47
    """UI abstraction.
51
51
    """
52
52
 
53
53
    def __init__(self):
54
 
        super(UIFactory, self).__init__()
55
 
        self._progress_bar_stack = None
56
 
 
57
 
    @deprecated_method(zero_eight)
58
 
    def progress_bar(self):
59
 
        """See UIFactory.nested_progress_bar()."""
60
 
        raise NotImplementedError(self.progress_bar)
 
54
        self._task_stack = []
61
55
 
62
56
    def get_password(self, prompt='', **kwargs):
63
57
        """Prompt the user for a password.
80
74
        When the bar has been finished with, it should be released by calling
81
75
        bar.finished().
82
76
        """
83
 
        raise NotImplementedError(self.nested_progress_bar)
 
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
84
107
 
85
108
    def clear_term(self):
86
109
        """Prepare the terminal for output.
87
110
 
88
111
        This will, for example, clear text progress bars, and leave the
89
 
        cursor at the leftmost position."""
90
 
        raise NotImplementedError(self.clear_term)
 
112
        cursor at the leftmost position.
 
113
        """
 
114
        pass
91
115
 
92
116
    def get_boolean(self, prompt):
93
 
        """Get a boolean question answered from the user. 
 
117
        """Get a boolean question answered from the user.
94
118
 
95
119
        :param prompt: a message to prompt the user with. Should be a single
96
120
        line without terminating \n.
111
135
            current_format_name,
112
136
            basedir)
113
137
 
114
 
            
 
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
 
115
148
class CLIUIFactory(UIFactory):
116
 
    """Common behaviour for command line UI factories."""
117
 
 
118
 
    def __init__(self):
119
 
        super(CLIUIFactory, self).__init__()
120
 
        self.stdin = sys.stdin
 
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
121
158
 
122
159
    def get_boolean(self, prompt):
123
 
        self.clear_term()
124
160
        # FIXME: make a regexp and handle case variations as well.
125
161
        while True:
126
162
            self.prompt(prompt + "? [y/n]: ")
130
166
            if line in ('n\n', 'no\n'):
131
167
                return False
132
168
 
133
 
    def get_non_echoed_password(self, prompt):
134
 
        return getpass.getpass(prompt)
 
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
135
183
 
136
184
    def get_password(self, prompt='', **kwargs):
137
185
        """Prompt the user for a password.
140
188
        :param kwargs: Arguments which will be expanded into the prompt.
141
189
                       This lets front ends display different things if
142
190
                       they so choose.
143
 
        :return: The password string, return None if the user 
 
191
        :return: The password string, return None if the user
144
192
                 canceled the request.
145
193
        """
146
194
        prompt += ': '
147
 
        prompt = (prompt % kwargs).encode(sys.stdout.encoding, 'replace')
 
195
        self.prompt(prompt, **kwargs)
148
196
        # There's currently no way to say 'i decline to enter a password'
149
197
        # as opposed to 'my password is empty' -- does it matter?
150
 
        return self.get_non_echoed_password(prompt)
151
 
 
152
 
    def prompt(self, prompt):
 
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):
153
220
        """Emit prompt on the CLI."""
 
221
        prompt = prompt % kwargs
 
222
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
223
        self.clear_term()
 
224
        self.stdout.write(prompt)
 
225
 
 
226
    def note(self, msg):
 
227
        """Write an already-formatted message."""
 
228
        self.stdout.write(msg + '\n')
154
229
 
155
230
 
156
231
class SilentUIFactory(CLIUIFactory):
159
234
    This is the default UI, if another one is never registered.
160
235
    """
161
236
 
162
 
    @deprecated_method(zero_eight)
163
 
    def progress_bar(self):
164
 
        """See UIFactory.nested_progress_bar()."""
165
 
        return progress.DummyProgress()
 
237
    def __init__(self):
 
238
        CLIUIFactory.__init__(self)
166
239
 
167
240
    def get_password(self, prompt='', **kwargs):
168
241
        return None
169
242
 
170
 
    def nested_progress_bar(self):
171
 
        if self._progress_bar_stack is None:
172
 
            self._progress_bar_stack = progress.ProgressBarStack(
173
 
                klass=progress.DummyProgress)
174
 
        return self._progress_bar_stack.get_nested()
 
243
    def get_username(self, prompt='', **kwargs):
 
244
        return None
175
245
 
176
 
    def clear_term(self):
 
246
    def prompt(self, prompt, **kwargs):
177
247
        pass
178
248
 
179
 
    def recommend_upgrade(self, *args):
 
249
    def note(self, msg):
180
250
        pass
181
251
 
182
252
 
187
257
 
188
258
 
189
259
ui_factory = SilentUIFactory()
190
 
"""IMPORTANT: never import this symbol directly. ONLY ever access it as 
 
260
"""IMPORTANT: never import this symbol directly. ONLY ever access it as
191
261
ui.ui_factory."""
 
262
 
 
263
 
 
264
def make_ui_for_terminal(stdin, stdout, stderr):
 
265
    """Construct and return a suitable UIFactory for a text mode program.
 
266
 
 
267
    If stdout is a smart terminal, this gets a smart UIFactory with
 
268
    progress indicators, etc.  If it's a dumb terminal, just plain text output.
 
269
    """
 
270
    cls = None
 
271
    isatty = getattr(stdin, 'isatty', None)
 
272
    if isatty is None:
 
273
        cls = CLIUIFactory
 
274
    elif not isatty():
 
275
        cls = CLIUIFactory
 
276
    elif os.environ.get('TERM') in ('dumb', ''):
 
277
        # e.g. emacs compile window
 
278
        cls = CLIUIFactory
 
279
    # User may know better, otherwise default to TextUIFactory
 
280
    if (   os.environ.get('BZR_USE_TEXT_UI', None) is not None
 
281
        or cls is None):
 
282
        from bzrlib.ui.text import TextUIFactory
 
283
        cls = TextUIFactory
 
284
    return cls(stdin=stdin, stdout=stdout, stderr=stderr)