0001# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
0002# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
0003"""
0004A subclass of ``optparse.OptionParser`` that allows boolean long
0005options (like ``--verbose``) to also take arguments (like
0006``--verbose=true``).  Arguments *must* use ``=``.
0007"""
0008
0009import optparse
0010try:
0011    _ = optparse._
0012except AttributeError:
0013    from gettext import gettext as _
0014
0015class BoolOptionParser(optparse.OptionParser):
0016
0017    def _process_long_opt(self, rargs, values):
0018        arg = rargs.pop(0)
0019
0020        # Value explicitly attached to arg?  Pretend it's the next
0021        # argument.
0022        if "=" in arg:
0023            (opt, next_arg) = arg.split("=", 1)
0024            rargs.insert(0, next_arg)
0025            had_explicit_value = True
0026        else:
0027            opt = arg
0028            had_explicit_value = False
0029
0030        opt = self._match_long_opt(opt)
0031        option = self._long_opt[opt]
0032        if option.takes_value():
0033            nargs = option.nargs
0034            if len(rargs) < nargs:
0035                if nargs == 1:
0036                    self.error(_("%s option requires an argument") % opt)
0037                else:
0038                    self.error(_("%s option requires %d arguments")
0039                               % (opt, nargs))
0040            elif nargs == 1:
0041                value = rargs.pop(0)
0042            else:
0043                value = tuple(rargs[0:nargs])
0044                del rargs[0:nargs]
0045
0046        elif had_explicit_value:
0047            value = rargs[0].lower().strip()
0048            del rargs[0:1]
0049            if value in ('true', 'yes', 'on', '1', 'y', 't'):
0050                value = None
0051            elif value in ('false', 'no', 'off', '0', 'n', 'f'):
0052                # Don't process
0053                return
0054            else:
0055                self.error(_('%s option takes a boolean value only (true/false)') % opt)
0056
0057        else:
0058            value = None
0059
0060        option.process(opt, value, values, self)