~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Jelmer Vernooij
  • Date: 2012-02-20 12:19:29 UTC
  • mfrom: (6437.23.11 2.5)
  • mto: (6581.1.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 6582.
  • Revision ID: jelmer@samba.org-20120220121929-7ni2psvjoatm1yp4
Merge bzr/2.5.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
"""Text UI, write output to the console.
19
19
"""
20
20
 
 
21
from __future__ import absolute_import
 
22
 
21
23
import os
22
24
import sys
23
25
import time
43
45
    )
44
46
 
45
47
 
 
48
class _ChooseUI(object):
 
49
 
 
50
    """ Helper class for choose implementation.
 
51
    """
 
52
 
 
53
    def __init__(self, ui, msg, choices, default):
 
54
        self.ui = ui
 
55
        self._setup_mode()
 
56
        self._build_alternatives(msg, choices, default)
 
57
 
 
58
    def _setup_mode(self):
 
59
        """Setup input mode (line-based, char-based) and echo-back.
 
60
 
 
61
        Line-based input is used if the BZR_TEXTUI_INPUT environment
 
62
        variable is set to 'line-based', or if there is no controlling
 
63
        terminal.
 
64
        """
 
65
        if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
 
66
           self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
 
67
            self.line_based = False
 
68
            self.echo_back = True
 
69
        else:
 
70
            self.line_based = True
 
71
            self.echo_back = not self.ui.stdin.isatty()
 
72
 
 
73
    def _build_alternatives(self, msg, choices, default):
 
74
        """Parse choices string.
 
75
 
 
76
        Setup final prompt and the lists of choices and associated
 
77
        shortcuts.
 
78
        """
 
79
        index = 0
 
80
        help_list = []
 
81
        self.alternatives = {}
 
82
        choices = choices.split('\n')
 
83
        if default is not None and default not in range(0, len(choices)):
 
84
            raise ValueError("invalid default index")
 
85
        for c in choices:
 
86
            name = c.replace('&', '').lower()
 
87
            choice = (name, index)
 
88
            if name in self.alternatives:
 
89
                raise ValueError("duplicated choice: %s" % name)
 
90
            self.alternatives[name] = choice
 
91
            shortcut = c.find('&')
 
92
            if -1 != shortcut and (shortcut + 1) < len(c):
 
93
                help = c[:shortcut]
 
94
                help += '[' + c[shortcut + 1] + ']'
 
95
                help += c[(shortcut + 2):]
 
96
                shortcut = c[shortcut + 1]
 
97
            else:
 
98
                c = c.replace('&', '')
 
99
                shortcut = c[0]
 
100
                help = '[%s]%s' % (shortcut, c[1:])
 
101
            shortcut = shortcut.lower()
 
102
            if shortcut in self.alternatives:
 
103
                raise ValueError("duplicated shortcut: %s" % shortcut)
 
104
            self.alternatives[shortcut] = choice
 
105
            # Add redirections for default.
 
106
            if index == default:
 
107
                self.alternatives[''] = choice
 
108
                self.alternatives['\r'] = choice
 
109
            help_list.append(help)
 
110
            index += 1
 
111
 
 
112
        self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
 
113
 
 
114
    def _getline(self):
 
115
        line = self.ui.stdin.readline()
 
116
        if '' == line:
 
117
            raise EOFError
 
118
        return line.strip()
 
119
 
 
120
    def _getchar(self):
 
121
        char = osutils.getchar()
 
122
        if char == chr(3): # INTR
 
123
            raise KeyboardInterrupt
 
124
        if char == chr(4): # EOF (^d, C-d)
 
125
            raise EOFError
 
126
        return char
 
127
 
 
128
    def interact(self):
 
129
        """Keep asking the user until a valid choice is made.
 
130
        """
 
131
        if self.line_based:
 
132
            getchoice = self._getline
 
133
        else:
 
134
            getchoice = self._getchar
 
135
        iter = 0
 
136
        while True:
 
137
            iter += 1
 
138
            if 1 == iter or self.line_based:
 
139
                self.ui.prompt(self.prompt)
 
140
            try:
 
141
                choice = getchoice()
 
142
            except EOFError:
 
143
                self.ui.stderr.write('\n')
 
144
                return None
 
145
            except KeyboardInterrupt:
 
146
                self.ui.stderr.write('\n')
 
147
                raise KeyboardInterrupt
 
148
            choice = choice.lower()
 
149
            if choice not in self.alternatives:
 
150
                # Not a valid choice, keep on asking.
 
151
                continue
 
152
            name, index = self.alternatives[choice]
 
153
            if self.echo_back:
 
154
                self.ui.stderr.write(name + '\n')
 
155
            return index
 
156
 
 
157
 
46
158
class TextUIFactory(UIFactory):
47
159
    """A UI factory for Text user interefaces."""
48
160
 
61
173
        # paints progress, network activity, etc
62
174
        self._progress_view = self.make_progress_view()
63
175
 
 
176
    def choose(self, msg, choices, default=None):
 
177
        """Prompt the user for a list of alternatives.
 
178
 
 
179
        Support both line-based and char-based editing.
 
180
 
 
181
        In line-based mode, both the shortcut and full choice name are valid
 
182
        answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
 
183
        'YES ' are all valid input lines for choosing 'yes'.
 
184
 
 
185
        An empty line, when in line-based mode, or pressing enter in char-based
 
186
        mode will select the default choice (if any).
 
187
 
 
188
        Choice is echoed back if:
 
189
        - input is char-based; which means a controlling terminal is available,
 
190
          and osutils.getchar is used
 
191
        - input is line-based, and no controlling terminal is available
 
192
        """
 
193
 
 
194
        choose_ui = _ChooseUI(self, msg, choices, default)
 
195
        return choose_ui.interact()
 
196
 
64
197
    def be_quiet(self, state):
65
198
        if state and not self._quiet:
66
199
            self.clear_term()
78
211
        # to clear it.  We might need to separately check for the case of
79
212
        self._progress_view.clear()
80
213
 
81
 
    def get_boolean(self, prompt):
82
 
        while True:
83
 
            self.prompt(prompt + "? [y/n]: ")
84
 
            line = self.stdin.readline().lower()
85
 
            if line in ('y\n', 'yes\n'):
86
 
                return True
87
 
            elif line in ('n\n', 'no\n'):
88
 
                return False
89
 
            elif line in ('', None):
90
 
                # end-of-file; possibly should raise an error here instead
91
 
                return None
92
 
 
93
214
    def get_integer(self, prompt):
94
215
        while True:
95
216
            self.prompt(prompt)
205
326
            prompt = prompt % kwargs
206
327
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
207
328
        self.clear_term()
 
329
        self.stdout.flush()
208
330
        self.stderr.write(prompt)
209
331
 
210
332
    def report_transport_activity(self, transport, byte_count, direction):