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