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