/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/ui/text.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-08 23:30:31 UTC
  • mto: This revision was merged to the branch mainline in revision 6690.
  • Revision ID: jelmer@jelmer.uk-20170608233031-3qavls2o7a1pqllj
Update imports.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Text UI, write output to the console."""
18
18
 
 
19
from __future__ import absolute_import
 
20
 
19
21
import codecs
20
 
import io
21
22
import os
22
23
import sys
23
24
import warnings
61
62
        variable is set to 'line-based', or if there is no controlling
62
63
        terminal.
63
64
        """
64
 
        is_tty = self.ui.raw_stdin.isatty()
65
 
        if (os.environ.get('BRZ_TEXTUI_INPUT') != 'line-based' and
66
 
                self.ui.raw_stdin == _unwrap_stream(sys.stdin) and is_tty):
 
65
        if os.environ.get('BRZ_TEXTUI_INPUT') != 'line-based' and \
 
66
           self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
67
67
            self.line_based = False
68
68
            self.echo_back = True
69
69
        else:
70
70
            self.line_based = True
71
 
            self.echo_back = not is_tty
 
71
            self.echo_back = not self.ui.stdin.isatty()
72
72
 
73
73
    def _build_alternatives(self, msg, choices, default):
74
74
        """Parse choices string.
119
119
 
120
120
    def _getchar(self):
121
121
        char = osutils.getchar()
122
 
        if char == chr(3):  # INTR
 
122
        if char == chr(3): # INTR
123
123
            raise KeyboardInterrupt
124
 
        if char == chr(4):  # EOF (^d, C-d)
 
124
        if char == chr(4): # EOF (^d, C-d)
125
125
            raise EOFError
126
 
        if isinstance(char, bytes):
127
 
            return char.decode('ascii', 'replace')
128
 
        return char
 
126
        return char.decode("ascii", "replace")
129
127
 
130
128
    def interact(self):
131
129
        """Keep asking the user until a valid choice is made.
172
170
        self.stdin = stdin
173
171
        self.stdout = stdout
174
172
        self.stderr = stderr
175
 
        self._progress_view = NullProgressView()
176
 
 
177
 
    def __enter__(self):
178
 
        # Choose default encoding and handle py2/3 differences
179
 
        self._setup_streams()
180
173
        # paints progress, network activity, etc
181
174
        self._progress_view = self.make_progress_view()
182
 
        return self
183
 
 
184
 
    def _setup_streams(self):
185
 
        self.raw_stdin = _unwrap_stream(self.stdin)
186
 
        self.stdin = _wrap_in_stream(self.raw_stdin)
187
 
        self.raw_stdout = _unwrap_stream(self.stdout)
188
 
        self.stdout = _wrap_out_stream(self.raw_stdout)
189
 
        self.raw_stderr = _unwrap_stream(self.stderr)
190
 
        self.stderr = _wrap_out_stream(self.raw_stderr)
191
175
 
192
176
    def choose(self, msg, choices, default=None):
193
177
        """Prompt the user for a list of alternatives.
298
282
        if self.is_quiet():
299
283
            return NullProgressView()
300
284
        pb_type = config.GlobalStack().get('progress_bar')
301
 
        if pb_type == 'none':  # Explicit requirement
 
285
        if pb_type == 'none': # Explicit requirement
302
286
            return NullProgressView()
303
 
        if (pb_type == 'text' or # Explicit requirement
304
 
                progress._supports_progress(self.stderr)):  # Guess
 
287
        if (pb_type == 'text' # Explicit requirement
 
288
            or progress._supports_progress(self.stderr)): # Guess
305
289
            return TextProgressView(self.stderr)
306
290
        # No explicit requirement and no successful guess
307
291
        return NullProgressView()
320
304
        :param kwargs: Dictionary of arguments to insert into the prompt,
321
305
            to allow UIs to reformat the prompt.
322
306
        """
323
 
        if not isinstance(prompt, str):
 
307
        if not isinstance(prompt, unicode):
324
308
            raise ValueError("prompt %r not a unicode string" % prompt)
325
309
        if kwargs:
326
310
            # See <https://launchpad.net/bugs/365891>
328
312
        self.clear_term()
329
313
        self.stdout.flush()
330
314
        self.stderr.write(prompt)
331
 
        self.stderr.flush()
332
315
 
333
316
    def report_transport_activity(self, transport, byte_count, direction):
334
317
        """Called by transports as they do IO.
337
320
        By default it does nothing.
338
321
        """
339
322
        self._progress_view.show_transport_activity(transport,
340
 
                                                    direction, byte_count)
 
323
            direction, byte_count)
341
324
 
342
325
    def log_transport_activity(self, display=False):
343
326
        """See UIFactory.log_transport_activity()"""
361
344
        """
362
345
        if not self._task_stack:
363
346
            warnings.warn("%r updated but no tasks are active" %
364
 
                          (task,))
 
347
                (task,))
365
348
        elif task != self._task_stack[-1]:
366
349
            # We used to check it was the top task, but it's hard to always
367
350
            # get this right and it's not necessarily useful: any actual
368
351
            # problems will be evident in use
369
 
            # warnings.warn("%r is not the top progress task %r" %
 
352
            #warnings.warn("%r is not the top progress task %r" %
370
353
            #     (task, self._task_stack[-1]))
371
354
            pass
372
355
        self._progress_view.show_progress(task)
458
441
    def _render_bar(self):
459
442
        # return a string for the progress bar itself
460
443
        if self.enable_bar and (
461
 
                (self._last_task is None) or self._last_task.show_bar):
 
444
            (self._last_task is None) or self._last_task.show_bar):
462
445
            # If there's no task object, we show space for the bar anyhow.
463
446
            # That's because most invocations of bzr will end showing progress
464
447
            # at some point, though perhaps only after doing some initial IO.
465
448
            # It looks better to draw the progress bar initially rather than
466
449
            # to have what looks like an incomplete progress bar.
467
 
            spin_str = r'/-\|'[self._spin_pos % 4]
 
450
            spin_str =  r'/-\|'[self._spin_pos % 4]
468
451
            self._spin_pos += 1
469
452
            cols = 20
470
453
            if self._last_task is None:
474
457
                completion_fraction = \
475
458
                    self._last_task._overall_completion_fraction() or 0
476
459
            if (completion_fraction < self._fraction and 'progress' in
477
 
                    debug.debug_flags):
 
460
                debug.debug_flags):
478
461
                debug.set_trace()
479
462
            self._fraction = completion_fraction
480
463
            markers = int(round(float(cols) * completion_fraction)) - 1
482
465
            return bar_str
483
466
        elif (self._last_task is None) or self._last_task.show_spinner:
484
467
            # The last task wanted just a spinner, no bar
485
 
            spin_str = r'/-\|'[self._spin_pos % 4]
 
468
            spin_str =  r'/-\|'[self._spin_pos % 4]
486
469
            self._spin_pos += 1
487
470
            return spin_str + ' '
488
471
        else:
530
513
        avail_width = self._avail_width()
531
514
        if avail_width is not None:
532
515
            # if terminal avail_width is unknown, don't truncate
533
 
            current_len = len(bar_string) + len(trans) + \
534
 
                len(task_part) + len(counter_part)
 
516
            current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
535
517
            # GZ 2017-04-22: Should measure and truncate task_part properly
536
518
            gap = current_len - avail_width
537
519
            if gap > 0:
538
 
                task_part = task_part[:-gap - 2] + '..'
 
520
                task_part = task_part[:-gap-2] + '..'
539
521
        s = trans + bar_string + task_part + counter_part
540
522
        if avail_width is not None:
541
523
            if len(s) < avail_width:
601
583
        elif now >= (self._transport_update_time + 0.5):
602
584
            # guard against clock stepping backwards, and don't update too
603
585
            # often
604
 
            rate = (self._bytes_since_update /
605
 
                    (now - self._transport_update_time))
 
586
            rate = (self._bytes_since_update
 
587
                    / (now - self._transport_update_time))
606
588
            # using base-10 units (see HACKING.txt).
607
589
            msg = ("%6dkB %5dkB/s " %
608
 
                   (self._total_byte_count / 1000, int(rate) / 1000,))
 
590
                    (self._total_byte_count / 1000, int(rate) / 1000,))
609
591
            self._transport_update_time = now
610
592
            self._last_repaint = now
611
593
            self._bytes_since_update = 0
628
610
                  bps / 1000.,
629
611
                  self._bytes_by_direction['read'] / 1000.,
630
612
                  self._bytes_by_direction['write'] / 1000.,
631
 
                  ))
 
613
                 ))
632
614
        if self._bytes_by_direction['unknown'] > 0:
633
615
            msg += ' u:%.0fkB)' % (
634
616
                self._bytes_by_direction['unknown'] / 1000.
657
639
def _unwrap_stream(stream):
658
640
    inner = getattr(stream, "buffer", None)
659
641
    if inner is None:
660
 
        inner = getattr(stream, "stream", stream)
 
642
        inner = getattr(stream, "stream", None)
661
643
    return inner
662
644
 
663
645
 
664
646
def _wrap_in_stream(stream, encoding=None, errors='replace'):
665
647
    if encoding is None:
666
648
        encoding = _get_stream_encoding(stream)
667
 
    # Attempt to wrap using io.open if possible, since that can do
668
 
    # line-buffering.
669
 
    try:
670
 
        fileno = stream.fileno()
671
 
    except io.UnsupportedOperation:
672
 
        encoded_stream = codecs.getreader(encoding)(stream, errors=errors)
673
 
        encoded_stream.encoding = encoding
674
 
        return encoded_stream
675
 
    else:
676
 
        return io.open(fileno, encoding=encoding, errors=errors, mode='r', buffering=1)
 
649
    encoded_stream = codecs.getreader(encoding)(stream, errors=errors)
 
650
    encoded_stream.encoding = encoding
 
651
    return encoded_stream
677
652
 
678
653
 
679
654
def _wrap_out_stream(stream, encoding=None, errors='replace'):