~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/__init__.py

  • Committer: Vincent Ladeuil
  • Date: 2009-07-15 07:34:23 UTC
  • mfrom: (4503.2.6 bool-config-option)
  • mto: This revision was merged to the branch mainline in revision 4537.
  • Revision ID: v.ladeuil+lp@free.fr-20090715073423-ri6ms86pfwxfoop8
Support boolean variables in configuration files and UI queries

Show diffs side-by-side

added added

removed removed

Lines of Context:
43
43
""")
44
44
 
45
45
 
 
46
_valid_boolean_strings = dict(yes=True, no=False,
 
47
                              y=True, n=False,
 
48
                              on=True, off=False,
 
49
                              true=True, false=False)
 
50
_valid_boolean_strings['1'] = True
 
51
_valid_boolean_strings['0'] = False
 
52
 
 
53
 
 
54
def bool_from_string(s, accepted_values=None):
 
55
    """Returns a boolean if the string can be interpreted as such.
 
56
 
 
57
    Interpret case insensitive strings as booleans. The default values
 
58
    includes: 'yes', 'no, 'y', 'n', 'true', 'false', '0', '1', 'on',
 
59
    'off'. Alternative values can be provided with the 'accepted_values'
 
60
    parameter.
 
61
 
 
62
    :param s: A string that should be interpreted as a boolean. It should be of
 
63
        type string or unicode.
 
64
 
 
65
    :param accepted_values: An optional dict with accepted strings as keys and
 
66
        True/False as values. The strings will be tested against a lowered
 
67
        version of 's'.
 
68
 
 
69
    :return: True or False for accepted strings, None otherwise.
 
70
    """
 
71
    if accepted_values is None:
 
72
        accepted_values = _valid_boolean_strings
 
73
    val = None
 
74
    if type(s) in (str, unicode):
 
75
        try:
 
76
            val = accepted_values[s.lower()]
 
77
        except KeyError:
 
78
            pass
 
79
    return val
 
80
 
 
81
 
46
82
class UIFactory(object):
47
83
    """UI abstraction.
48
84
 
156
192
        self.stdout = stdout or sys.stdout
157
193
        self.stderr = stderr or sys.stderr
158
194
 
 
195
    _accepted_boolean_strings = dict(y=True, n=False, yes=True, no=False)
 
196
 
159
197
    def get_boolean(self, prompt):
160
198
        while True:
161
199
            self.prompt(prompt + "? [y/n]: ")
162
200
            line = self.stdin.readline()
163
 
            line = line.lower()
164
 
            if line in ('y\n', 'yes\n'):
165
 
                return True
166
 
            if line in ('n\n', 'no\n'):
167
 
                return False
 
201
            line = line.rstrip('\n')
 
202
            val = bool_from_string(line, self._accepted_boolean_strings)
 
203
            if val is not None:
 
204
                return val
168
205
 
169
206
    def get_non_echoed_password(self):
170
207
        isatty = getattr(self.stdin, 'isatty', None)