153
154
if option is self:
157
def get_negation_name(self):
158
if self.name.startswith('no-'):
161
return 'no-' + self.name
163
def add_option(self, parser, short_name):
164
"""Add this option to an Optparse parser"""
165
option_strings = ['--%s' % self.name]
166
if short_name is not None:
167
option_strings.append('-%s' % short_name)
170
parser.add_option(action='store_true', dest=self.name,
172
default=OptionParser.DEFAULT_VALUE,
174
negation_strings = ['--%s' % self.get_negation_name()]
175
parser.add_option(action='store_false', dest=self.name,
176
help=optparse.SUPPRESS_HELP, *negation_strings)
178
parser.add_option(action='callback',
179
callback=self._optparse_callback,
180
type='string', metavar=self.argname.upper(),
182
default=OptionParser.DEFAULT_VALUE,
185
def _optparse_callback(self, option, opt, value, parser):
186
setattr(parser.values, self.name, self.type(value))
188
def iter_switches(self):
189
"""Iterate through the list of switches provided by the option
191
:return: an iterator of (name, short_name, argname, help)
193
argname = self.argname
194
if argname is not None:
195
argname = argname.upper()
196
yield self.name, self.short_name(), argname, self.help
199
class OptionParser(optparse.OptionParser):
200
"""OptionParser that raises exceptions instead of exiting"""
202
DEFAULT_VALUE = object()
204
def error(self, message):
205
raise BzrCommandError(message)
208
def get_optparser(options):
209
"""Generate an optparse parser for bzrlib-style options"""
211
parser = OptionParser()
212
parser.remove_option('--help')
213
short_options = dict((k.name, v) for v, k in
214
Option.SHORT_OPTIONS.iteritems())
215
for option in options.itervalues():
216
option.add_option(parser, short_options.get(option.name))
157
220
def _global_option(name, **kwargs):
158
221
"""Register o as a global option."""