1 import textwrap, getopt, re
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 f_nice = re.sub(r'\W', '_', f)
55 self._aliases[f] = flagl[0]
56 self._aliases[f_nice] = flagl[0]
57 self._hasparms[f] = has_parm
59 self._shortopts += f + (has_parm and ':' or '')
60 flagl_nice.append('-' + f)
62 assert(not f.startswith('no-')) # supported implicitly
63 self._longopts.append(f + (has_parm and '=' or ''))
64 self._longopts.append('no-' + f)
65 flagl_nice.append('--' + f)
66 flags_nice = ', '.join(flagl_nice)
69 prefix = ' %-20s ' % flags_nice
70 argtext = '\n'.join(textwrap.wrap(extra, width=70,
71 initial_indent=prefix,
72 subsequent_indent=' '*28))
73 out.append(argtext + '\n')
76 return ''.join(out).rstrip() + '\n'
83 log('error: %s\n' % s)
86 def parse(self, args):
88 (flags,extra) = getopt.gnu_getopt(args,
89 self._shortopts, self._longopts)
90 except getopt.GetoptError, e:
94 for f in self._aliases.values():
97 while k.startswith('-'):
99 if k in ['h', '?', 'help']:
101 if k.startswith('no-'):
102 k = self._aliases[k[3:]]
106 if not self._hasparms[k]:
108 opt[k] = (opt._opts.get(k) or 0) + 1
117 for (f1,f2) in self._aliases.items():
119 return (opt,flags,extra)