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