blob: a593354c9d1483ef659a511071b35056a175d9f8 [file] [log] [blame]
Greg Ward2689e3d1999-03-22 14:52:19 +00001"""distutils.fancy_getopt
2
3Wrapper around the standard getopt module that provides the following
4additional features:
5 * short and long options are tied together
6 * options have help strings, so fancy_getopt could potentially
7 create a complete usage summary
8 * options set attributes of a passed-in object
9"""
10
11# created 1999/03/03, Greg Ward
12
Greg Ward3ce77fd2000-03-02 01:49:45 +000013__revision__ = "$Id$"
Greg Ward2689e3d1999-03-22 14:52:19 +000014
Greg Ward44f8e4e1999-12-12 16:54:55 +000015import sys, string, re
Greg Ward2689e3d1999-03-22 14:52:19 +000016from types import *
17import getopt
18from distutils.errors import *
19
20# Much like command_re in distutils.core, this is close to but not quite
21# the same as a Python NAME -- except, in the spirit of most GNU
22# utilities, we use '-' in place of '_'. (The spirit of LISP lives on!)
23# The similarities to NAME are again not a coincidence...
Greg Warda564cc31999-10-03 20:48:53 +000024longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'
25longopt_re = re.compile (r'^%s$' % longopt_pat)
26
27# For recognizing "negative alias" options, eg. "quiet=!verbose"
28neg_alias_re = re.compile ("^(%s)=!(%s)$" % (longopt_pat, longopt_pat))
29
Greg Ward2689e3d1999-03-22 14:52:19 +000030# This is used to translate long options to legitimate Python identifiers
31# (for use as attributes of some object).
32longopt_xlate = string.maketrans ('-', '_')
33
Greg Wardffc10d92000-04-21 01:41:54 +000034# This records (option, value) pairs in the order seen on the command line;
35# it's close to what getopt.getopt() returns, but with short options
36# expanded. (Ugh, this module should be OO-ified.)
37_option_order = None
38
39
40class FancyGetopt:
41 """Wrapper around the standard 'getopt()' module that provides some
42 handy extra functionality:
43 * short and long options are tied together
44 * options have help strings, and help text can be assembled
45 from them
46 * options set attributes of a passed-in object
47 * boolean options can have "negative aliases" -- eg. if
48 --quiet is the "negative alias" of --verbose, then "--quiet"
49 on the command line sets 'verbose' to false
50 """
51
52 def __init__ (self, option_table=None):
53
54 # The option table is (currently) a list of 3-tuples:
55 # (long_option, short_option, help_string)
56 # if an option takes an argument, its long_option should have '='
57 # appended; short_option should just be a single character, no ':'
58 # in any case. If a long_option doesn't have a corresponding
59 # short_option, short_option should be None. All option tuples
60 # must have long options.
61 self.option_table = option_table
62
63 # 'option_index' maps long option names to entries in the option
64 # table (ie. those 3-tuples).
65 self.option_index = {}
66 if self.option_table:
Greg Ward283c7452000-04-21 02:09:26 +000067 self._build_index()
Greg Wardffc10d92000-04-21 01:41:54 +000068
Greg Ward1e7b5092000-04-21 04:22:01 +000069 # 'alias' records (duh) alias options; {'foo': 'bar'} means
70 # --foo is an alias for --bar
71 self.alias = {}
72
Greg Wardffc10d92000-04-21 01:41:54 +000073 # 'negative_alias' keeps track of options that are the boolean
74 # opposite of some other option
75 self.negative_alias = {}
76
77 # These keep track of the information in the option table. We
78 # don't actually populate these structures until we're ready to
79 # parse the command-line, since the 'option_table' passed in here
80 # isn't necessarily the final word.
81 self.short_opts = []
82 self.long_opts = []
83 self.short2long = {}
84 self.attr_name = {}
85 self.takes_arg = {}
86
87 # And 'option_order' is filled up in 'getopt()'; it records the
88 # original order of options (and their values) on the command-line,
89 # but expands short options, converts aliases, etc.
90 self.option_order = []
91
92 # __init__ ()
93
94
Greg Ward283c7452000-04-21 02:09:26 +000095 def _build_index (self):
Greg Wardffc10d92000-04-21 01:41:54 +000096 for option in self.option_table:
97 self.option_index[option[0]] = option
98
Greg Ward283c7452000-04-21 02:09:26 +000099 def set_option_table (self, option_table):
100 self.option_table = option_table
101 self._build_index()
102
Greg Wardffc10d92000-04-21 01:41:54 +0000103 def add_option (self, long_option, short_option=None, help_string=None):
104 if self.option_index.has_key(long_option):
105 raise DistutilsGetoptError, \
106 "option conflict: already an option '%s'" % long_option
107 else:
108 option = (long_option, short_option, help_string)
109 self.option_table.append (option)
110 self.option_index[long_option] = option
111
Greg Ward320df702000-04-21 02:31:07 +0000112
113 def has_option (self, long_option):
114 """Return true if the option table for this parser has an
115 option with long name 'long_option'."""
116 return self.option_index.has_key(long_option)
117
118 def get_attr_name (self, long_option):
119 """Translate long option name 'long_option' to the form it
120 has as an attribute of some object: ie., translate hyphens
121 to underscores."""
122 return string.translate (long_option, longopt_xlate)
123
124
Greg Ward1e7b5092000-04-21 04:22:01 +0000125 def _check_alias_dict (self, aliases, what):
126 assert type(aliases) is DictionaryType
127 for (alias, opt) in aliases.items():
128 if not self.option_index.has_key(alias):
129 raise DistutilsGetoptError, \
130 ("invalid %s '%s': "
131 "option '%s' not defined") % (what, alias, alias)
132 if not self.option_index.has_key(opt):
133 raise DistutilsGetoptError, \
134 ("invalid %s '%s': "
135 "aliased option '%s' not defined") % (what, alias, opt)
136
137 def set_aliases (self, alias):
138 """Set the aliases for this option parser."""
139 self._check_alias_dict (alias, "alias")
140 self.alias = alias
141
Greg Wardffc10d92000-04-21 01:41:54 +0000142 def set_negative_aliases (self, negative_alias):
143 """Set the negative aliases for this option parser.
144 'negative_alias' should be a dictionary mapping option names to
145 option names, both the key and value must already be defined
146 in the option table."""
Greg Ward1e7b5092000-04-21 04:22:01 +0000147 self._check_alias_dict (negative_alias, "negative alias")
Greg Wardffc10d92000-04-21 01:41:54 +0000148 self.negative_alias = negative_alias
149
150
151 def _grok_option_table (self):
152 """Populate the various data structures that keep tabs on
153 the option table. Called by 'getopt()' before it can do
154 anything worthwhile."""
155
156 for option in self.option_table:
157 try:
158 (long, short, help) = option
159 except ValueError:
160 raise DistutilsGetoptError, \
161 "invalid option tuple " + str (option)
162
163 # Type- and value-check the option names
164 if type(long) is not StringType or len(long) < 2:
165 raise DistutilsGetoptError, \
166 ("invalid long option '%s': "
167 "must be a string of length >= 2") % long
168
169 if (not ((short is None) or
170 (type (short) is StringType and len (short) == 1))):
171 raise DistutilsGetoptError, \
172 ("invalid short option '%s': "
173 "must a single character or None") % short
174
175 self.long_opts.append (long)
176
177 if long[-1] == '=': # option takes an argument?
178 if short: short = short + ':'
179 long = long[0:-1]
180 self.takes_arg[long] = 1
181 else:
182
183 # Is option is a "negative alias" for some other option (eg.
184 # "quiet" == "!verbose")?
185 alias_to = self.negative_alias.get(long)
186 if alias_to is not None:
187 if self.takes_arg[alias_to]:
188 raise DistutilsGetoptError, \
189 ("invalid negative alias '%s': "
190 "aliased option '%s' takes a value") % \
191 (long, alias_to)
192
193 self.long_opts[-1] = long # XXX redundant?!
194 self.takes_arg[long] = 0
195
196 else:
197 self.takes_arg[long] = 0
198
Greg Ward1e7b5092000-04-21 04:22:01 +0000199 # If this is an alias option, make sure its "takes arg" flag is
200 # the same as the option it's aliased to.
201 alias_to = self.alias.get(long)
202 if alias_to is not None:
203 if self.takes_arg[long] != self.takes_arg[alias_to]:
204 raise DistutilsGetoptError, \
205 ("invalid alias '%s': inconsistent with "
206 "aliased option '%s' (one of them takes a value, "
207 "the other doesn't") % (long, alias_to)
208
Greg Wardffc10d92000-04-21 01:41:54 +0000209
210 # Now enforce some bondage on the long option name, so we can
211 # later translate it to an attribute name on some object. Have
212 # to do this a bit late to make sure we've removed any trailing
213 # '='.
214 if not longopt_re.match (long):
215 raise DistutilsGetoptError, \
216 ("invalid long option name '%s' " +
217 "(must be letters, numbers, hyphens only") % long
218
Greg Ward320df702000-04-21 02:31:07 +0000219 self.attr_name[long] = self.get_attr_name (long)
Greg Wardffc10d92000-04-21 01:41:54 +0000220 if short:
221 self.short_opts.append (short)
222 self.short2long[short[0]] = long
223
224 # for option_table
225
226 # _grok_option_table()
227
228
229 def getopt (self, args=None, object=None):
Greg Wardffc10d92000-04-21 01:41:54 +0000230 """Parse the command-line options in 'args' and store the results
231 as attributes of 'object'. If 'args' is None or not supplied, uses
232 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new
233 OptionDummy object, stores option values there, and returns a tuple
234 (args, object). If 'object' is supplied, it is modified in place
235 and 'getopt()' just returns 'args'; in both cases, the returned
236 'args' is a modified copy of the passed-in 'args' list, which is
237 left untouched."""
238
239 if args is None:
240 args = sys.argv[1:]
241 if object is None:
Greg Ward981f7362000-05-23 03:53:10 +0000242 object = OptionDummy()
Greg Wardffc10d92000-04-21 01:41:54 +0000243 created_object = 1
244 else:
245 created_object = 0
246
247 self._grok_option_table()
248
249 short_opts = string.join (self.short_opts)
250 try:
251 (opts, args) = getopt.getopt (args, short_opts, self.long_opts)
252 except getopt.error, msg:
253 raise DistutilsArgError, msg
254
255 for (opt, val) in opts:
256 if len (opt) == 2 and opt[0] == '-': # it's a short option
257 opt = self.short2long[opt[1]]
258
259 elif len (opt) > 2 and opt[0:2] == '--':
260 opt = opt[2:]
261
262 else:
263 raise DistutilsInternalError, \
264 "this can't happen: bad option string '%s'" % opt
265
Greg Ward1e7b5092000-04-21 04:22:01 +0000266 alias = self.alias.get(opt)
267 if alias:
268 opt = alias
269
Greg Wardffc10d92000-04-21 01:41:54 +0000270 if not self.takes_arg[opt]: # boolean option?
271 if val != '': # shouldn't have a value!
272 raise DistutilsInternalError, \
273 "this can't happen: bad option value '%s'" % value
274
275 alias = self.negative_alias.get (opt)
276 if alias:
277 opt = alias
278 val = 0
279 else:
280 val = 1
281
282 attr = self.attr_name[opt]
283 setattr (object, attr, val)
284 self.option_order.append ((opt, val))
285
286 # for opts
287
288 if created_object:
289 return (args, object)
290 else:
291 return args
292
293 # getopt()
294
295
Greg Ward283c7452000-04-21 02:09:26 +0000296 def get_option_order (self):
Greg Wardffc10d92000-04-21 01:41:54 +0000297 """Returns the list of (option, value) tuples processed by the
Greg Ward283c7452000-04-21 02:09:26 +0000298 previous run of 'getopt()'. Raises RuntimeError if
299 'getopt()' hasn't been called yet."""
Greg Wardffc10d92000-04-21 01:41:54 +0000300
301 if self.option_order is None:
Greg Ward283c7452000-04-21 02:09:26 +0000302 raise RuntimeError, "'getopt()' hasn't been called yet"
Greg Wardffc10d92000-04-21 01:41:54 +0000303 else:
304 return self.option_order
305
Greg Ward283c7452000-04-21 02:09:26 +0000306
Greg Ward66bf4462000-04-23 02:50:45 +0000307 def generate_help (self, header=None):
Greg Ward283c7452000-04-21 02:09:26 +0000308 """Generate help text (a list of strings, one per suggested line of
309 output) from the option table for this FancyGetopt object."""
310
311 # Blithely assume the option table is good: probably wouldn't call
312 # 'generate_help()' unless you've already called 'getopt()'.
313
314 # First pass: determine maximum length of long option names
315 max_opt = 0
316 for option in self.option_table:
317 long = option[0]
318 short = option[1]
319 l = len (long)
320 if long[-1] == '=':
321 l = l - 1
322 if short is not None:
323 l = l + 5 # " (-x)" where short == 'x'
324 if l > max_opt:
325 max_opt = l
326
327 opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
328
329 # Typical help block looks like this:
330 # --foo controls foonabulation
331 # Help block for longest option looks like this:
332 # --flimflam set the flim-flam level
333 # and with wrapped text:
334 # --flimflam set the flim-flam level (must be between
335 # 0 and 100, except on Tuesdays)
336 # Options with short names will have the short name shown (but
337 # it doesn't contribute to max_opt):
338 # --foo (-f) controls foonabulation
339 # If adding the short option would make the left column too wide,
340 # we push the explanation off to the next line
341 # --flimflam (-l)
342 # set the flim-flam level
343 # Important parameters:
344 # - 2 spaces before option block start lines
345 # - 2 dashes for each long option name
346 # - min. 2 spaces between option and explanation (gutter)
347 # - 5 characters (incl. space) for short option name
348
349 # Now generate lines of help text. (If 80 columns were good enough
350 # for Jesus, then 78 columns are good enough for me!)
351 line_width = 78
352 text_width = line_width - opt_width
353 big_indent = ' ' * opt_width
354 if header:
355 lines = [header]
356 else:
357 lines = ['Option summary:']
358
359 for (long,short,help) in self.option_table:
360
361 text = wrap_text (help, text_width)
362 if long[-1] == '=':
363 long = long[0:-1]
364
365 # Case 1: no short option at all (makes life easy)
366 if short is None:
367 if text:
368 lines.append (" --%-*s %s" % (max_opt, long, text[0]))
369 else:
370 lines.append (" --%-*s " % (max_opt, long))
371
372 for l in text[1:]:
373 lines.append (big_indent + l)
374
375 # Case 2: we have a short option, so we have to include it
376 # just after the long option
377 else:
378 opt_names = "%s (-%s)" % (long, short)
379 if text:
380 lines.append (" --%-*s %s" %
381 (max_opt, opt_names, text[0]))
382 else:
383 lines.append (" --%-*s" % opt_names)
384
385 # for self.option_table
386
387 return lines
388
389 # generate_help ()
390
Greg Ward66bf4462000-04-23 02:50:45 +0000391 def print_help (self, header=None, file=None):
Greg Ward283c7452000-04-21 02:09:26 +0000392 if file is None:
393 file = sys.stdout
394 for line in self.generate_help (header):
395 file.write (line + "\n")
396 # print_help ()
397
Greg Wardffc10d92000-04-21 01:41:54 +0000398# class FancyGetopt
399
Greg Ward2689e3d1999-03-22 14:52:19 +0000400
Greg Ward44f8e4e1999-12-12 16:54:55 +0000401def fancy_getopt (options, negative_opt, object, args):
Greg Wardffc10d92000-04-21 01:41:54 +0000402 parser = FancyGetopt (options)
403 parser.set_negative_aliases (negative_opt)
404 return parser.getopt (args, object)
405
406
Greg Ward44f8e4e1999-12-12 16:54:55 +0000407WS_TRANS = string.maketrans (string.whitespace, ' ' * len (string.whitespace))
408
409def wrap_text (text, width):
410
411 if text is None:
412 return []
413 if len (text) <= width:
414 return [text]
415
416 text = string.expandtabs (text)
417 text = string.translate (text, WS_TRANS)
418 chunks = re.split (r'( +|-+)', text)
419 chunks = filter (None, chunks) # ' - ' results in empty strings
420 lines = []
421
422 while chunks:
423
424 cur_line = [] # list of chunks (to-be-joined)
425 cur_len = 0 # length of current line
426
427 while chunks:
428 l = len (chunks[0])
429 if cur_len + l <= width: # can squeeze (at least) this chunk in
430 cur_line.append (chunks[0])
431 del chunks[0]
432 cur_len = cur_len + l
433 else: # this line is full
434 # drop last chunk if all space
435 if cur_line and cur_line[-1][0] == ' ':
436 del cur_line[-1]
437 break
438
439 if chunks: # any chunks left to process?
440
441 # if the current line is still empty, then we had a single
442 # chunk that's too big too fit on a line -- so we break
443 # down and break it up at the line width
444 if cur_len == 0:
445 cur_line.append (chunks[0][0:width])
446 chunks[0] = chunks[0][width:]
447
448 # all-whitespace chunks at the end of a line can be discarded
449 # (and we know from the re.split above that if a chunk has
450 # *any* whitespace, it is *all* whitespace)
451 if chunks[0][0] == ' ':
452 del chunks[0]
453
454 # and store this line in the list-of-all-lines -- as a single
455 # string, of course!
456 lines.append (string.join (cur_line, ''))
457
458 # while chunks
459
460 return lines
461
462# wrap_text ()
463
464
Greg Wardffc10d92000-04-21 01:41:54 +0000465class OptionDummy:
466 """Dummy class just used as a place to hold command-line option
467 values as instance attributes."""
Greg Ward3c67b1d2000-05-23 01:44:20 +0000468
469 def __init__ (self, options=[]):
470 """Create a new OptionDummy instance. The attributes listed in
471 'options' will be initialized to None."""
472 for opt in options:
473 setattr(self, opt, None)
474
475# class OptionDummy
Greg Ward44f8e4e1999-12-12 16:54:55 +0000476
477
478if __name__ == "__main__":
479 text = """\
480Tra-la-la, supercalifragilisticexpialidocious.
481How *do* you spell that odd word, anyways?
482(Someone ask Mary -- she'll know [or she'll
483say, "How should I know?"].)"""
484
485 for w in (10, 20, 30, 40):
486 print "width: %d" % w
487 print string.join (wrap_text (text, w), "\n")
488 print