1
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
"""Text UI, write output to the console.
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
38
from bzrlib.ui import (
44
class TextUIFactory(UIFactory):
45
"""A UI factory for Text user interefaces."""
51
"""Create a TextUIFactory.
53
super(TextUIFactory, self).__init__()
54
# TODO: there's no good reason not to pass all three streams, maybe we
55
# should deprecate the default values...
59
# paints progress, network activity, etc
60
self._progress_view = self.make_progress_view()
63
"""Prepare the terminal for output.
65
This will, clear any progress bars, and leave the cursor at the
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
70
# to clear it. We might need to separately check for the case of
71
self._progress_view.clear()
73
def get_boolean(self, prompt):
75
self.prompt(prompt + "? [y/n]: ")
76
line = self.stdin.readline().lower()
77
if line in ('y\n', 'yes\n'):
79
elif line in ('n\n', 'no\n'):
81
elif line in ('', None):
82
# end-of-file; possibly should raise an error here instead
85
def get_non_echoed_password(self):
86
isatty = getattr(self.stdin, 'isatty', None)
87
if isatty is not None and isatty():
88
# getpass() ensure the password is not echoed and other
89
# cross-platform niceties
90
password = getpass.getpass('')
92
# echo doesn't make sense without a terminal
93
password = self.stdin.readline()
96
elif password[-1] == '\n':
97
password = password[:-1]
100
def get_password(self, prompt='', **kwargs):
101
"""Prompt the user for a password.
103
:param prompt: The prompt to present the user
104
:param kwargs: Arguments which will be expanded into the prompt.
105
This lets front ends display different things if
107
:return: The password string, return None if the user
108
canceled the request.
111
self.prompt(prompt, **kwargs)
112
# There's currently no way to say 'i decline to enter a password'
113
# as opposed to 'my password is empty' -- does it matter?
114
return self.get_non_echoed_password()
116
def get_username(self, prompt, **kwargs):
117
"""Prompt the user for a username.
119
:param prompt: The prompt to present the user
120
:param kwargs: Arguments which will be expanded into the prompt.
121
This lets front ends display different things if
123
:return: The username string, return None if the user
124
canceled the request.
127
self.prompt(prompt, **kwargs)
128
username = self.stdin.readline()
131
elif username[-1] == '\n':
132
username = username[:-1]
135
def make_progress_view(self):
136
"""Construct and return a new ProgressView subclass for this UI.
138
# if the user specifically requests either text or no progress bars,
139
# always do that. otherwise, guess based on $TERM and tty presence.
140
if os.environ.get('BZR_PROGRESS_BAR') == 'text':
141
return TextProgressView(self.stderr)
142
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
143
return NullProgressView()
144
elif progress._supports_progress(self.stderr):
145
return TextProgressView(self.stderr)
147
return NullProgressView()
150
"""Write an already-formatted message, clearing the progress bar if necessary."""
152
self.stdout.write(msg + '\n')
154
def prompt(self, prompt, **kwargs):
155
"""Emit prompt on the CLI.
157
:param kwargs: Dictionary of arguments to insert into the prompt,
158
to allow UIs to reformat the prompt.
161
# See <https://launchpad.net/bugs/365891>
162
prompt = prompt % kwargs
163
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
165
self.stderr.write(prompt)
167
def report_transport_activity(self, transport, byte_count, direction):
168
"""Called by transports as they do IO.
170
This may update a progress bar, spinner, or similar display.
171
By default it does nothing.
173
self._progress_view.show_transport_activity(transport,
174
direction, byte_count)
176
def show_error(self, msg):
178
self.stderr.write("bzr: error: %s\n" % msg)
180
def show_message(self, msg):
183
def show_warning(self, msg):
185
self.stderr.write("bzr: warning: %s\n" % msg)
187
def _progress_updated(self, task):
188
"""A task has been updated and wants to be displayed.
190
if not self._task_stack:
191
warnings.warn("%r updated but no tasks are active" %
193
elif task != self._task_stack[-1]:
194
warnings.warn("%r is not the top progress task %r" %
195
(task, self._task_stack[-1]))
196
self._progress_view.show_progress(task)
198
def _progress_all_finished(self):
199
self._progress_view.clear()
202
class TextProgressView(object):
203
"""Display of progress bar and other information on a tty.
205
This shows one line of text, including possibly a network indicator, spinner,
206
progress bar, message, etc.
208
One instance of this is created and held by the UI, and fed updates when a
209
task wants to be painted.
211
Transports feed data to this through the ui_factory object.
213
The Progress views can comprise a tree with _parent_task pointers, but
214
this only prints the stack from the nominated current task up to the root.
217
def __init__(self, term_file):
218
self._term_file = term_file
219
# true when there's output on the screen we may need to clear
220
self._have_output = False
221
# XXX: We could listen for SIGWINCH and update the terminal width...
222
# https://launchpad.net/bugs/316357
223
self._width = osutils.terminal_width()
224
self._last_transport_msg = ''
226
# time we last repainted the screen
227
self._last_repaint = 0
228
# time we last got information about transport activity
229
self._transport_update_time = 0
230
self._last_task = None
231
self._total_byte_count = 0
232
self._bytes_since_update = 0
235
def _show_line(self, s):
236
# sys.stderr.write("progress %r\n" % s)
238
self._term_file.write('\r%-*.*s\r' % (n, n, s))
241
if self._have_output:
243
self._have_output = False
245
def _render_bar(self):
246
# return a string for the progress bar itself
247
if (self._last_task is None) or self._last_task.show_bar:
248
# If there's no task object, we show space for the bar anyhow.
249
# That's because most invocations of bzr will end showing progress
250
# at some point, though perhaps only after doing some initial IO.
251
# It looks better to draw the progress bar initially rather than
252
# to have what looks like an incomplete progress bar.
253
spin_str = r'/-\|'[self._spin_pos % 4]
256
if self._last_task is None:
257
completion_fraction = 0
260
completion_fraction = \
261
self._last_task._overall_completion_fraction() or 0
262
if (completion_fraction < self._fraction and 'progress' in
264
import pdb;pdb.set_trace()
265
self._fraction = completion_fraction
266
markers = int(round(float(cols) * completion_fraction)) - 1
267
bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
269
elif self._last_task.show_spinner:
270
# The last task wanted just a spinner, no bar
271
spin_str = r'/-\|'[self._spin_pos % 4]
273
return spin_str + ' '
277
def _format_task(self, task):
278
if not task.show_count:
280
elif task.current_cnt is not None and task.total_cnt is not None:
281
s = ' %d/%d' % (task.current_cnt, task.total_cnt)
282
elif task.current_cnt is not None:
283
s = ' %d' % (task.current_cnt)
286
# compose all the parent messages
289
while t._parent_task:
295
def _render_line(self):
296
bar_string = self._render_bar()
298
task_msg = self._format_task(self._last_task)
301
if self._last_task and not self._last_task.show_transport_activity:
304
trans = self._last_transport_msg
307
return (bar_string + trans + task_msg)
310
s = self._render_line()
312
self._have_output = True
314
def show_progress(self, task):
315
"""Called by the task object when it has changed.
317
:param task: The top task object; its parents are also included
320
must_update = task is not self._last_task
321
self._last_task = task
323
if (not must_update) and (now < self._last_repaint + task.update_latency):
325
if now > self._transport_update_time + 10:
326
# no recent activity; expire it
327
self._last_transport_msg = ''
328
self._last_repaint = now
331
def show_transport_activity(self, transport, direction, byte_count):
332
"""Called by transports via the ui_factory, as they do IO.
334
This may update a progress bar, spinner, or similar display.
335
By default it does nothing.
337
# XXX: Probably there should be a transport activity model, and that
338
# too should be seen by the progress view, rather than being poked in
340
if not self._have_output:
341
# As a workaround for <https://launchpad.net/bugs/321935> we only
342
# show transport activity when there's already a progress bar
343
# shown, which time the application code is expected to know to
344
# clear off the progress bar when it's going to send some other
345
# output. Eventually it would be nice to have that automatically
348
self._total_byte_count += byte_count
349
self._bytes_since_update += byte_count
351
if self._total_byte_count < 2000:
352
# a little resistance at first, so it doesn't stay stuck at 0
353
# while connecting...
355
if self._transport_update_time is None:
356
self._transport_update_time = now
357
elif now >= (self._transport_update_time + 0.5):
358
# guard against clock stepping backwards, and don't update too
360
rate = self._bytes_since_update / (now - self._transport_update_time)
361
msg = ("%6dKB %5dKB/s" %
362
(self._total_byte_count>>10, int(rate)>>10,))
363
self._transport_update_time = now
364
self._last_repaint = now
365
self._bytes_since_update = 0
366
self._last_transport_msg = msg