203
203
yield self.name, self.short_name(), argname, self.help
206
class RegistryOption(Option):
207
"""Option based on a registry
209
The values for the options correspond to entries in the registry. Input
210
must be a registry key. After validation, it is converted into an object
211
using Registry.get or a caller-provided converter.
214
def validate_value(self, value):
215
"""Validate a value name"""
216
if value not in self.registry:
217
raise errors.BadOptionValue(self.name, value)
219
def convert(self, value):
220
"""Convert a value name into an output type"""
221
self.validate_value(value)
222
if self.converter is None:
223
return self.registry.get(value)
225
return self.converter(value)
227
def __init__(self, name, help, registry, converter=None,
228
value_switches=False):
232
:param name: The option name.
233
:param help: Help for the option.
234
:param registry: A Registry containing the values
235
:param converter: Callable to invoke with the value name to produce
236
the value. If not supplied, self.registry.get is used.
237
:param value_switches: If true, each possible value is assigned its
238
own switch. For example, instead of '--format metaweave',
239
'--metaweave' can be used interchangeably.
241
Option.__init__(self, name, help, type=self.convert)
242
self.registry = registry
244
self.converter = converter
245
self.value_switches = value_switches
247
def add_option(self, parser, short_name):
248
"""Add this option to an Optparse parser"""
249
Option.add_option(self, parser, short_name)
250
if self.value_switches:
251
for key in self.registry.keys():
252
option_strings = ['--%s' % key]
253
parser.add_option(action='callback',
254
callback=self._optparse_value_callback(key),
255
help=self.registry.get_help(key),
258
def _optparse_value_callback(self, cb_value):
259
def cb(option, opt, value, parser):
260
setattr(parser.values, self.name, self.type(cb_value))
263
def iter_switches(self):
264
"""Iterate through the list of switches provided by the option
266
:return: an iterator of (name, short_name, argname, help)
268
for value in Option.iter_switches(self):
270
if self.value_switches:
271
for key in sorted(self.registry.keys()):
272
yield key, None, None, self.registry.get_help(key)
206
275
class OptionParser(optparse.OptionParser):
207
276
"""OptionParser that raises exceptions instead of exiting"""