1 import textwrap, getopt
8 def __setitem__(self, k, v):
11 def __getitem__(self, k):
14 def __getattr__(self, k):
19 def __init__(self, exe, optspec):
21 self.optspec = optspec
23 self._shortopts = 'h?'
24 self._longopts = ['help']
26 self._usagestr = self._gen_usage()
30 lines = self.optspec.strip().split('\n')
36 out.append('%s: %s\n' % (first_syn and 'usage' or ' or', l))
42 out.append('\n%s\n' % l.lstrip())
44 (flags, extra) = l.split(' ', 1)
46 if flags.endswith('='):
51 flagl = flags.split(',')
54 self._aliases[f] = flagl[0]
55 self._hasparms[f] = has_parm
57 self._shortopts += f + (has_parm and ':' or '')
58 flagl_nice.append('-' + f)
60 assert(not f.startswith('no-')) # supported implicitly
61 self._longopts.append(f + (has_parm and '=' or ''))
62 self._longopts.append('no-' + f)
63 flagl_nice.append('--' + f)
64 flags_nice = ', '.join(flagl_nice)
67 prefix = ' %-20s ' % flags_nice
68 argtext = '\n'.join(textwrap.wrap(extra, width=70,
69 initial_indent=prefix,
70 subsequent_indent=' '*28))
71 out.append(argtext + '\n')
80 def parse(self, args):
82 (flags,extra) = getopt.gnu_getopt(args,
83 self._shortopts, self._longopts)
84 except getopt.GetoptError, e:
85 log('%s: %s\n' % (self.exe, e))
89 for f in self._aliases.values():
92 while k.startswith('-'):
94 if k in ['h', '?', 'help']:
96 if k.startswith('no-'):
97 k = self._aliases[k[3:]]
101 if not self._hasparms[k]:
103 opt[k] = (opt._opts.get(k) or 0) + 1
106 for (f1,f2) in self._aliases.items():
108 return (opt,flags,extra)