/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: 2018-02-18 21:42:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6859.
  • Revision ID: jelmer@jelmer.uk-20180218214257-jpevutp1wa30tz3v
Update TODO to reference Breezy, not Bazaar.

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