/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4634.144.1 by Martin Pool
Give the warning about cross-format fetches earlier on in fetch
1
# Copyright (C) 2005, 2008, 2009, 2010 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
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.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
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.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
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.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
16
17
18
"""Text UI, write output to the console.
19
"""
20
4566.1.1 by John Arbash Meinel
Fix a fairly critical bug where TextUIFactory.get_non_echoed_password was failing.
21
import getpass
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
22
import os
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
23
import sys
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
24
import time
3948.2.2 by Martin Pool
Corrections to finishing progress bars
25
import warnings
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
26
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
29
from bzrlib import (
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
30
    debug,
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
31
    progress,
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
32
    osutils,
3882.8.8 by Martin Pool
Progress and UI test cleanups
33
    symbol_versioning,
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
34
    trace,
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
35
    )
3882.8.8 by Martin Pool
Progress and UI test cleanups
36
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
37
""")
38
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
39
from bzrlib.ui import (
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
40
    UIFactory,
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
41
    NullProgressView,
42
    )
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
43
44
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
45
class TextUIFactory(UIFactory):
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
46
    """A UI factory for Text user interefaces."""
47
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
48
    def __init__(self,
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
49
                 stdin=None,
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
50
                 stdout=None,
51
                 stderr=None):
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
52
        """Create a TextUIFactory.
53
4463.1.1 by Martin Pool
Update docstrings for recent progress changes
54
        :param bar_type: The type of progress bar to create.  Deprecated
55
            and ignored; a TextProgressView is always used.
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
56
        """
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
57
        super(TextUIFactory, self).__init__()
4449.3.28 by Martin Pool
todo
58
        # TODO: there's no good reason not to pass all three streams, maybe we
59
        # should deprecate the default values...
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
60
        self.stdin = stdin
61
        self.stdout = stdout
62
        self.stderr = stderr
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
63
        # paints progress, network activity, etc
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
64
        self._progress_view = self.make_progress_view()
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
65
        
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
66
    def clear_term(self):
67
        """Prepare the terminal for output.
68
69
        This will, clear any progress bars, and leave the cursor at the
70
        leftmost position."""
3882.7.6 by Martin Pool
Preliminary support for drawing network io into the progress bar
71
        # XXX: If this is preparing to write to stdout, but that's for example
72
        # directed into a file rather than to the terminal, and the progress
73
        # bar _is_ going to the terminal, we shouldn't need
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
74
        # to clear it.  We might need to separately check for the case of
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
75
        self._progress_view.clear()
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
76
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
77
    def get_boolean(self, prompt):
78
        while True:
79
            self.prompt(prompt + "? [y/n]: ")
4449.3.37 by Martin Pool
TextUIFactory should cope with EOF when in get_boolean
80
            line = self.stdin.readline().lower()
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
81
            if line in ('y\n', 'yes\n'):
82
                return True
4449.3.37 by Martin Pool
TextUIFactory should cope with EOF when in get_boolean
83
            elif line in ('n\n', 'no\n'):
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
84
                return False
4449.3.37 by Martin Pool
TextUIFactory should cope with EOF when in get_boolean
85
            elif line in ('', None):
86
                # end-of-file; possibly should raise an error here instead
87
                return None
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
88
89
    def get_non_echoed_password(self):
90
        isatty = getattr(self.stdin, 'isatty', None)
91
        if isatty is not None and isatty():
92
            # getpass() ensure the password is not echoed and other
93
            # cross-platform niceties
94
            password = getpass.getpass('')
95
        else:
96
            # echo doesn't make sense without a terminal
97
            password = self.stdin.readline()
98
            if not password:
99
                password = None
100
            elif password[-1] == '\n':
101
                password = password[:-1]
102
        return password
103
104
    def get_password(self, prompt='', **kwargs):
105
        """Prompt the user for a password.
106
107
        :param prompt: The prompt to present the user
108
        :param kwargs: Arguments which will be expanded into the prompt.
109
                       This lets front ends display different things if
110
                       they so choose.
111
        :return: The password string, return None if the user
112
                 canceled the request.
113
        """
114
        prompt += ': '
115
        self.prompt(prompt, **kwargs)
116
        # There's currently no way to say 'i decline to enter a password'
117
        # as opposed to 'my password is empty' -- does it matter?
118
        return self.get_non_echoed_password()
119
120
    def get_username(self, prompt, **kwargs):
121
        """Prompt the user for a username.
122
123
        :param prompt: The prompt to present the user
124
        :param kwargs: Arguments which will be expanded into the prompt.
125
                       This lets front ends display different things if
126
                       they so choose.
127
        :return: The username string, return None if the user
128
                 canceled the request.
129
        """
130
        prompt += ': '
131
        self.prompt(prompt, **kwargs)
132
        username = self.stdin.readline()
133
        if not username:
134
            username = None
135
        elif username[-1] == '\n':
136
            username = username[:-1]
137
        return username
138
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
139
    def make_progress_view(self):
140
        """Construct and return a new ProgressView subclass for this UI.
141
        """
142
        # if the user specifically requests either text or no progress bars,
143
        # always do that.  otherwise, guess based on $TERM and tty presence.
144
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
145
            return TextProgressView(self.stderr)
146
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
147
            return NullProgressView()
148
        elif progress._supports_progress(self.stderr):
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
149
            return TextProgressView(self.stderr)
150
        else:
151
            return NullProgressView()
152
3882.8.4 by Martin Pool
All UI factories should support note()
153
    def note(self, msg):
154
        """Write an already-formatted message, clearing the progress bar if necessary."""
155
        self.clear_term()
156
        self.stdout.write(msg + '\n')
157
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
158
    def prompt(self, prompt, **kwargs):
159
        """Emit prompt on the CLI.
160
        
161
        :param kwargs: Dictionary of arguments to insert into the prompt,
162
            to allow UIs to reformat the prompt.
163
        """
164
        if kwargs:
165
            # See <https://launchpad.net/bugs/365891>
166
            prompt = prompt % kwargs
167
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
168
        self.clear_term()
169
        self.stderr.write(prompt)
170
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
171
    def report_transport_activity(self, transport, byte_count, direction):
172
        """Called by transports as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
173
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
174
        This may update a progress bar, spinner, or similar display.
175
        By default it does nothing.
176
        """
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
177
        self._progress_view.show_transport_activity(transport,
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
178
            direction, byte_count)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
179
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
180
    def _progress_updated(self, task):
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
181
        """A task has been updated and wants to be displayed.
182
        """
4070.1.1 by Martin Pool
Be more robust about pb updates when none are active
183
        if not self._task_stack:
184
            warnings.warn("%r updated but no tasks are active" %
185
                (task,))
186
        elif task != self._task_stack[-1]:
3948.2.2 by Martin Pool
Corrections to finishing progress bars
187
            warnings.warn("%r is not the top progress task %r" %
188
                (task, self._task_stack[-1]))
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
189
        self._progress_view.show_progress(task)
190
3948.2.5 by Martin Pool
rename to _progress_all_finished
191
    def _progress_all_finished(self):
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
192
        self._progress_view.clear()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
193
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
194
    def show_user_warning(self, warning_id, **message_args):
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
195
        """Show a text message to the user.
196
197
        Explicitly not for warnings about bzr apis, deprecations or internals.
198
        """
199
        # eventually trace.warning should migrate here, to avoid logging and
200
        # be easier to test; that has a lot of test fallout so for now just
201
        # new code can call this
4634.144.11 by Martin Pool
Rename squelched to suppressed
202
        if warning_id not in self.suppressed_warnings:
4634.144.9 by Martin Pool
Suppress user warnings about cross-format fetch during upgrade
203
            self.stderr.write(self.format_user_warning(warning_id, message_args) +
204
                '\n')
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
205
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
206
207
class TextProgressView(object):
208
    """Display of progress bar and other information on a tty.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
209
210
    This shows one line of text, including possibly a network indicator, spinner,
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
211
    progress bar, message, etc.
212
213
    One instance of this is created and held by the UI, and fed updates when a
214
    task wants to be painted.
215
216
    Transports feed data to this through the ui_factory object.
3948.2.2 by Martin Pool
Corrections to finishing progress bars
217
218
    The Progress views can comprise a tree with _parent_task pointers, but
219
    this only prints the stack from the nominated current task up to the root.
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
220
    """
221
222
    def __init__(self, term_file):
223
        self._term_file = term_file
224
        # true when there's output on the screen we may need to clear
225
        self._have_output = False
226
        # XXX: We could listen for SIGWINCH and update the terminal width...
4470.3.1 by Martin Pool
Progress bars no longer show transport scheme or direction
227
        # https://launchpad.net/bugs/316357
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
228
        self._width = osutils.terminal_width()
229
        self._last_transport_msg = ''
230
        self._spin_pos = 0
231
        # time we last repainted the screen
232
        self._last_repaint = 0
233
        # time we last got information about transport activity
234
        self._transport_update_time = 0
235
        self._last_task = None
236
        self._total_byte_count = 0
237
        self._bytes_since_update = 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
238
        self._fraction = 0
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
239
240
    def _show_line(self, s):
4580.3.1 by Martin Pool
ProgressTasks can specify an update latency
241
        # sys.stderr.write("progress %r\n" % s)
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
242
        n = self._width - 1
243
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
244
245
    def clear(self):
246
        if self._have_output:
247
            self._show_line('')
248
        self._have_output = False
249
250
    def _render_bar(self):
251
        # return a string for the progress bar itself
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
252
        if (self._last_task is None) or self._last_task.show_bar:
253
            # If there's no task object, we show space for the bar anyhow.
254
            # That's because most invocations of bzr will end showing progress
255
            # at some point, though perhaps only after doing some initial IO.
256
            # It looks better to draw the progress bar initially rather than
257
            # to have what looks like an incomplete progress bar.
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
258
            spin_str =  r'/-\|'[self._spin_pos % 4]
259
            self._spin_pos += 1
260
            cols = 20
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
261
            if self._last_task is None:
262
                completion_fraction = 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
263
                self._fraction = 0
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
264
            else:
265
                completion_fraction = \
266
                    self._last_task._overall_completion_fraction() or 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
267
            if (completion_fraction < self._fraction and 'progress' in
268
                debug.debug_flags):
269
                import pdb;pdb.set_trace()
270
            self._fraction = completion_fraction
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
271
            markers = int(round(float(cols) * completion_fraction)) - 1
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
272
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
273
            return bar_str
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
274
        elif self._last_task.show_spinner:
275
            # The last task wanted just a spinner, no bar
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
276
            spin_str =  r'/-\|'[self._spin_pos % 4]
277
            self._spin_pos += 1
278
            return spin_str + ' '
279
        else:
280
            return ''
281
282
    def _format_task(self, task):
283
        if not task.show_count:
284
            s = ''
4017.1.1 by John Arbash Meinel
Get a pb.tick() to work after calling pb.update()
285
        elif task.current_cnt is not None and task.total_cnt is not None:
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
286
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
287
        elif task.current_cnt is not None:
288
            s = ' %d' % (task.current_cnt)
289
        else:
290
            s = ''
291
        # compose all the parent messages
292
        t = task
293
        m = task.msg
294
        while t._parent_task:
295
            t = t._parent_task
296
            if t.msg:
297
                m = t.msg + ':' + m
298
        return m + s
299
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
300
    def _render_line(self):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
301
        bar_string = self._render_bar()
302
        if self._last_task:
303
            task_msg = self._format_task(self._last_task)
304
        else:
305
            task_msg = ''
4580.3.5 by Martin Pool
selftest sets ProgressTask.show_transport_activity off
306
        if self._last_task and not self._last_task.show_transport_activity:
307
            trans = ''
308
        else:
309
            trans = self._last_transport_msg
310
            if trans:
311
                trans += ' | '
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
312
        return (bar_string + trans + task_msg)
313
314
    def _repaint(self):
315
        s = self._render_line()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
316
        self._show_line(s)
317
        self._have_output = True
318
319
    def show_progress(self, task):
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
320
        """Called by the task object when it has changed.
321
        
322
        :param task: The top task object; its parents are also included 
323
            by following links.
324
        """
4110.2.18 by Martin Pool
Progress bars always repaint when task structure is changed
325
        must_update = task is not self._last_task
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
326
        self._last_task = task
327
        now = time.time()
4580.3.1 by Martin Pool
ProgressTasks can specify an update latency
328
        if (not must_update) and (now < self._last_repaint + task.update_latency):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
329
            return
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
330
        if now > self._transport_update_time + 10:
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
331
            # no recent activity; expire it
332
            self._last_transport_msg = ''
333
        self._last_repaint = now
334
        self._repaint()
335
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
336
    def show_transport_activity(self, transport, direction, byte_count):
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
337
        """Called by transports via the ui_factory, as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
338
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
339
        This may update a progress bar, spinner, or similar display.
340
        By default it does nothing.
341
        """
342
        # XXX: Probably there should be a transport activity model, and that
343
        # too should be seen by the progress view, rather than being poked in
344
        # here.
4480.1.1 by Martin Pool
(mbp) only show transport activity when progress is already visible
345
        if not self._have_output:
346
            # As a workaround for <https://launchpad.net/bugs/321935> we only
347
            # show transport activity when there's already a progress bar
348
            # shown, which time the application code is expected to know to
349
            # clear off the progress bar when it's going to send some other
350
            # output.  Eventually it would be nice to have that automatically
351
            # synchronized.
352
            return
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
353
        self._total_byte_count += byte_count
354
        self._bytes_since_update += byte_count
355
        now = time.time()
4580.3.4 by Martin Pool
Don't show transport activity until 2kB has gone past
356
        if self._total_byte_count < 2000:
357
            # a little resistance at first, so it doesn't stay stuck at 0
358
            # while connecting...
359
            return
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
360
        if self._transport_update_time is None:
361
            self._transport_update_time = now
4043.1.1 by John Arbash Meinel
Increase the debounce time for 'transport activity' to 0.5s
362
        elif now >= (self._transport_update_time + 0.5):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
363
            # guard against clock stepping backwards, and don't update too
364
            # often
365
            rate = self._bytes_since_update / (now - self._transport_update_time)
4470.3.1 by Martin Pool
Progress bars no longer show transport scheme or direction
366
            msg = ("%6dKB %5dKB/s" %
367
                    (self._total_byte_count>>10, int(rate)>>10,))
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
368
            self._transport_update_time = now
369
            self._last_repaint = now
370
            self._bytes_since_update = 0
371
            self._last_transport_msg = msg
372
            self._repaint()