~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Samuel Bronson
  • Date: 2012-08-30 20:36:18 UTC
  • mto: (6015.57.3 2.4)
  • mto: This revision was merged to the branch mainline in revision 6558.
  • Revision ID: naesten@gmail.com-20120830203618-y2dzw91nqpvpgxvx
Update INSTALL for switch to Python 2.6 and up.

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
 
 
23
21
import os
24
22
import sys
25
23
import time
45
43
    )
46
44
 
47
45
 
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
 
 
158
46
class TextUIFactory(UIFactory):
159
47
    """A UI factory for Text user interefaces."""
160
48
 
173
61
        # paints progress, network activity, etc
174
62
        self._progress_view = self.make_progress_view()
175
63
 
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
 
 
197
64
    def be_quiet(self, state):
198
65
        if state and not self._quiet:
199
66
            self.clear_term()
211
78
        # to clear it.  We might need to separately check for the case of
212
79
        self._progress_view.clear()
213
80
 
 
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
 
214
93
    def get_integer(self, prompt):
215
94
        while True:
216
95
            self.prompt(prompt)
326
205
            prompt = prompt % kwargs
327
206
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
328
207
        self.clear_term()
329
 
        self.stdout.flush()
330
208
        self.stderr.write(prompt)
331
209
 
332
210
    def report_transport_activity(self, transport, byte_count, direction):