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 | |
Greg Ward | 3ce77fd | 2000-03-02 01:49:45 +0000 | [diff] [blame] | 11 | __revision__ = "$Id$" |
Greg Ward | 2689e3d | 1999-03-22 14:52:19 +0000 | [diff] [blame] | 12 | |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 13 | import sys, string, re |
Greg Ward | 2689e3d | 1999-03-22 14:52:19 +0000 | [diff] [blame] | 14 | import getopt |
| 15 | from distutils.errors import * |
| 16 | |
| 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 Ward | a564cc3 | 1999-10-03 20:48:53 +0000 | [diff] [blame] | 21 | longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)' |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 22 | longopt_re = re.compile(r'^%s$' % longopt_pat) |
Greg Ward | a564cc3 | 1999-10-03 20:48:53 +0000 | [diff] [blame] | 23 | |
| 24 | # For recognizing "negative alias" options, eg. "quiet=!verbose" |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 25 | neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat)) |
Greg Ward | a564cc3 | 1999-10-03 20:48:53 +0000 | [diff] [blame] | 26 | |
Greg Ward | 2689e3d | 1999-03-22 14:52:19 +0000 | [diff] [blame] | 27 | # This is used to translate long options to legitimate Python identifiers |
| 28 | # (for use as attributes of some object). |
Tarek Ziadé | 03d5d08 | 2009-09-21 13:01:54 +0000 | [diff] [blame] | 29 | longopt_xlate = str.maketrans('-', '_') |
Greg Ward | 2689e3d | 1999-03-22 14:52:19 +0000 | [diff] [blame] | 30 | |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 31 | class 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 43 | def __init__(self, option_table=None): |
Fred Drake | 576298d | 2004-08-02 17:58:51 +0000 | [diff] [blame] | 44 | # 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 Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 47 | # 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 Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 58 | self._build_index() |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 59 | |
Greg Ward | 1e7b509 | 2000-04-21 04:22:01 +0000 | [diff] [blame] | 60 | # 'alias' records (duh) alias options; {'foo': 'bar'} means |
| 61 | # --foo is an alias for --bar |
| 62 | self.alias = {} |
| 63 | |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 64 | # 'negative_alias' keeps track of options that are the boolean |
| 65 | # opposite of some other option |
| 66 | self.negative_alias = {} |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 67 | |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 68 | # 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 83 | def _build_index(self): |
Greg Ward | 0fd2dd6 | 2000-08-07 00:45:51 +0000 | [diff] [blame] | 84 | self.option_index.clear() |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 85 | for option in self.option_table: |
| 86 | self.option_index[option[0]] = option |
| 87 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 88 | def set_option_table(self, option_table): |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 89 | self.option_table = option_table |
| 90 | self._build_index() |
| 91 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 92 | def add_option(self, long_option, short_option=None, help_string=None): |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 93 | if long_option in self.option_index: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 94 | raise DistutilsGetoptError( |
| 95 | "option conflict: already an option '%s'" % long_option) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 96 | else: |
| 97 | option = (long_option, short_option, help_string) |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 98 | self.option_table.append(option) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 99 | self.option_index[long_option] = option |
| 100 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 101 | def has_option(self, long_option): |
Greg Ward | 320df70 | 2000-04-21 02:31:07 +0000 | [diff] [blame] | 102 | """Return true if the option table for this parser has an |
| 103 | option with long name 'long_option'.""" |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 104 | return long_option in self.option_index |
Greg Ward | 320df70 | 2000-04-21 02:31:07 +0000 | [diff] [blame] | 105 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 106 | def get_attr_name(self, long_option): |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 107 | """Translate long option name 'long_option' to the form it |
Greg Ward | 320df70 | 2000-04-21 02:31:07 +0000 | [diff] [blame] | 108 | has as an attribute of some object: ie., translate hyphens |
| 109 | to underscores.""" |
Tarek Ziadé | 03d5d08 | 2009-09-21 13:01:54 +0000 | [diff] [blame] | 110 | return long_option.translate(longopt_xlate) |
Greg Ward | 320df70 | 2000-04-21 02:31:07 +0000 | [diff] [blame] | 111 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 112 | def _check_alias_dict(self, aliases, what): |
| 113 | assert isinstance(aliases, dict) |
Greg Ward | 1e7b509 | 2000-04-21 04:22:01 +0000 | [diff] [blame] | 114 | for (alias, opt) in aliases.items(): |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 115 | if alias not in self.option_index: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 116 | raise DistutilsGetoptError(("invalid %s '%s': " |
| 117 | "option '%s' not defined") % (what, alias, alias)) |
Guido van Rossum | e2b70bc | 2006-08-18 22:13:04 +0000 | [diff] [blame] | 118 | if opt not in self.option_index: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 119 | raise DistutilsGetoptError(("invalid %s '%s': " |
| 120 | "aliased option '%s' not defined") % (what, alias, opt)) |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 121 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 122 | def set_aliases(self, alias): |
Greg Ward | 1e7b509 | 2000-04-21 04:22:01 +0000 | [diff] [blame] | 123 | """Set the aliases for this option parser.""" |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 124 | self._check_alias_dict(alias, "alias") |
Greg Ward | 1e7b509 | 2000-04-21 04:22:01 +0000 | [diff] [blame] | 125 | self.alias = alias |
| 126 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 127 | def set_negative_aliases(self, negative_alias): |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 128 | """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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 132 | self._check_alias_dict(negative_alias, "negative alias") |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 133 | self.negative_alias = negative_alias |
| 134 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 135 | def _grok_option_table(self): |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 136 | """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 Ward | 0fd2dd6 | 2000-08-07 00:45:51 +0000 | [diff] [blame] | 140 | self.long_opts = [] |
| 141 | self.short_opts = [] |
| 142 | self.short2long.clear() |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 143 | self.repeat = {} |
Greg Ward | 0fd2dd6 | 2000-08-07 00:45:51 +0000 | [diff] [blame] | 144 | |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 145 | for option in self.option_table: |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 146 | 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 154 | raise ValueError("invalid option tuple: %r" % (option,)) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 155 | |
| 156 | # Type- and value-check the option names |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 157 | if not isinstance(long, str) or len(long) < 2: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 158 | raise DistutilsGetoptError(("invalid long option '%s': " |
| 159 | "must be a string of length >= 2") % long) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 160 | |
| 161 | if (not ((short is None) or |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 162 | (isinstance(short, str) and len(short) == 1))): |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 163 | raise DistutilsGetoptError("invalid short option '%s': " |
| 164 | "must a single character or None" % short) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 165 | |
Jeremy Hylton | a181ec0 | 2002-06-04 20:24:05 +0000 | [diff] [blame] | 166 | self.repeat[long] = repeat |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 167 | self.long_opts.append(long) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 168 | |
| 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 Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 174 | # 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 179 | raise DistutilsGetoptError( |
| 180 | "invalid negative alias '%s': " |
| 181 | "aliased option '%s' takes a value" |
| 182 | % (long, alias_to)) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 183 | |
| 184 | self.long_opts[-1] = long # XXX redundant?! |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 185 | self.takes_arg[long] = 0 |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 186 | |
Greg Ward | 1e7b509 | 2000-04-21 04:22:01 +0000 | [diff] [blame] | 187 | # 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 Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 192 | 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 Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 197 | |
| 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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 202 | if not longopt_re.match(long): |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 203 | raise DistutilsGetoptError( |
| 204 | "invalid long option name '%s' " |
| 205 | "(must be letters, numbers, hyphens only" % long) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 206 | |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 207 | self.attr_name[long] = self.get_attr_name(long) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 208 | if short: |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 209 | self.short_opts.append(short) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 210 | self.short2long[short[0]] = long |
| 211 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 212 | def getopt(self, args=None, object=None): |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 213 | """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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 222 | """ |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 223 | if args is None: |
| 224 | args = sys.argv[1:] |
| 225 | if object is None: |
Greg Ward | 981f736 | 2000-05-23 03:53:10 +0000 | [diff] [blame] | 226 | object = OptionDummy() |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 227 | created_object = True |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 228 | else: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 229 | created_object = False |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 230 | |
| 231 | self._grok_option_table() |
| 232 | |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 233 | short_opts = ' '.join(self.short_opts) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 234 | try: |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 235 | opts, args = getopt.getopt(args, short_opts, self.long_opts) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 236 | except getopt.error as msg: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 237 | raise DistutilsArgError(msg) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 238 | |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 239 | for opt, val in opts: |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 240 | if len(opt) == 2 and opt[0] == '-': # it's a short option |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 241 | opt = self.short2long[opt[1]] |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 242 | else: |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 243 | assert len(opt) > 2 and opt[:2] == '--' |
| 244 | opt = opt[2:] |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 245 | |
Greg Ward | 1e7b509 | 2000-04-21 04:22:01 +0000 | [diff] [blame] | 246 | alias = self.alias.get(opt) |
| 247 | if alias: |
| 248 | opt = alias |
| 249 | |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 250 | if not self.takes_arg[opt]: # boolean option? |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 251 | assert val == '', "boolean option can't have value" |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 252 | alias = self.negative_alias.get(opt) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 253 | if alias: |
| 254 | opt = alias |
| 255 | val = 0 |
| 256 | else: |
| 257 | val = 1 |
| 258 | |
| 259 | attr = self.attr_name[opt] |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 260 | # 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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 264 | setattr(object, attr, val) |
| 265 | self.option_order.append((opt, val)) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 266 | |
| 267 | # for opts |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 268 | if created_object: |
Jeremy Hylton | cd8a114 | 2002-06-04 20:14:43 +0000 | [diff] [blame] | 269 | return args, object |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 270 | else: |
| 271 | return args |
| 272 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 273 | def get_option_order(self): |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 274 | """Returns the list of (option, value) tuples processed by the |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 275 | previous run of 'getopt()'. Raises RuntimeError if |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 276 | 'getopt()' hasn't been called yet. |
| 277 | """ |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 278 | if self.option_order is None: |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 279 | raise RuntimeError("'getopt()' hasn't been called yet") |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 280 | else: |
| 281 | return self.option_order |
| 282 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 283 | def generate_help(self, header=None): |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 284 | """Generate help text (a list of strings, one per suggested line of |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 285 | output) from the option table for this FancyGetopt object. |
| 286 | """ |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 287 | # 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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 295 | l = len(long) |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 296 | 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 Hylton | 40ebbef | 2002-06-04 21:10:35 +0000 | [diff] [blame] | 335 | for option in self.option_table: |
Jeremy Hylton | 8f787bf | 2002-06-04 21:11:56 +0000 | [diff] [blame] | 336 | long, short, help = option[:3] |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 337 | text = wrap_text(help, text_width) |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 338 | 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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 344 | lines.append(" --%-*s %s" % (max_opt, long, text[0])) |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 345 | else: |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 346 | lines.append(" --%-*s " % (max_opt, long)) |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 347 | |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 348 | # 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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 353 | lines.append(" --%-*s %s" % |
| 354 | (max_opt, opt_names, text[0])) |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 355 | else: |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 356 | lines.append(" --%-*s" % opt_names) |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 357 | |
Greg Ward | 373dbfa | 2000-06-08 00:35:33 +0000 | [diff] [blame] | 358 | for l in text[1:]: |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 359 | lines.append(big_indent + l) |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 360 | return lines |
| 361 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 362 | def print_help(self, header=None, file=None): |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 363 | if file is None: |
| 364 | file = sys.stdout |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 365 | for line in self.generate_help(header): |
| 366 | file.write(line + "\n") |
Greg Ward | 283c745 | 2000-04-21 02:09:26 +0000 | [diff] [blame] | 367 | |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 368 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 369 | def fancy_getopt(options, negative_opt, object, args): |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 370 | parser = FancyGetopt(options) |
| 371 | parser.set_negative_aliases(negative_opt) |
| 372 | return parser.getopt(args, object) |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 373 | |
| 374 | |
Georg Brandl | 7f13e6b | 2007-08-31 10:37:15 +0000 | [diff] [blame] | 375 | WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace} |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 376 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 377 | def wrap_text(text, width): |
Greg Ward | 46a69b9 | 2000-08-30 17:16:27 +0000 | [diff] [blame] | 378 | """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 Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 383 | if text is None: |
| 384 | return [] |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 385 | if len(text) <= width: |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 386 | return [text] |
| 387 | |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 388 | text = text.expandtabs() |
| 389 | text = text.translate(WS_TRANS) |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 390 | chunks = re.split(r'( +|-+)', text) |
Guido van Rossum | 85ac28d | 2007-09-25 21:48:09 +0000 | [diff] [blame] | 391 | chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 392 | lines = [] |
| 393 | |
| 394 | while chunks: |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 395 | cur_line = [] # list of chunks (to-be-joined) |
| 396 | cur_len = 0 # length of current line |
| 397 | |
| 398 | while chunks: |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 399 | l = len(chunks[0]) |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 400 | if cur_len + l <= width: # can squeeze (at least) this chunk in |
Greg Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 401 | cur_line.append(chunks[0]) |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 402 | 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 Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 411 | # 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 Ward | 071ed76 | 2000-09-26 02:12:31 +0000 | [diff] [blame] | 415 | cur_line.append(chunks[0][0:width]) |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 416 | 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 Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 426 | lines.append(''.join(cur_line)) |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 427 | |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 428 | return lines |
| 429 | |
Greg Ward | 68ded6e | 2000-09-25 01:58:31 +0000 | [diff] [blame] | 430 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 431 | def translate_longopt(opt): |
Greg Ward | 68ded6e | 2000-09-25 01:58:31 +0000 | [diff] [blame] | 432 | """Convert a long option name to a valid Python identifier by |
| 433 | changing "-" to "_". |
| 434 | """ |
Tarek Ziadé | 03d5d08 | 2009-09-21 13:01:54 +0000 | [diff] [blame] | 435 | return opt.translate(longopt_xlate) |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 436 | |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 437 | |
Greg Ward | ffc10d9 | 2000-04-21 01:41:54 +0000 | [diff] [blame] | 438 | class OptionDummy: |
| 439 | """Dummy class just used as a place to hold command-line option |
| 440 | values as instance attributes.""" |
Greg Ward | 3c67b1d | 2000-05-23 01:44:20 +0000 | [diff] [blame] | 441 | |
Collin Winter | 5b7e9d7 | 2007-08-30 03:52:21 +0000 | [diff] [blame] | 442 | def __init__(self, options=[]): |
Greg Ward | 3c67b1d | 2000-05-23 01:44:20 +0000 | [diff] [blame] | 443 | """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) |
| 447 | |
Greg Ward | 44f8e4e | 1999-12-12 16:54:55 +0000 | [diff] [blame] | 448 | |
| 449 | if __name__ == "__main__": |
| 450 | text = """\ |
| 451 | Tra-la-la, supercalifragilisticexpialidocious. |
| 452 | How *do* you spell that odd word, anyways? |
| 453 | (Someone ask Mary -- she'll know [or she'll |
| 454 | say, "How should I know?"].)""" |
| 455 | |
| 456 | for w in (10, 20, 30, 40): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 457 | print("width: %d" % w) |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 458 | print("\n".join(wrap_text(text, w))) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 459 | print() |