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