blob: 879d4d25bf4db0ed8e581a666b3c258f93e4e0d9 [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é36797272010-07-22 12:50:05 +000013import sys, string, re
Greg Ward2689e3d1999-03-22 14:52:19 +000014import getopt
Tarek Ziadé36797272010-07-22 12:50:05 +000015from distutils.errors import *
Greg Ward2689e3d1999-03-22 14:52:19 +000016
17# Much like command_re in distutils.core, this is close to but not quite
18# the same as a Python NAME -- except, in the spirit of most GNU
19# utilities, we use '-' in place of '_'. (The spirit of LISP lives on!)
20# The similarities to NAME are again not a coincidence...
Greg Warda564cc31999-10-03 20:48:53 +000021longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'
Greg Ward071ed762000-09-26 02:12:31 +000022longopt_re = re.compile(r'^%s$' % longopt_pat)
Greg Warda564cc31999-10-03 20:48:53 +000023
24# For recognizing "negative alias" options, eg. "quiet=!verbose"
Greg Ward071ed762000-09-26 02:12:31 +000025neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat))
Greg Warda564cc31999-10-03 20:48:53 +000026
Greg Ward2689e3d1999-03-22 14:52:19 +000027# This is used to translate long options to legitimate Python identifiers
28# (for use as attributes of some object).
Tarek Ziadé03d5d082009-09-21 13:01:54 +000029longopt_xlate = str.maketrans('-', '_')
Greg Ward2689e3d1999-03-22 14:52:19 +000030
Greg Wardffc10d92000-04-21 01:41:54 +000031class FancyGetopt:
32 """Wrapper around the standard 'getopt()' module that provides some
33 handy extra functionality:
34 * short and long options are tied together
35 * options have help strings, and help text can be assembled
36 from them
37 * options set attributes of a passed-in object
38 * boolean options can have "negative aliases" -- eg. if
39 --quiet is the "negative alias" of --verbose, then "--quiet"
40 on the command line sets 'verbose' to false
41 """
42
Collin Winter5b7e9d72007-08-30 03:52:21 +000043 def __init__(self, option_table=None):
Fred Drake576298d2004-08-02 17:58:51 +000044 # The option table is (currently) a list of tuples. The
45 # tuples may have 3 or four values:
46 # (long_option, short_option, help_string [, repeatable])
Greg Wardffc10d92000-04-21 01:41:54 +000047 # if an option takes an argument, its long_option should have '='
48 # appended; short_option should just be a single character, no ':'
49 # in any case. If a long_option doesn't have a corresponding
50 # short_option, short_option should be None. All option tuples
51 # must have long options.
52 self.option_table = option_table
53
54 # 'option_index' maps long option names to entries in the option
55 # table (ie. those 3-tuples).
56 self.option_index = {}
57 if self.option_table:
Greg Ward283c7452000-04-21 02:09:26 +000058 self._build_index()
Greg Wardffc10d92000-04-21 01:41:54 +000059
Greg Ward1e7b5092000-04-21 04:22:01 +000060 # 'alias' records (duh) alias options; {'foo': 'bar'} means
61 # --foo is an alias for --bar
62 self.alias = {}
63
Greg Wardffc10d92000-04-21 01:41:54 +000064 # 'negative_alias' keeps track of options that are the boolean
65 # opposite of some other option
66 self.negative_alias = {}
Fred Drakeb94b8492001-12-06 20:51:35 +000067
Greg Wardffc10d92000-04-21 01:41:54 +000068 # These keep track of the information in the option table. We
69 # don't actually populate these structures until we're ready to
70 # parse the command-line, since the 'option_table' passed in here
71 # isn't necessarily the final word.
72 self.short_opts = []
73 self.long_opts = []
74 self.short2long = {}
75 self.attr_name = {}
76 self.takes_arg = {}
77
78 # And 'option_order' is filled up in 'getopt()'; it records the
79 # original order of options (and their values) on the command-line,
80 # but expands short options, converts aliases, etc.
81 self.option_order = []
82
Collin Winter5b7e9d72007-08-30 03:52:21 +000083 def _build_index(self):
Greg Ward0fd2dd62000-08-07 00:45:51 +000084 self.option_index.clear()
Greg Wardffc10d92000-04-21 01:41:54 +000085 for option in self.option_table:
86 self.option_index[option[0]] = option
87
Collin Winter5b7e9d72007-08-30 03:52:21 +000088 def set_option_table(self, option_table):
Greg Ward283c7452000-04-21 02:09:26 +000089 self.option_table = option_table
90 self._build_index()
91
Collin Winter5b7e9d72007-08-30 03:52:21 +000092 def add_option(self, long_option, short_option=None, help_string=None):
Guido van Rossume2b70bc2006-08-18 22:13:04 +000093 if long_option in self.option_index:
Collin Winter5b7e9d72007-08-30 03:52:21 +000094 raise DistutilsGetoptError(
95 "option conflict: already an option '%s'" % long_option)
Greg Wardffc10d92000-04-21 01:41:54 +000096 else:
97 option = (long_option, short_option, help_string)
Greg Ward071ed762000-09-26 02:12:31 +000098 self.option_table.append(option)
Greg Wardffc10d92000-04-21 01:41:54 +000099 self.option_index[long_option] = option
100
Collin Winter5b7e9d72007-08-30 03:52:21 +0000101 def has_option(self, long_option):
Greg Ward320df702000-04-21 02:31:07 +0000102 """Return true if the option table for this parser has an
103 option with long name 'long_option'."""
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000104 return long_option in self.option_index
Greg Ward320df702000-04-21 02:31:07 +0000105
Collin Winter5b7e9d72007-08-30 03:52:21 +0000106 def get_attr_name(self, long_option):
Fred Drakeb94b8492001-12-06 20:51:35 +0000107 """Translate long option name 'long_option' to the form it
Greg Ward320df702000-04-21 02:31:07 +0000108 has as an attribute of some object: ie., translate hyphens
109 to underscores."""
Tarek Ziadé03d5d082009-09-21 13:01:54 +0000110 return long_option.translate(longopt_xlate)
Greg Ward320df702000-04-21 02:31:07 +0000111
Collin Winter5b7e9d72007-08-30 03:52:21 +0000112 def _check_alias_dict(self, aliases, what):
113 assert isinstance(aliases, dict)
Greg Ward1e7b5092000-04-21 04:22:01 +0000114 for (alias, opt) in aliases.items():
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000115 if alias not in self.option_index:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000116 raise DistutilsGetoptError(("invalid %s '%s': "
117 "option '%s' not defined") % (what, alias, alias))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000118 if opt not in self.option_index:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000119 raise DistutilsGetoptError(("invalid %s '%s': "
120 "aliased option '%s' not defined") % (what, alias, opt))
Fred Drakeb94b8492001-12-06 20:51:35 +0000121
Collin Winter5b7e9d72007-08-30 03:52:21 +0000122 def set_aliases(self, alias):
Greg Ward1e7b5092000-04-21 04:22:01 +0000123 """Set the aliases for this option parser."""
Greg Ward071ed762000-09-26 02:12:31 +0000124 self._check_alias_dict(alias, "alias")
Greg Ward1e7b5092000-04-21 04:22:01 +0000125 self.alias = alias
126
Collin Winter5b7e9d72007-08-30 03:52:21 +0000127 def set_negative_aliases(self, negative_alias):
Greg Wardffc10d92000-04-21 01:41:54 +0000128 """Set the negative aliases for this option parser.
129 'negative_alias' should be a dictionary mapping option names to
130 option names, both the key and value must already be defined
131 in the option table."""
Greg Ward071ed762000-09-26 02:12:31 +0000132 self._check_alias_dict(negative_alias, "negative alias")
Greg Wardffc10d92000-04-21 01:41:54 +0000133 self.negative_alias = negative_alias
134
Collin Winter5b7e9d72007-08-30 03:52:21 +0000135 def _grok_option_table(self):
Greg Ward071ed762000-09-26 02:12:31 +0000136 """Populate the various data structures that keep tabs on the
137 option table. Called by 'getopt()' before it can do anything
138 worthwhile.
139 """
Greg Ward0fd2dd62000-08-07 00:45:51 +0000140 self.long_opts = []
141 self.short_opts = []
142 self.short2long.clear()
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000143 self.repeat = {}
Greg Ward0fd2dd62000-08-07 00:45:51 +0000144
Greg Wardffc10d92000-04-21 01:41:54 +0000145 for option in self.option_table:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000146 if len(option) == 3:
147 long, short, help = option
148 repeat = 0
149 elif len(option) == 4:
150 long, short, help, repeat = option
151 else:
152 # the option table is part of the code, so simply
153 # assert that it is correct
Collin Winter5b7e9d72007-08-30 03:52:21 +0000154 raise ValueError("invalid option tuple: %r" % (option,))
Greg Wardffc10d92000-04-21 01:41:54 +0000155
156 # Type- and value-check the option names
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000157 if not isinstance(long, str) or len(long) < 2:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000158 raise DistutilsGetoptError(("invalid long option '%s': "
159 "must be a string of length >= 2") % long)
Greg Wardffc10d92000-04-21 01:41:54 +0000160
161 if (not ((short is None) or
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000162 (isinstance(short, str) and len(short) == 1))):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000163 raise DistutilsGetoptError("invalid short option '%s': "
164 "must a single character or None" % short)
Greg Wardffc10d92000-04-21 01:41:54 +0000165
Jeremy Hyltona181ec02002-06-04 20:24:05 +0000166 self.repeat[long] = repeat
Greg Ward071ed762000-09-26 02:12:31 +0000167 self.long_opts.append(long)
Greg Wardffc10d92000-04-21 01:41:54 +0000168
169 if long[-1] == '=': # option takes an argument?
170 if short: short = short + ':'
171 long = long[0:-1]
172 self.takes_arg[long] = 1
173 else:
Greg Wardffc10d92000-04-21 01:41:54 +0000174 # Is option is a "negative alias" for some other option (eg.
175 # "quiet" == "!verbose")?
176 alias_to = self.negative_alias.get(long)
177 if alias_to is not None:
178 if self.takes_arg[alias_to]:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000179 raise DistutilsGetoptError(
180 "invalid negative alias '%s': "
181 "aliased option '%s' takes a value"
182 % (long, alias_to))
Greg Wardffc10d92000-04-21 01:41:54 +0000183
184 self.long_opts[-1] = long # XXX redundant?!
Collin Winter5b7e9d72007-08-30 03:52:21 +0000185 self.takes_arg[long] = 0
Greg Wardffc10d92000-04-21 01:41:54 +0000186
Greg Ward1e7b5092000-04-21 04:22:01 +0000187 # If this is an alias option, make sure its "takes arg" flag is
188 # the same as the option it's aliased to.
189 alias_to = self.alias.get(long)
190 if alias_to is not None:
191 if self.takes_arg[long] != self.takes_arg[alias_to]:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000192 raise DistutilsGetoptError(
193 "invalid alias '%s': inconsistent with "
194 "aliased option '%s' (one of them takes a value, "
195 "the other doesn't"
196 % (long, alias_to))
Greg Wardffc10d92000-04-21 01:41:54 +0000197
198 # Now enforce some bondage on the long option name, so we can
199 # later translate it to an attribute name on some object. Have
200 # to do this a bit late to make sure we've removed any trailing
201 # '='.
Greg Ward071ed762000-09-26 02:12:31 +0000202 if not longopt_re.match(long):
Collin Winter5b7e9d72007-08-30 03:52:21 +0000203 raise DistutilsGetoptError(
204 "invalid long option name '%s' "
205 "(must be letters, numbers, hyphens only" % long)
Greg Wardffc10d92000-04-21 01:41:54 +0000206
Greg Ward071ed762000-09-26 02:12:31 +0000207 self.attr_name[long] = self.get_attr_name(long)
Greg Wardffc10d92000-04-21 01:41:54 +0000208 if short:
Greg Ward071ed762000-09-26 02:12:31 +0000209 self.short_opts.append(short)
Greg Wardffc10d92000-04-21 01:41:54 +0000210 self.short2long[short[0]] = long
211
Collin Winter5b7e9d72007-08-30 03:52:21 +0000212 def getopt(self, args=None, object=None):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000213 """Parse command-line options in args. Store as attributes on object.
214
215 If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
216 'object' is None or not supplied, creates a new OptionDummy
217 object, stores option values there, and returns a tuple (args,
218 object). If 'object' is supplied, it is modified in place and
219 'getopt()' just returns 'args'; in both cases, the returned
220 'args' is a modified copy of the passed-in 'args' list, which
221 is left untouched.
Greg Ward071ed762000-09-26 02:12:31 +0000222 """
Greg Wardffc10d92000-04-21 01:41:54 +0000223 if args is None:
224 args = sys.argv[1:]
225 if object is None:
Greg Ward981f7362000-05-23 03:53:10 +0000226 object = OptionDummy()
Collin Winter5b7e9d72007-08-30 03:52:21 +0000227 created_object = True
Greg Wardffc10d92000-04-21 01:41:54 +0000228 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000229 created_object = False
Greg Wardffc10d92000-04-21 01:41:54 +0000230
231 self._grok_option_table()
232
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000233 short_opts = ' '.join(self.short_opts)
Greg Wardffc10d92000-04-21 01:41:54 +0000234 try:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000235 opts, args = getopt.getopt(args, short_opts, self.long_opts)
Guido van Rossumb940e112007-01-10 16:19:56 +0000236 except getopt.error as msg:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000237 raise DistutilsArgError(msg)
Greg Wardffc10d92000-04-21 01:41:54 +0000238
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000239 for opt, val in opts:
Greg Ward071ed762000-09-26 02:12:31 +0000240 if len(opt) == 2 and opt[0] == '-': # it's a short option
Greg Wardffc10d92000-04-21 01:41:54 +0000241 opt = self.short2long[opt[1]]
Greg Wardffc10d92000-04-21 01:41:54 +0000242 else:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000243 assert len(opt) > 2 and opt[:2] == '--'
244 opt = opt[2:]
Greg Wardffc10d92000-04-21 01:41:54 +0000245
Greg Ward1e7b5092000-04-21 04:22:01 +0000246 alias = self.alias.get(opt)
247 if alias:
248 opt = alias
249
Greg Wardffc10d92000-04-21 01:41:54 +0000250 if not self.takes_arg[opt]: # boolean option?
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000251 assert val == '', "boolean option can't have value"
Greg Ward071ed762000-09-26 02:12:31 +0000252 alias = self.negative_alias.get(opt)
Greg Wardffc10d92000-04-21 01:41:54 +0000253 if alias:
254 opt = alias
255 val = 0
256 else:
257 val = 1
258
259 attr = self.attr_name[opt]
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000260 # The only repeating option at the moment is 'verbose'.
261 # It has a negative option -q quiet, which should set verbose = 0.
262 if val and self.repeat.get(attr) is not None:
263 val = getattr(object, attr, 0) + 1
Greg Ward071ed762000-09-26 02:12:31 +0000264 setattr(object, attr, val)
265 self.option_order.append((opt, val))
Greg Wardffc10d92000-04-21 01:41:54 +0000266
267 # for opts
Greg Wardffc10d92000-04-21 01:41:54 +0000268 if created_object:
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000269 return args, object
Greg Wardffc10d92000-04-21 01:41:54 +0000270 else:
271 return args
272
Collin Winter5b7e9d72007-08-30 03:52:21 +0000273 def get_option_order(self):
Greg Wardffc10d92000-04-21 01:41:54 +0000274 """Returns the list of (option, value) tuples processed by the
Greg Ward283c7452000-04-21 02:09:26 +0000275 previous run of 'getopt()'. Raises RuntimeError if
Greg Ward071ed762000-09-26 02:12:31 +0000276 'getopt()' hasn't been called yet.
277 """
Greg Wardffc10d92000-04-21 01:41:54 +0000278 if self.option_order is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000279 raise RuntimeError("'getopt()' hasn't been called yet")
Greg Wardffc10d92000-04-21 01:41:54 +0000280 else:
281 return self.option_order
282
Collin Winter5b7e9d72007-08-30 03:52:21 +0000283 def generate_help(self, header=None):
Greg Ward283c7452000-04-21 02:09:26 +0000284 """Generate help text (a list of strings, one per suggested line of
Greg Ward071ed762000-09-26 02:12:31 +0000285 output) from the option table for this FancyGetopt object.
286 """
Greg Ward283c7452000-04-21 02:09:26 +0000287 # Blithely assume the option table is good: probably wouldn't call
288 # 'generate_help()' unless you've already called 'getopt()'.
289
290 # First pass: determine maximum length of long option names
291 max_opt = 0
292 for option in self.option_table:
293 long = option[0]
294 short = option[1]
Greg Ward071ed762000-09-26 02:12:31 +0000295 l = len(long)
Greg Ward283c7452000-04-21 02:09:26 +0000296 if long[-1] == '=':
297 l = l - 1
298 if short is not None:
299 l = l + 5 # " (-x)" where short == 'x'
300 if l > max_opt:
301 max_opt = l
302
303 opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
304
305 # Typical help block looks like this:
306 # --foo controls foonabulation
307 # Help block for longest option looks like this:
308 # --flimflam set the flim-flam level
309 # and with wrapped text:
310 # --flimflam set the flim-flam level (must be between
311 # 0 and 100, except on Tuesdays)
312 # Options with short names will have the short name shown (but
313 # it doesn't contribute to max_opt):
314 # --foo (-f) controls foonabulation
315 # If adding the short option would make the left column too wide,
316 # we push the explanation off to the next line
317 # --flimflam (-l)
318 # set the flim-flam level
319 # Important parameters:
320 # - 2 spaces before option block start lines
321 # - 2 dashes for each long option name
322 # - min. 2 spaces between option and explanation (gutter)
323 # - 5 characters (incl. space) for short option name
324
325 # Now generate lines of help text. (If 80 columns were good enough
326 # for Jesus, then 78 columns are good enough for me!)
327 line_width = 78
328 text_width = line_width - opt_width
329 big_indent = ' ' * opt_width
330 if header:
331 lines = [header]
332 else:
333 lines = ['Option summary:']
334
Jeremy Hylton40ebbef2002-06-04 21:10:35 +0000335 for option in self.option_table:
Jeremy Hylton8f787bf2002-06-04 21:11:56 +0000336 long, short, help = option[:3]
Greg Ward071ed762000-09-26 02:12:31 +0000337 text = wrap_text(help, text_width)
Greg Ward283c7452000-04-21 02:09:26 +0000338 if long[-1] == '=':
339 long = long[0:-1]
340
341 # Case 1: no short option at all (makes life easy)
342 if short is None:
343 if text:
Greg Ward071ed762000-09-26 02:12:31 +0000344 lines.append(" --%-*s %s" % (max_opt, long, text[0]))
Greg Ward283c7452000-04-21 02:09:26 +0000345 else:
Greg Ward071ed762000-09-26 02:12:31 +0000346 lines.append(" --%-*s " % (max_opt, long))
Greg Ward283c7452000-04-21 02:09:26 +0000347
Greg Ward283c7452000-04-21 02:09:26 +0000348 # Case 2: we have a short option, so we have to include it
349 # just after the long option
350 else:
351 opt_names = "%s (-%s)" % (long, short)
352 if text:
Greg Ward071ed762000-09-26 02:12:31 +0000353 lines.append(" --%-*s %s" %
354 (max_opt, opt_names, text[0]))
Greg Ward283c7452000-04-21 02:09:26 +0000355 else:
Greg Ward071ed762000-09-26 02:12:31 +0000356 lines.append(" --%-*s" % opt_names)
Greg Ward283c7452000-04-21 02:09:26 +0000357
Greg Ward373dbfa2000-06-08 00:35:33 +0000358 for l in text[1:]:
Greg Ward071ed762000-09-26 02:12:31 +0000359 lines.append(big_indent + l)
Greg Ward283c7452000-04-21 02:09:26 +0000360 return lines
361
Collin Winter5b7e9d72007-08-30 03:52:21 +0000362 def print_help(self, header=None, file=None):
Greg Ward283c7452000-04-21 02:09:26 +0000363 if file is None:
364 file = sys.stdout
Greg Ward071ed762000-09-26 02:12:31 +0000365 for line in self.generate_help(header):
366 file.write(line + "\n")
Greg Ward283c7452000-04-21 02:09:26 +0000367
Greg Wardffc10d92000-04-21 01:41:54 +0000368
Collin Winter5b7e9d72007-08-30 03:52:21 +0000369def fancy_getopt(options, negative_opt, object, args):
Greg Ward071ed762000-09-26 02:12:31 +0000370 parser = FancyGetopt(options)
371 parser.set_negative_aliases(negative_opt)
372 return parser.getopt(args, object)
Greg Wardffc10d92000-04-21 01:41:54 +0000373
374
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000375WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace}
Greg Ward44f8e4e1999-12-12 16:54:55 +0000376
Collin Winter5b7e9d72007-08-30 03:52:21 +0000377def wrap_text(text, width):
Greg Ward46a69b92000-08-30 17:16:27 +0000378 """wrap_text(text : string, width : int) -> [string]
379
380 Split 'text' into multiple lines of no more than 'width' characters
381 each, and return the list of strings that results.
382 """
Greg Ward44f8e4e1999-12-12 16:54:55 +0000383 if text is None:
384 return []
Greg Ward071ed762000-09-26 02:12:31 +0000385 if len(text) <= width:
Greg Ward44f8e4e1999-12-12 16:54:55 +0000386 return [text]
387
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000388 text = text.expandtabs()
389 text = text.translate(WS_TRANS)
Greg Ward071ed762000-09-26 02:12:31 +0000390 chunks = re.split(r'( +|-+)', text)
Guido van Rossum85ac28d2007-09-25 21:48:09 +0000391 chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings
Greg Ward44f8e4e1999-12-12 16:54:55 +0000392 lines = []
393
394 while chunks:
Greg Ward44f8e4e1999-12-12 16:54:55 +0000395 cur_line = [] # list of chunks (to-be-joined)
396 cur_len = 0 # length of current line
397
398 while chunks:
Greg Ward071ed762000-09-26 02:12:31 +0000399 l = len(chunks[0])
Greg Ward44f8e4e1999-12-12 16:54:55 +0000400 if cur_len + l <= width: # can squeeze (at least) this chunk in
Greg Ward071ed762000-09-26 02:12:31 +0000401 cur_line.append(chunks[0])
Greg Ward44f8e4e1999-12-12 16:54:55 +0000402 del chunks[0]
403 cur_len = cur_len + l
404 else: # this line is full
405 # drop last chunk if all space
406 if cur_line and cur_line[-1][0] == ' ':
407 del cur_line[-1]
408 break
409
410 if chunks: # any chunks left to process?
Greg Ward44f8e4e1999-12-12 16:54:55 +0000411 # if the current line is still empty, then we had a single
412 # chunk that's too big too fit on a line -- so we break
413 # down and break it up at the line width
414 if cur_len == 0:
Greg Ward071ed762000-09-26 02:12:31 +0000415 cur_line.append(chunks[0][0:width])
Greg Ward44f8e4e1999-12-12 16:54:55 +0000416 chunks[0] = chunks[0][width:]
417
418 # all-whitespace chunks at the end of a line can be discarded
419 # (and we know from the re.split above that if a chunk has
420 # *any* whitespace, it is *all* whitespace)
421 if chunks[0][0] == ' ':
422 del chunks[0]
423
424 # and store this line in the list-of-all-lines -- as a single
425 # string, of course!
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000426 lines.append(''.join(cur_line))
Greg Ward44f8e4e1999-12-12 16:54:55 +0000427
Greg Ward44f8e4e1999-12-12 16:54:55 +0000428 return lines
429
Greg Ward68ded6e2000-09-25 01:58:31 +0000430
Collin Winter5b7e9d72007-08-30 03:52:21 +0000431def translate_longopt(opt):
Greg Ward68ded6e2000-09-25 01:58:31 +0000432 """Convert a long option name to a valid Python identifier by
433 changing "-" to "_".
434 """
Tarek Ziadé03d5d082009-09-21 13:01:54 +0000435 return opt.translate(longopt_xlate)
Fred Drakeb94b8492001-12-06 20:51:35 +0000436
Greg Ward44f8e4e1999-12-12 16:54:55 +0000437
Greg Wardffc10d92000-04-21 01:41:54 +0000438class OptionDummy:
439 """Dummy class just used as a place to hold command-line option
440 values as instance attributes."""
Greg Ward3c67b1d2000-05-23 01:44:20 +0000441
Collin Winter5b7e9d72007-08-30 03:52:21 +0000442 def __init__(self, options=[]):
Greg Ward3c67b1d2000-05-23 01:44:20 +0000443 """Create a new OptionDummy instance. The attributes listed in
444 'options' will be initialized to None."""
445 for opt in options:
446 setattr(self, opt, None)
Tarek Ziadé36797272010-07-22 12:50:05 +0000447
448
449if __name__ == "__main__":
450 text = """\
451Tra-la-la, supercalifragilisticexpialidocious.
452How *do* you spell that odd word, anyways?
453(Someone ask Mary -- she'll know [or she'll
454say, "How should I know?"].)"""
455
456 for w in (10, 20, 30, 40):
457 print("width: %d" % w)
458 print("\n".join(wrap_text(text, w)))
459 print()