/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: Vincent Ladeuil
  • Date: 2009-01-23 21:06:48 UTC
  • mto: (3966.1.1 bzr.integration)
  • mto: This revision was merged to the branch mainline in revision 3967.
  • Revision ID: v.ladeuil+lp@free.fr-20090123210648-yfb39g22yyo83d3y
Slight refactoring and test fixing.

* bzrlib/tests/test_merge.py:
(TestMergerEntriesLCAOnDisk.test_modified_symlink): Passing now.

* bzrlib/merge.py:
(Merge3Merger._lca_multi_way): Fix doc reference.
(Merge3Merger.merge_contents.contents_conflict): Try to delay
this_pair evaulation to avoid unnecessary sha1 (impyling file read
from disk) calculation. Also slightly refactor to avoid repeated
file_id in trees calculations.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
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
 
 
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
        if task != self._task_stack[-1]:
 
86
            warnings.warn("%r is not currently active" % (task,))
 
87
        else:
 
88
            del self._task_stack[-1]
 
89
 
 
90
    def clear_term(self):
 
91
        """Prepare the terminal for output.
 
92
 
 
93
        This will, for example, clear text progress bars, and leave the
 
94
        cursor at the leftmost position."""
 
95
        raise NotImplementedError(self.clear_term)
 
96
 
 
97
    def get_boolean(self, prompt):
 
98
        """Get a boolean question answered from the user. 
 
99
 
 
100
        :param prompt: a message to prompt the user with. Should be a single
 
101
        line without terminating \n.
 
102
        :return: True or False for y/yes or n/no.
 
103
        """
 
104
        raise NotImplementedError(self.get_boolean)
 
105
 
 
106
    def recommend_upgrade(self,
 
107
        current_format_name,
 
108
        basedir):
 
109
        # this should perhaps be in the TextUIFactory and the default can do
 
110
        # nothing
 
111
        trace.warning("%s is deprecated "
 
112
            "and a better format is available.\n"
 
113
            "It is recommended that you upgrade by "
 
114
            "running the command\n"
 
115
            "  bzr upgrade %s",
 
116
            current_format_name,
 
117
            basedir)
 
118
 
 
119
    def report_transport_activity(self, transport, byte_count, direction):
 
120
        """Called by transports as they do IO.
 
121
        
 
122
        This may update a progress bar, spinner, or similar display.
 
123
        By default it does nothing.
 
124
        """
 
125
        pass
 
126
 
 
127
 
 
128
 
 
129
class CLIUIFactory(UIFactory):
 
130
    """Common behaviour for command line UI factories.
 
131
    
 
132
    This is suitable for dumb terminals that can't repaint existing text."""
 
133
 
 
134
    def __init__(self, stdin=None, stdout=None, stderr=None):
 
135
        UIFactory.__init__(self)
 
136
        self.stdin = stdin or sys.stdin
 
137
        self.stdout = stdout or sys.stdout
 
138
        self.stderr = stderr or sys.stderr
 
139
 
 
140
    def get_boolean(self, prompt):
 
141
        self.clear_term()
 
142
        # FIXME: make a regexp and handle case variations as well.
 
143
        while True:
 
144
            self.prompt(prompt + "? [y/n]: ")
 
145
            line = self.stdin.readline()
 
146
            if line in ('y\n', 'yes\n'):
 
147
                return True
 
148
            if line in ('n\n', 'no\n'):
 
149
                return False
 
150
 
 
151
    def get_non_echoed_password(self, prompt):
 
152
        if not sys.stdin.isatty():
 
153
            raise errors.NotATerminal()
 
154
        encoding = osutils.get_terminal_encoding()
 
155
        return getpass.getpass(prompt.encode(encoding, 'replace'))
 
156
 
 
157
    def get_password(self, prompt='', **kwargs):
 
158
        """Prompt the user for a password.
 
159
 
 
160
        :param prompt: The prompt to present the user
 
161
        :param kwargs: Arguments which will be expanded into the prompt.
 
162
                       This lets front ends display different things if
 
163
                       they so choose.
 
164
        :return: The password string, return None if the user 
 
165
                 canceled the request.
 
166
        """
 
167
        prompt += ': '
 
168
        prompt = (prompt % kwargs)
 
169
        # There's currently no way to say 'i decline to enter a password'
 
170
        # as opposed to 'my password is empty' -- does it matter?
 
171
        return self.get_non_echoed_password(prompt)
 
172
 
 
173
    def prompt(self, prompt):
 
174
        """Emit prompt on the CLI."""
 
175
        self.stdout.write(prompt)
 
176
 
 
177
    def note(self, msg):
 
178
        """Write an already-formatted message."""
 
179
        self.stdout.write(msg + '\n')
 
180
 
 
181
    def clear_term(self):
 
182
        pass
 
183
 
 
184
    def show_progress(self, task):
 
185
        pass
 
186
 
 
187
    def progress_finished(self, task):
 
188
        pass
 
189
 
 
190
 
 
191
class SilentUIFactory(CLIUIFactory):
 
192
    """A UI Factory which never prints anything.
 
193
 
 
194
    This is the default UI, if another one is never registered.
 
195
    """
 
196
 
 
197
    def __init__(self):
 
198
        CLIUIFactory.__init__(self)
 
199
 
 
200
    def get_password(self, prompt='', **kwargs):
 
201
        return None
 
202
 
 
203
    def prompt(self, prompt):
 
204
        pass
 
205
 
 
206
    def note(self, msg):
 
207
        pass
 
208
 
 
209
 
 
210
def clear_decorator(func, *args, **kwargs):
 
211
    """Decorator that clears the term"""
 
212
    ui_factory.clear_term()
 
213
    func(*args, **kwargs)
 
214
 
 
215
 
 
216
ui_factory = SilentUIFactory()
 
217
"""IMPORTANT: never import this symbol directly. ONLY ever access it as 
 
218
ui.ui_factory."""
 
219
 
 
220
 
 
221
def make_ui_for_terminal(stdin, stdout, stderr):
 
222
    """Construct and return a suitable UIFactory for a text mode program.
 
223
 
 
224
    If stdout is a smart terminal, this gets a smart UIFactory with 
 
225
    progress indicators, etc.  If it's a dumb terminal, just plain text output.
 
226
    """
 
227
    cls = None
 
228
    isatty = getattr(stdin, 'isatty', None)
 
229
    if isatty is None:
 
230
        cls = CLIUIFactory
 
231
    elif not isatty():
 
232
        cls = CLIUIFactory
 
233
    elif os.environ.get('TERM') in (None, 'dumb', ''):
 
234
        # e.g. emacs compile window
 
235
        cls = CLIUIFactory
 
236
    # User may know better, otherwise default to TextUIFactory
 
237
    if (   os.environ.get('BZR_USE_TEXT_UI', None) is not None
 
238
        or cls is None):
 
239
        from bzrlib.ui.text import TextUIFactory
 
240
        cls = TextUIFactory
 
241
    return cls(stdin=stdin, stdout=stdout, stderr=stderr)