blob: 73343ad5afa14e1a9943b1f8f769cc626948dda3 [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
Greg Ward3ce77fd2000-03-02 01:49:45 +000011__revision__ = "$Id$"
Greg Ward2689e3d1999-03-22 14:52:19 +000012
Tarek Ziadé88e2c5d2009-12-21 01:49:00 +000013import sys
14import string
15import re
Greg Ward2689e3d1999-03-22 14:52:19 +000016import getopt
Tarek Ziadé88e2c5d2009-12-21 01:49:00 +000017from distutils.errors import DistutilsGetoptError, DistutilsArgError
Greg Ward2689e3d1999-03-22 14:52:19 +000018
19# Much like command_re in distutils.core, this is close to but not quite
20# the same as a Python NAME -- except, in the spirit of most GNU
21# utilities, we use '-' in place of '_'. (The spirit of LISP lives on!)
22# The similarities to NAME are again not a coincidence...
Greg Warda564cc31999-10-03 20:48:53 +000023longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'
Greg Ward071ed762000-09-26 02:12:31 +000024longopt_re = re.compile(r'^%s$' % longopt_pat)
Greg Warda564cc31999-10-03 20:48:53 +000025
26# For recognizing "negative alias" options, eg. "quiet=!verbose"
Greg Ward071ed762000-09-26 02:12:31 +000027neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat))
Greg Warda564cc31999-10-03 20:48:53 +000028
Greg Ward2689e3d1999-03-22 14:52:19 +000029# This is used to translate long options to legitimate Python identifiers
30# (for use as attributes of some object).
Tarek Ziadé03d5d082009-09-21 13:01:54 +000031longopt_xlate = str.maketrans('-', '_')
Greg Ward2689e3d1999-03-22 14:52:19 +000032
Greg Wardffc10d92000-04-21 01:41:54 +000033class FancyGetopt:
34 """Wrapper around the standard 'getopt()' module that provides some
35 handy extra functionality:
36 * short and long options are tied together
37 * options have help strings, and help text can be assembled
38 from them
39 * options set attributes of a passed-in object
40 * boolean options can have "negative aliases" -- eg. if
41 --quiet is the "negative alias" of --verbose, then "--quiet"
42 on the command line sets 'verbose' to false
43 """
44
Collin Winter5b7e9d72007-08-30 03:52:21 +000045 def __init__(self, option_table=None):
Fred Drake576298d2004-08-02 17:58:51 +000046 # The option table is (currently) a list of tuples. The
47 # tuples may have 3 or four values:
48 # (long_option, short_option, help_string [, repeatable])
Greg Wardffc10d92000-04-21 01:41:54 +000049 # if an option takes an argument, its long_option should have '='
50 # appended; short_option should just be a single character, no ':'
51 # in any case. If a long_option doesn't have a corresponding
52 # short_option, short_option should be None. All option tuples
53 # must have long options.
54 self.option_table = option_table
55
56 # 'option_index' maps long option names to entries in the option
57 # table (ie. those 3-tuples).
58 self.option_index = {}
59 if self.option_table:
Greg Ward283c7452000-04-21 02:09:26 +000060 self._build_index()
Greg Wardffc10d92000-04-21 01:41:54 +000061
Greg Ward1e7b5092000-04-21 04:22:01 +000062 # 'alias' records (duh) alias options; {'foo': 'bar'} means
63 # --foo is an alias for --bar
64 self.alias = {}
65
Greg Wardffc10d92000-04-21 01:41:54 +000066 # 'negative_alias' keeps track of options that are the boolean
67 # opposite of some other option
68 self.negative_alias = {}
Fred Drakeb94b8492001-12-06 20:51:35 +000069
Greg Wardffc10d92000-04-21 01:41:54 +000070 # These keep track of the information in the option table. We
71 # don't actually populate these structures until we're ready to
72 # parse the command-line, since the 'option_table' passed in here
73 # isn't necessarily the final word.
74 self.short_opts = []
75 self.long_opts = []
76 self.short2long = {}
77 self.attr_name = {}
78 self.takes_arg = {}
79
80 # And 'option_order' is filled up in 'getopt()'; it records the
81 # original order of options (and their values) on the command-line,
82 # but expands short options, converts aliases, etc.
83 self.option_order = []
84
Collin Winter5b7e9d72007-08-30 03:52:21 +000085 def _build_index(self):
Greg Ward0fd2dd62000-08-07 00:45:51 +000086 self.option_index.clear()
Greg Wardffc10d92000-04-21 01:41:54 +000087 for option in self.option_table:
88 self.option_index[option[0]] = option
89
Collin Winter5b7e9d72007-08-30 03:52:21 +000090 def set_option_table(self, option_table):
Greg Ward283c7452000-04-21 02:09:26 +000091 self.option_table = option_table
92 self._build_index()
93
Collin Winter5b7e9d72007-08-30 03:52:21 +000094 def add_option(self, long_option, short_option=None, help_string=None):
Guido van Rossume2b70bc2006-08-18 22:13:04 +000095 if long_option in self.option_index:
Collin Winter5b7e9d72007-08-30 03:52:21 +000096 raise DistutilsGetoptError(
97 "option conflict: already an option '%s'" % long_option)
Greg Wardffc10d92000-04-21 01:41:54 +000098 else:
99 option = (long_option, short_option, help_string)
Greg Ward071ed762000-09-26 02:12:31 +0000100 self.option_table.append(option)
Greg Wardffc10d92000-04-21 01:41:54 +0000101 self.option_index[long_option] = option
102
Collin Winter5b7e9d72007-08-30 03:52:21 +0000103 def has_option(self, long_option):
Greg Ward320df702000-04-21 02:31:07 +0000104 """Return true if the option table for this parser has an
105 option with long name 'long_option'."""
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000106 return long_option in self.option_index
Greg Ward320df702000-04-21 02:31:07 +0000107
Collin Winter5b7e9d72007-08-30 03:52:21 +0000108 def get_attr_name(self, long_option):
Fred Drakeb94b8492001-12-06 20:51:35 +0000109 """Translate long option name 'long_option' to the form it
Greg Ward320df702000-04-21 02:31:07 +0000110 has as an attribute of some object: ie., translate hyphens
111 to underscores."""
Tarek Ziadé03d5d082009-09-21 13:01:54 +0000112 return long_option.translate(longopt_xlate)
Greg Ward320df702000-04-21 02:31:07 +0000113
Collin Winter5b7e9d72007-08-30 03:52:21 +0000114 def _check_alias_dict(self, aliases, what):
115 assert isinstance(aliases, dict)
Greg Ward1e7b5092000-04-21 04:22:01 +0000116 for (alias, opt) in aliases.items():
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000117 if alias not in self.option_index:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000118 raise DistutilsGetoptError(("invalid %s '%s': "
119 "option '%s' not defined") % (what, alias, alias))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000120 if opt not in self.option_index:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000121 raise DistutilsGetoptError(("invalid %s '%s': "
122 "aliased option '%s' not defined") % (what, alias, opt))
Fred Drakeb94b8492001-12-06 20:51:35 +0000123
Collin Winter5b7e9d72007-08-30 03:52:21 +0000124 def set_aliases(self, alias):
Greg Ward1e7b5092000-04-21 04:22:01 +0000125 """Set the aliases for this option parser."""
Greg Ward071ed762000-09-26 02:12:31 +0000126 self._check_alias_dict(alias, "alias")
Greg Ward1e7b5092000-04-21 04:22:01 +0000127 self.alias = alias
128
Collin Winter5b7e9d72007-08-30 03:52:21 +0000129 def set_negative_aliases(self, negative_alias):
Greg Wardffc10d92000-04-21 01:41:54 +0000130 """Set the negative aliases for this option parser.
131 'negative_alias' should be a dictionary mapping option names to
132 option names, both the key and value must already be defined
133 in the option table."""
Greg Ward071ed762000-09-26 02:12:31 +0000134 self._check_alias_dict(negative_alias, "negative alias")
Greg Wardffc10d92000-04-21 01:41:54 +0000135 self.negative_alias = negative_alias
136
Collin Winter5b7e9d72007-08-30 03:52:21 +0000137 def _grok_option_table(self):
Greg Ward071ed762000-09-26 02:12:31 +0000138 """Populate the various data structures that keep tabs on the
139 option table. Called by 'getopt()' before it can do anything
140 worthwhile.
141 """
Greg Ward0fd2dd62000-08-07 00:45:51 +0000142 self.long_opts = []
143 self.short_opts = []
144 self.short2long.clear()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000145 self.repeat = {}
Greg Ward0fd2dd62000-08-07 00:45:51 +0000146
Greg Wardffc10d92000-04-21 01:41:54 +0000147 for option in self.option_table:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000148 if len(option) == 3:
149 long, short, help = option
150 repeat = 0
151 elif len(option) == 4:
152 long, short, help, repeat = option
153 else:
154 # the option table is part of the code, so simply
155 # assert that it is correct
Collin Winter5b7e9d72007-08-30 03:52:21 +0000156 raise ValueError("invalid option tuple: %r" % (option,))
Greg Wardffc10d92000-04-21 01:41:54 +0000157
158 # Type- and value-check the option names
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000159 if not isinstance(long, str) or len(long) < 2:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000160 raise DistutilsGetoptError(("invalid long option '%s': "
161 "must be a string of length >= 2") % long)
Greg Wardffc10d92000-04-21 01:41:54 +0000162
163 if (not ((short is None) or
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000164 (isinstance(short, str) and len(short) == 1))):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000165 raise DistutilsGetoptError("invalid short option '%s': "
166 "must a single character or None" % short)
Greg Wardffc10d92000-04-21 01:41:54 +0000167
Jeremy Hyltona181ec02002-06-04 20:24:05 +0000168 self.repeat[long] = repeat
Greg Ward071ed762000-09-26 02:12:31 +0000169 self.long_opts.append(long)
Greg Wardffc10d92000-04-21 01:41:54 +0000170
171 if long[-1] == '=': # option takes an argument?
172 if short: short = short + ':'
173 long = long[0:-1]
174 self.takes_arg[long] = 1
175 else:
Greg Wardffc10d92000-04-21 01:41:54 +0000176 # Is option is a "negative alias" for some other option (eg.
177 # "quiet" == "!verbose")?
178 alias_to = self.negative_alias.get(long)
179 if alias_to is not None:
180 if self.takes_arg[alias_to]:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000181 raise DistutilsGetoptError(
182 "invalid negative alias '%s': "
183 "aliased option '%s' takes a value"
184 % (long, alias_to))
Greg Wardffc10d92000-04-21 01:41:54 +0000185
186 self.long_opts[-1] = long # XXX redundant?!
Collin Winter5b7e9d72007-08-30 03:52:21 +0000187 self.takes_arg[long] = 0
Greg Wardffc10d92000-04-21 01:41:54 +0000188
Greg Ward1e7b5092000-04-21 04:22:01 +0000189 # If this is an alias option, make sure its "takes arg" flag is
190 # the same as the option it's aliased to.
191 alias_to = self.alias.get(long)
192 if alias_to is not None:
193 if self.takes_arg[long] != self.takes_arg[alias_to]:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000194 raise DistutilsGetoptError(
195 "invalid alias '%s': inconsistent with "
196 "aliased option '%s' (one of them takes a value, "
197 "the other doesn't"
198 % (long, alias_to))
Greg Wardffc10d92000-04-21 01:41:54 +0000199
200 # Now enforce some bondage on the long option name, so we can
201 # later translate it to an attribute name on some object. Have
202 # to do this a bit late to make sure we've removed any trailing
203 # '='.
Greg Ward071ed762000-09-26 02:12:31 +0000204 if not longopt_re.match(long):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000205 raise DistutilsGetoptError(
206 "invalid long option name '%s' "
207 "(must be letters, numbers, hyphens only" % long)
Greg Wardffc10d92000-04-21 01:41:54 +0000208
Greg Ward071ed762000-09-26 02:12:31 +0000209 self.attr_name[long] = self.get_attr_name(long)
Greg Wardffc10d92000-04-21 01:41:54 +0000210 if short:
Greg Ward071ed762000-09-26 02:12:31 +0000211 self.short_opts.append(short)
Greg Wardffc10d92000-04-21 01:41:54 +0000212 self.short2long[short[0]] = long
213
Collin Winter5b7e9d72007-08-30 03:52:21 +0000214 def getopt(self, args=None, object=None):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000215 """Parse command-line options in args. Store as attributes on object.
216
217 If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
218 'object' is None or not supplied, creates a new OptionDummy
219 object, stores option values there, and returns a tuple (args,
220 object). If 'object' is supplied, it is modified in place and
221 'getopt()' just returns 'args'; in both cases, the returned
222 'args' is a modified copy of the passed-in 'args' list, which
223 is left untouched.
Greg Ward071ed762000-09-26 02:12:31 +0000224 """
Greg Wardffc10d92000-04-21 01:41:54 +0000225 if args is None:
226 args = sys.argv[1:]
227 if object is None:
Greg Ward981f7362000-05-23 03:53:10 +0000228 object = OptionDummy()
Collin Winter5b7e9d72007-08-30 03:52:21 +0000229 created_object = True
Greg Wardffc10d92000-04-21 01:41:54 +0000230 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000231 created_object = False
Greg Wardffc10d92000-04-21 01:41:54 +0000232
233 self._grok_option_table()
234
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000235 short_opts = ' '.join(self.short_opts)
Greg Wardffc10d92000-04-21 01:41:54 +0000236 try:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000237 opts, args = getopt.getopt(args, short_opts, self.long_opts)
Guido van Rossumb940e112007-01-10 16:19:56 +0000238 except getopt.error as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000239 raise DistutilsArgError(msg)
Greg Wardffc10d92000-04-21 01:41:54 +0000240
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000241 for opt, val in opts:
Greg Ward071ed762000-09-26 02:12:31 +0000242 if len(opt) == 2 and opt[0] == '-': # it's a short option
Greg Wardffc10d92000-04-21 01:41:54 +0000243 opt = self.short2long[opt[1]]
Greg Wardffc10d92000-04-21 01:41:54 +0000244 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000245 assert len(opt) > 2 and opt[:2] == '--'
246 opt = opt[2:]
Greg Wardffc10d92000-04-21 01:41:54 +0000247
Greg Ward1e7b5092000-04-21 04:22:01 +0000248 alias = self.alias.get(opt)
249 if alias:
250 opt = alias
251
Greg Wardffc10d92000-04-21 01:41:54 +0000252 if not self.takes_arg[opt]: # boolean option?
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000253 assert val == '', "boolean option can't have value"
Greg Ward071ed762000-09-26 02:12:31 +0000254 alias = self.negative_alias.get(opt)
Greg Wardffc10d92000-04-21 01:41:54 +0000255 if alias:
256 opt = alias
257 val = 0
258 else:
259 val = 1
260
261 attr = self.attr_name[opt]
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000262 # The only repeating option at the moment is 'verbose'.
263 # It has a negative option -q quiet, which should set verbose = 0.
264 if val and self.repeat.get(attr) is not None:
265 val = getattr(object, attr, 0) + 1
Greg Ward071ed762000-09-26 02:12:31 +0000266 setattr(object, attr, val)
267 self.option_order.append((opt, val))
Greg Wardffc10d92000-04-21 01:41:54 +0000268
269 # for opts
Greg Wardffc10d92000-04-21 01:41:54 +0000270 if created_object:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000271 return args, object
Greg Wardffc10d92000-04-21 01:41:54 +0000272 else:
273 return args
274
Collin Winter5b7e9d72007-08-30 03:52:21 +0000275 def get_option_order(self):
Greg Wardffc10d92000-04-21 01:41:54 +0000276 """Returns the list of (option, value) tuples processed by the
Greg Ward283c7452000-04-21 02:09:26 +0000277 previous run of 'getopt()'. Raises RuntimeError if
Greg Ward071ed762000-09-26 02:12:31 +0000278 'getopt()' hasn't been called yet.
279 """
Greg Wardffc10d92000-04-21 01:41:54 +0000280 if self.option_order is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000281 raise RuntimeError("'getopt()' hasn't been called yet")
Greg Wardffc10d92000-04-21 01:41:54 +0000282 else:
283 return self.option_order
284
Collin Winter5b7e9d72007-08-30 03:52:21 +0000285 def generate_help(self, header=None):
Greg Ward283c7452000-04-21 02:09:26 +0000286 """Generate help text (a list of strings, one per suggested line of
Greg Ward071ed762000-09-26 02:12:31 +0000287 output) from the option table for this FancyGetopt object.
288 """
Greg Ward283c7452000-04-21 02:09:26 +0000289 # Blithely assume the option table is good: probably wouldn't call
290 # 'generate_help()' unless you've already called 'getopt()'.
291
292 # First pass: determine maximum length of long option names
293 max_opt = 0
294 for option in self.option_table:
295 long = option[0]
296 short = option[1]
Greg Ward071ed762000-09-26 02:12:31 +0000297 l = len(long)
Greg Ward283c7452000-04-21 02:09:26 +0000298 if long[-1] == '=':
299 l = l - 1
300 if short is not None:
301 l = l + 5 # " (-x)" where short == 'x'
302 if l > max_opt:
303 max_opt = l
304
305 opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
306
307 # Typical help block looks like this:
308 # --foo controls foonabulation
309 # Help block for longest option looks like this:
310 # --flimflam set the flim-flam level
311 # and with wrapped text:
312 # --flimflam set the flim-flam level (must be between
313 # 0 and 100, except on Tuesdays)
314 # Options with short names will have the short name shown (but
315 # it doesn't contribute to max_opt):
316 # --foo (-f) controls foonabulation
317 # If adding the short option would make the left column too wide,
318 # we push the explanation off to the next line
319 # --flimflam (-l)
320 # set the flim-flam level
321 # Important parameters:
322 # - 2 spaces before option block start lines
323 # - 2 dashes for each long option name
324 # - min. 2 spaces between option and explanation (gutter)
325 # - 5 characters (incl. space) for short option name
326
327 # Now generate lines of help text. (If 80 columns were good enough
328 # for Jesus, then 78 columns are good enough for me!)
329 line_width = 78
330 text_width = line_width - opt_width
331 big_indent = ' ' * opt_width
332 if header:
333 lines = [header]
334 else:
335 lines = ['Option summary:']
336
Jeremy Hylton40ebbef2002-06-04 21:10:35 +0000337 for option in self.option_table:
Jeremy Hylton8f787bf2002-06-04 21:11:56 +0000338 long, short, help = option[:3]
Greg Ward071ed762000-09-26 02:12:31 +0000339 text = wrap_text(help, text_width)
Greg Ward283c7452000-04-21 02:09:26 +0000340 if long[-1] == '=':
341 long = long[0:-1]
342
343 # Case 1: no short option at all (makes life easy)
344 if short is None:
345 if text:
Greg Ward071ed762000-09-26 02:12:31 +0000346 lines.append(" --%-*s %s" % (max_opt, long, text[0]))
Greg Ward283c7452000-04-21 02:09:26 +0000347 else:
Greg Ward071ed762000-09-26 02:12:31 +0000348 lines.append(" --%-*s " % (max_opt, long))
Greg Ward283c7452000-04-21 02:09:26 +0000349
Greg Ward283c7452000-04-21 02:09:26 +0000350 # Case 2: we have a short option, so we have to include it
351 # just after the long option
352 else:
353 opt_names = "%s (-%s)" % (long, short)
354 if text:
Greg Ward071ed762000-09-26 02:12:31 +0000355 lines.append(" --%-*s %s" %
356 (max_opt, opt_names, text[0]))
Greg Ward283c7452000-04-21 02:09:26 +0000357 else:
Greg Ward071ed762000-09-26 02:12:31 +0000358 lines.append(" --%-*s" % opt_names)
Greg Ward283c7452000-04-21 02:09:26 +0000359
Greg Ward373dbfa2000-06-08 00:35:33 +0000360 for l in text[1:]:
Greg Ward071ed762000-09-26 02:12:31 +0000361 lines.append(big_indent + l)
Greg Ward283c7452000-04-21 02:09:26 +0000362 return lines
363
Collin Winter5b7e9d72007-08-30 03:52:21 +0000364 def print_help(self, header=None, file=None):
Greg Ward283c7452000-04-21 02:09:26 +0000365 if file is None:
366 file = sys.stdout
Greg Ward071ed762000-09-26 02:12:31 +0000367 for line in self.generate_help(header):
368 file.write(line + "\n")
Greg Ward283c7452000-04-21 02:09:26 +0000369
Greg Wardffc10d92000-04-21 01:41:54 +0000370
Collin Winter5b7e9d72007-08-30 03:52:21 +0000371def fancy_getopt(options, negative_opt, object, args):
Greg Ward071ed762000-09-26 02:12:31 +0000372 parser = FancyGetopt(options)
373 parser.set_negative_aliases(negative_opt)
374 return parser.getopt(args, object)
Greg Wardffc10d92000-04-21 01:41:54 +0000375
376
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000377WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace}
Greg Ward44f8e4e1999-12-12 16:54:55 +0000378
Collin Winter5b7e9d72007-08-30 03:52:21 +0000379def wrap_text(text, width):
Greg Ward46a69b92000-08-30 17:16:27 +0000380 """wrap_text(text : string, width : int) -> [string]
381
382 Split 'text' into multiple lines of no more than 'width' characters
383 each, and return the list of strings that results.
384 """
Greg Ward44f8e4e1999-12-12 16:54:55 +0000385 if text is None:
386 return []
Greg Ward071ed762000-09-26 02:12:31 +0000387 if len(text) <= width:
Greg Ward44f8e4e1999-12-12 16:54:55 +0000388 return [text]
389
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000390 text = text.expandtabs()
391 text = text.translate(WS_TRANS)
Greg Ward071ed762000-09-26 02:12:31 +0000392 chunks = re.split(r'( +|-+)', text)
Guido van Rossum85ac28d2007-09-25 21:48:09 +0000393 chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings
Greg Ward44f8e4e1999-12-12 16:54:55 +0000394 lines = []
395
396 while chunks:
Greg Ward44f8e4e1999-12-12 16:54:55 +0000397 cur_line = [] # list of chunks (to-be-joined)
398 cur_len = 0 # length of current line
399
400 while chunks:
Greg Ward071ed762000-09-26 02:12:31 +0000401 l = len(chunks[0])
Greg Ward44f8e4e1999-12-12 16:54:55 +0000402 if cur_len + l <= width: # can squeeze (at least) this chunk in
Greg Ward071ed762000-09-26 02:12:31 +0000403 cur_line.append(chunks[0])
Greg Ward44f8e4e1999-12-12 16:54:55 +0000404 del chunks[0]
405 cur_len = cur_len + l
406 else: # this line is full
407 # drop last chunk if all space
408 if cur_line and cur_line[-1][0] == ' ':
409 del cur_line[-1]
410 break
411
412 if chunks: # any chunks left to process?
Greg Ward44f8e4e1999-12-12 16:54:55 +0000413 # if the current line is still empty, then we had a single
414 # chunk that's too big too fit on a line -- so we break
415 # down and break it up at the line width
416 if cur_len == 0:
Greg Ward071ed762000-09-26 02:12:31 +0000417 cur_line.append(chunks[0][0:width])
Greg Ward44f8e4e1999-12-12 16:54:55 +0000418 chunks[0] = chunks[0][width:]
419
420 # all-whitespace chunks at the end of a line can be discarded
421 # (and we know from the re.split above that if a chunk has
422 # *any* whitespace, it is *all* whitespace)
423 if chunks[0][0] == ' ':
424 del chunks[0]
425
426 # and store this line in the list-of-all-lines -- as a single
427 # string, of course!
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000428 lines.append(''.join(cur_line))
Greg Ward44f8e4e1999-12-12 16:54:55 +0000429
Greg Ward44f8e4e1999-12-12 16:54:55 +0000430 return lines
431
Greg Ward68ded6e2000-09-25 01:58:31 +0000432
Collin Winter5b7e9d72007-08-30 03:52:21 +0000433def translate_longopt(opt):
Greg Ward68ded6e2000-09-25 01:58:31 +0000434 """Convert a long option name to a valid Python identifier by
435 changing "-" to "_".
436 """
Tarek Ziadé03d5d082009-09-21 13:01:54 +0000437 return opt.translate(longopt_xlate)
Fred Drakeb94b8492001-12-06 20:51:35 +0000438
Greg Ward44f8e4e1999-12-12 16:54:55 +0000439
Greg Wardffc10d92000-04-21 01:41:54 +0000440class OptionDummy:
441 """Dummy class just used as a place to hold command-line option
442 values as instance attributes."""
Greg Ward3c67b1d2000-05-23 01:44:20 +0000443
Collin Winter5b7e9d72007-08-30 03:52:21 +0000444 def __init__(self, options=[]):
Greg Ward3c67b1d2000-05-23 01:44:20 +0000445 """Create a new OptionDummy instance. The attributes listed in
446 'options' will be initialized to None."""
447 for opt in options:
448 setattr(self, opt, None)