2010-09-04 07:58:44 +02:00
|
|
|
"""Command-line options parser.
|
|
|
|
With the help of an options spec string, easily parse command-line options.
|
|
|
|
"""
|
2010-09-22 03:03:17 +02:00
|
|
|
import sys, os, textwrap, getopt, re, struct
|
2010-05-01 22:15:37 +02:00
|
|
|
|
|
|
|
class OptDict:
|
|
|
|
def __init__(self):
|
|
|
|
self._opts = {}
|
|
|
|
|
|
|
|
def __setitem__(self, k, v):
|
2010-09-22 03:03:17 +02:00
|
|
|
if k.startswith('no-') or k.startswith('no_'):
|
|
|
|
k = k[3:]
|
|
|
|
v = not v
|
2010-05-01 22:15:37 +02:00
|
|
|
self._opts[k] = v
|
2010-09-04 07:58:44 +02:00
|
|
|
|
2010-05-01 22:15:37 +02:00
|
|
|
def __getitem__(self, k):
|
2010-09-22 03:03:17 +02:00
|
|
|
if k.startswith('no-') or k.startswith('no_'):
|
|
|
|
return not self._opts[k[3:]]
|
2010-05-01 22:15:37 +02:00
|
|
|
return self._opts[k]
|
|
|
|
|
|
|
|
def __getattr__(self, k):
|
|
|
|
return self[k]
|
|
|
|
|
|
|
|
|
2010-09-04 07:58:44 +02:00
|
|
|
def _default_onabort(msg):
|
|
|
|
sys.exit(97)
|
|
|
|
|
|
|
|
|
|
|
|
def _intify(v):
|
|
|
|
try:
|
|
|
|
vv = int(v or '')
|
|
|
|
if str(vv) == v:
|
|
|
|
return vv
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
return v
|
|
|
|
|
|
|
|
|
2010-09-22 03:03:17 +02:00
|
|
|
def _atoi(v):
|
|
|
|
try:
|
|
|
|
return int(v or 0)
|
|
|
|
except ValueError:
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
def _remove_negative_kv(k, v):
|
|
|
|
if k.startswith('no-') or k.startswith('no_'):
|
|
|
|
return k[3:], not v
|
|
|
|
return k,v
|
|
|
|
|
|
|
|
def _remove_negative_k(k):
|
|
|
|
return _remove_negative_kv(k, None)[0]
|
|
|
|
|
|
|
|
|
|
|
|
def _tty_width():
|
|
|
|
s = struct.pack("HHHH", 0, 0, 0, 0)
|
|
|
|
try:
|
|
|
|
import fcntl, termios
|
|
|
|
s = fcntl.ioctl(sys.stderr.fileno(), termios.TIOCGWINSZ, s)
|
|
|
|
except (IOError, ImportError):
|
|
|
|
return _atoi(os.environ.get('WIDTH')) or 70
|
|
|
|
(ysize,xsize,ypix,xpix) = struct.unpack('HHHH', s)
|
2011-01-23 01:42:32 +01:00
|
|
|
return xsize or 70
|
2010-09-22 03:03:17 +02:00
|
|
|
|
|
|
|
|
2010-05-01 22:15:37 +02:00
|
|
|
class Options:
|
2010-09-04 07:58:44 +02:00
|
|
|
"""Option parser.
|
|
|
|
When constructed, two strings are mandatory. The first one is the command
|
|
|
|
name showed before error messages. The second one is a string called an
|
|
|
|
optspec that specifies the synopsis and option flags and their description.
|
|
|
|
For more information about optspecs, consult the bup-options(1) man page.
|
|
|
|
|
|
|
|
Two optional arguments specify an alternative parsing function and an
|
|
|
|
alternative behaviour on abort (after having output the usage string).
|
|
|
|
|
|
|
|
By default, the parser function is getopt.gnu_getopt, and the abort
|
|
|
|
behaviour is to exit the program.
|
|
|
|
"""
|
|
|
|
def __init__(self, exe, optspec, optfunc=getopt.gnu_getopt,
|
|
|
|
onabort=_default_onabort):
|
2010-05-01 22:15:37 +02:00
|
|
|
self.exe = exe
|
|
|
|
self.optspec = optspec
|
2010-09-04 07:58:44 +02:00
|
|
|
self._onabort = onabort
|
2010-05-01 22:15:37 +02:00
|
|
|
self.optfunc = optfunc
|
|
|
|
self._aliases = {}
|
|
|
|
self._shortopts = 'h?'
|
|
|
|
self._longopts = ['help']
|
|
|
|
self._hasparms = {}
|
2010-09-04 07:58:44 +02:00
|
|
|
self._defaults = {}
|
2010-05-01 22:15:37 +02:00
|
|
|
self._usagestr = self._gen_usage()
|
2010-09-04 07:58:44 +02:00
|
|
|
|
2010-05-01 22:15:37 +02:00
|
|
|
def _gen_usage(self):
|
|
|
|
out = []
|
|
|
|
lines = self.optspec.strip().split('\n')
|
|
|
|
lines.reverse()
|
|
|
|
first_syn = True
|
|
|
|
while lines:
|
|
|
|
l = lines.pop()
|
|
|
|
if l == '--': break
|
|
|
|
out.append('%s: %s\n' % (first_syn and 'usage' or ' or', l))
|
|
|
|
first_syn = False
|
|
|
|
out.append('\n')
|
2010-09-22 03:03:17 +02:00
|
|
|
last_was_option = False
|
2010-05-01 22:15:37 +02:00
|
|
|
while lines:
|
|
|
|
l = lines.pop()
|
|
|
|
if l.startswith(' '):
|
2010-09-22 03:03:17 +02:00
|
|
|
out.append('%s%s\n' % (last_was_option and '\n' or '',
|
|
|
|
l.lstrip()))
|
|
|
|
last_was_option = False
|
2010-05-01 22:15:37 +02:00
|
|
|
elif l:
|
|
|
|
(flags, extra) = l.split(' ', 1)
|
|
|
|
extra = extra.strip()
|
|
|
|
if flags.endswith('='):
|
|
|
|
flags = flags[:-1]
|
|
|
|
has_parm = 1
|
|
|
|
else:
|
|
|
|
has_parm = 0
|
2010-09-22 03:03:17 +02:00
|
|
|
g = re.search(r'\[([^\]]*)\]$', extra)
|
2010-09-04 07:58:44 +02:00
|
|
|
if g:
|
|
|
|
defval = g.group(1)
|
|
|
|
else:
|
|
|
|
defval = None
|
2010-05-01 22:15:37 +02:00
|
|
|
flagl = flags.split(',')
|
|
|
|
flagl_nice = []
|
|
|
|
for f in flagl:
|
2010-09-22 03:03:17 +02:00
|
|
|
f,dvi = _remove_negative_kv(f, _intify(defval))
|
|
|
|
self._aliases[f] = _remove_negative_k(flagl[0])
|
2010-05-01 22:15:37 +02:00
|
|
|
self._hasparms[f] = has_parm
|
2010-09-22 03:03:17 +02:00
|
|
|
self._defaults[f] = dvi
|
2010-05-01 22:15:37 +02:00
|
|
|
if len(f) == 1:
|
|
|
|
self._shortopts += f + (has_parm and ':' or '')
|
|
|
|
flagl_nice.append('-' + f)
|
|
|
|
else:
|
2010-09-04 07:58:44 +02:00
|
|
|
f_nice = re.sub(r'\W', '_', f)
|
2010-09-22 03:03:17 +02:00
|
|
|
self._aliases[f_nice] = _remove_negative_k(flagl[0])
|
2010-05-01 22:15:37 +02:00
|
|
|
self._longopts.append(f + (has_parm and '=' or ''))
|
|
|
|
self._longopts.append('no-' + f)
|
|
|
|
flagl_nice.append('--' + f)
|
|
|
|
flags_nice = ', '.join(flagl_nice)
|
|
|
|
if has_parm:
|
|
|
|
flags_nice += ' ...'
|
|
|
|
prefix = ' %-20s ' % flags_nice
|
2010-09-22 03:03:17 +02:00
|
|
|
argtext = '\n'.join(textwrap.wrap(extra, width=_tty_width(),
|
2010-05-01 22:15:37 +02:00
|
|
|
initial_indent=prefix,
|
|
|
|
subsequent_indent=' '*28))
|
|
|
|
out.append(argtext + '\n')
|
2010-09-22 03:03:17 +02:00
|
|
|
last_was_option = True
|
2010-05-01 22:15:37 +02:00
|
|
|
else:
|
|
|
|
out.append('\n')
|
2010-09-22 03:03:17 +02:00
|
|
|
last_was_option = False
|
2010-05-01 22:15:37 +02:00
|
|
|
return ''.join(out).rstrip() + '\n'
|
2010-09-04 07:58:44 +02:00
|
|
|
|
|
|
|
def usage(self, msg=""):
|
|
|
|
"""Print usage string to stderr and abort."""
|
2010-05-01 22:15:37 +02:00
|
|
|
sys.stderr.write(self._usagestr)
|
2010-09-04 07:58:44 +02:00
|
|
|
e = self._onabort and self._onabort(msg) or None
|
|
|
|
if e:
|
|
|
|
raise e
|
2010-05-01 22:15:37 +02:00
|
|
|
|
|
|
|
def fatal(self, s):
|
2010-09-04 07:58:44 +02:00
|
|
|
"""Print an error message to stderr and abort with usage string."""
|
|
|
|
msg = 'error: %s\n' % s
|
|
|
|
sys.stderr.write(msg)
|
|
|
|
return self.usage(msg)
|
|
|
|
|
2010-05-01 22:15:37 +02:00
|
|
|
def parse(self, args):
|
2010-09-04 07:58:44 +02:00
|
|
|
"""Parse a list of arguments and return (options, flags, extra).
|
|
|
|
|
|
|
|
In the returned tuple, "options" is an OptDict with known options,
|
|
|
|
"flags" is a list of option flags that were used on the command-line,
|
|
|
|
and "extra" is a list of positional arguments.
|
|
|
|
"""
|
2010-05-01 22:15:37 +02:00
|
|
|
try:
|
|
|
|
(flags,extra) = self.optfunc(args, self._shortopts, self._longopts)
|
|
|
|
except getopt.GetoptError, e:
|
|
|
|
self.fatal(e)
|
|
|
|
|
|
|
|
opt = OptDict()
|
2010-09-04 07:58:44 +02:00
|
|
|
|
|
|
|
for k,v in self._defaults.iteritems():
|
|
|
|
k = self._aliases[k]
|
|
|
|
opt[k] = v
|
|
|
|
|
2010-05-01 22:15:37 +02:00
|
|
|
for (k,v) in flags:
|
2010-09-04 07:58:44 +02:00
|
|
|
k = k.lstrip('-')
|
|
|
|
if k in ('h', '?', 'help'):
|
2010-05-01 22:15:37 +02:00
|
|
|
self.usage()
|
|
|
|
if k.startswith('no-'):
|
|
|
|
k = self._aliases[k[3:]]
|
2010-09-04 07:58:44 +02:00
|
|
|
v = 0
|
2010-05-01 22:15:37 +02:00
|
|
|
else:
|
|
|
|
k = self._aliases[k]
|
|
|
|
if not self._hasparms[k]:
|
|
|
|
assert(v == '')
|
2010-09-04 07:58:44 +02:00
|
|
|
v = (opt._opts.get(k) or 0) + 1
|
2010-05-01 22:15:37 +02:00
|
|
|
else:
|
2010-09-04 07:58:44 +02:00
|
|
|
v = _intify(v)
|
|
|
|
opt[k] = v
|
|
|
|
for (f1,f2) in self._aliases.iteritems():
|
|
|
|
opt[f1] = opt._opts.get(f2)
|
2010-05-01 22:15:37 +02:00
|
|
|
return (opt,flags,extra)
|