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(), """
37
from bzrlib.ui import (
43
class TextUIFactory(UIFactory):
44
"""A UI factory for Text user interefaces."""
50
"""Create a TextUIFactory.
52
:param bar_type: The type of progress bar to create. It defaults to
53
letting the bzrlib.progress.ProgressBar factory auto
56
super(TextUIFactory, self).__init__()
57
# TODO: there's no good reason not to pass all three streams, maybe we
58
# should deprecate the default values...
62
# paints progress, network activity, etc
63
self._progress_view = self.make_progress_view()
66
"""Prepare the terminal for output.
68
This will, clear any progress bars, and leave the cursor at the
70
# XXX: If this is preparing to write to stdout, but that's for example
71
# directed into a file rather than to the terminal, and the progress
72
# bar _is_ going to the terminal, we shouldn't need
73
# to clear it. We might need to separately check for the case of
74
self._progress_view.clear()
76
def get_boolean(self, prompt):
78
self.prompt(prompt + "? [y/n]: ")
79
line = self.stdin.readline().lower()
80
if line in ('y\n', 'yes\n'):
82
elif line in ('n\n', 'no\n'):
84
elif line in ('', None):
85
# end-of-file; possibly should raise an error here instead
88
def get_non_echoed_password(self):
89
isatty = getattr(self.stdin, 'isatty', None)
90
if isatty is not None and isatty():
91
# getpass() ensure the password is not echoed and other
92
# cross-platform niceties
93
password = getpass.getpass('')
95
# echo doesn't make sense without a terminal
96
password = self.stdin.readline()
99
elif password[-1] == '\n':
100
password = password[:-1]
103
def get_password(self, prompt='', **kwargs):
104
"""Prompt the user for a password.
106
:param prompt: The prompt to present the user
107
:param kwargs: Arguments which will be expanded into the prompt.
108
This lets front ends display different things if
110
:return: The password string, return None if the user
111
canceled the request.
114
self.prompt(prompt, **kwargs)
115
# There's currently no way to say 'i decline to enter a password'
116
# as opposed to 'my password is empty' -- does it matter?
117
return self.get_non_echoed_password()
119
def get_username(self, prompt, **kwargs):
120
"""Prompt the user for a username.
122
:param prompt: The prompt to present the user
123
:param kwargs: Arguments which will be expanded into the prompt.
124
This lets front ends display different things if
126
:return: The username string, return None if the user
127
canceled the request.
130
self.prompt(prompt, **kwargs)
131
username = self.stdin.readline()
134
elif username[-1] == '\n':
135
username = username[:-1]
138
def make_progress_view(self):
139
"""Construct and return a new ProgressView subclass for this UI.
141
# if the user specifically requests either text or no progress bars,
142
# always do that. otherwise, guess based on $TERM and tty presence.
143
if os.environ.get('BZR_PROGRESS_BAR') == 'text':
144
return TextProgressView(self.stderr)
145
elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
146
return NullProgressView()
147
elif progress._supports_progress(self.stderr):
148
return TextProgressView(self.stderr)
150
return NullProgressView()
153
"""Write an already-formatted message, clearing the progress bar if necessary."""
155
self.stdout.write(msg + '\n')
157
def prompt(self, prompt, **kwargs):
158
"""Emit prompt on the CLI.
160
:param kwargs: Dictionary of arguments to insert into the prompt,
161
to allow UIs to reformat the prompt.
164
# See <https://launchpad.net/bugs/365891>
165
prompt = prompt % kwargs
166
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
168
self.stderr.write(prompt)
170
def report_transport_activity(self, transport, byte_count, direction):
171
"""Called by transports as they do IO.
173
This may update a progress bar, spinner, or similar display.
174
By default it does nothing.
176
self._progress_view.show_transport_activity(transport,
177
direction, byte_count)
179
def _progress_updated(self, task):
180
"""A task has been updated and wants to be displayed.
182
if not self._task_stack:
183
warnings.warn("%r updated but no tasks are active" %
185
elif task != self._task_stack[-1]:
186
warnings.warn("%r is not the top progress task %r" %
187
(task, self._task_stack[-1]))
188
self._progress_view.show_progress(task)
190
def _progress_all_finished(self):
191
self._progress_view.clear()
194
class TextProgressView(object):
195
"""Display of progress bar and other information on a tty.
197
This shows one line of text, including possibly a network indicator, spinner,
198
progress bar, message, etc.
200
One instance of this is created and held by the UI, and fed updates when a
201
task wants to be painted.
203
Transports feed data to this through the ui_factory object.
205
The Progress views can comprise a tree with _parent_task pointers, but
206
this only prints the stack from the nominated current task up to the root.
209
def __init__(self, term_file):
210
self._term_file = term_file
211
# true when there's output on the screen we may need to clear
212
self._have_output = False
213
# XXX: We could listen for SIGWINCH and update the terminal width...
214
# https://launchpad.net/bugs/316357
215
self._width = osutils.terminal_width()
216
self._last_transport_msg = ''
218
# time we last repainted the screen
219
self._last_repaint = 0
220
# time we last got information about transport activity
221
self._transport_update_time = 0
222
self._last_task = None
223
self._total_byte_count = 0
224
self._bytes_since_update = 0
226
def _show_line(self, s):
228
self._term_file.write('\r%-*.*s\r' % (n, n, s))
231
if self._have_output:
233
self._have_output = False
235
def _render_bar(self):
236
# return a string for the progress bar itself
237
if (self._last_task is None) or self._last_task.show_bar:
238
# If there's no task object, we show space for the bar anyhow.
239
# That's because most invocations of bzr will end showing progress
240
# at some point, though perhaps only after doing some initial IO.
241
# It looks better to draw the progress bar initially rather than
242
# to have what looks like an incomplete progress bar.
243
spin_str = r'/-\|'[self._spin_pos % 4]
246
if self._last_task is None:
247
completion_fraction = 0
249
completion_fraction = \
250
self._last_task._overall_completion_fraction() or 0
251
markers = int(round(float(cols) * completion_fraction)) - 1
252
bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
254
elif self._last_task.show_spinner:
255
# The last task wanted just a spinner, no bar
256
spin_str = r'/-\|'[self._spin_pos % 4]
258
return spin_str + ' '
262
def _format_task(self, task):
263
if not task.show_count:
265
elif task.current_cnt is not None and task.total_cnt is not None:
266
s = ' %d/%d' % (task.current_cnt, task.total_cnt)
267
elif task.current_cnt is not None:
268
s = ' %d' % (task.current_cnt)
271
# compose all the parent messages
274
while t._parent_task:
280
def _render_line(self):
281
bar_string = self._render_bar()
283
task_msg = self._format_task(self._last_task)
286
trans = self._last_transport_msg
289
return (bar_string + trans + task_msg)
292
s = self._render_line()
294
self._have_output = True
296
def show_progress(self, task):
297
"""Called by the task object when it has changed.
299
:param task: The top task object; its parents are also included
302
must_update = task is not self._last_task
303
self._last_task = task
305
if (not must_update) and (now < self._last_repaint + 0.1):
307
if now > self._transport_update_time + 10:
308
# no recent activity; expire it
309
self._last_transport_msg = ''
310
self._last_repaint = now
313
def show_transport_activity(self, transport, direction, byte_count):
314
"""Called by transports via the ui_factory, as they do IO.
316
This may update a progress bar, spinner, or similar display.
317
By default it does nothing.
319
# XXX: Probably there should be a transport activity model, and that
320
# too should be seen by the progress view, rather than being poked in
322
if not self._have_output:
323
# As a workaround for <https://launchpad.net/bugs/321935> we only
324
# show transport activity when there's already a progress bar
325
# shown, which time the application code is expected to know to
326
# clear off the progress bar when it's going to send some other
327
# output. Eventually it would be nice to have that automatically
330
self._total_byte_count += byte_count
331
self._bytes_since_update += byte_count
333
if self._transport_update_time is None:
334
self._transport_update_time = now
335
elif now >= (self._transport_update_time + 0.5):
336
# guard against clock stepping backwards, and don't update too
338
rate = self._bytes_since_update / (now - self._transport_update_time)
339
msg = ("%6dKB %5dKB/s" %
340
(self._total_byte_count>>10, int(rate)>>10,))
341
self._transport_update_time = now
342
self._last_repaint = now
343
self._bytes_since_update = 0
344
self._last_transport_msg = msg