260: Option.normalize() now does same conversion for multivalue as Option.convert() does

This commit is contained in:
Jason Gerard DeRose 2008-09-04 08:16:12 +00:00
parent c7cd694d4f
commit 915486dadc
3 changed files with 27 additions and 17 deletions

View File

@ -26,6 +26,7 @@ import sys
import code
import optparse
import public
import errors
def to_cli(name):
@ -161,14 +162,14 @@ class CLI(object):
while True:
if error is not None:
print '>>> %s: %s' % (option.name, error)
value = raw_input(prompt)
if default is not None and len(value) == 0:
value = default
if len(value) == 0:
error = 'Must supply a value'
else:
raw = raw_input(prompt)
try:
value = option(raw)
if value is not None:
kw[option.name] = value
break
except errors.ValidationError, e:
error = e.error
cmd(*args, **kw)

View File

@ -127,15 +127,18 @@ class Option(plugable.ReadOnly):
def __normalize_scalar(self, value):
if not isinstance(value, basestring):
raise_TypeError(value, basestring, 'value')
try:
return self.__normalize(value)
except Exception:
return value
def normalize(self, value):
if self.__normalize is None:
return value
if self.multivalue:
if type(value) is not tuple:
raise_TypeError(value, tuple, 'value')
if type(value) in (tuple, list):
return tuple(self.__normalize_scalar(v) for v in value)
return (self.__normalize_scalar(value),) # tuple
return self.__normalize_scalar(value)
def __validate_scalar(self, value, index=None):
@ -170,10 +173,18 @@ class Option(plugable.ReadOnly):
return tuple()
def __call__(self, value, **kw):
if value in ('', tuple(), []):
value = None
if value is None:
value = self.get_default(**kw)
if value is None:
if self.required:
raise RequirementError(option.name)
return None
else:
pass
class Command(plugable.Plugin):
__public__ = frozenset((
'get_default',

View File

@ -215,12 +215,10 @@ class test_Option(ClassChecker):
# Scenario 4: multivalue=True, normalize=callback
o = self.cls(name, doc, t, multivalue=True, normalize=callback)
for value in [(u'Hello',), (u'hello',)]: # Okay
for value in [(u'Hello',), (u'hello',), 'Hello', ['Hello']]: # Okay
assert o.normalize(value) == (u'hello',)
for v in (None, u'Hello', [u'hello']): # Not tuple
check_TypeError(v, tuple, 'value', o.normalize, v)
fail = 42 # Not basestring
for v in [(fail,), (u'Hello', fail)]: # Non unicode member
for v in [fail, [fail], (u'Hello', fail)]: # Non unicode member
check_TypeError(fail, basestring, 'value', o.normalize, v)
def test_validate(self):