codekingpro/portable-devtools
114k
1"""distutils.fancy_getopt2 3Wrapper around the standard getopt module that provides the following4additional features:5 * short and long options are tied together6 * options have help strings, so fancy_getopt could potentially7 create a complete usage summary8 * options set attributes of a passed-in object9"""10 11from __future__ import annotations12 13import getopt14import re15import string16import sys17from collections.abc import Sequence18from typing import Any19 20from .errors import DistutilsArgError, DistutilsGetoptError21 22# Much like command_re in distutils.core, this is close to but not quite23# the same as a Python NAME -- except, in the spirit of most GNU24# utilities, we use '-' in place of '_'. (The spirit of LISP lives on!)25# The similarities to NAME are again not a coincidence...26longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'27longopt_re = re.compile(rf'^{longopt_pat}$')28 29# For recognizing "negative alias" options, eg. "quiet=!verbose"30neg_alias_re = re.compile(f"^({longopt_pat})=!({longopt_pat})$")31 32# This is used to translate long options to legitimate Python identifiers33# (for use as attributes of some object).34longopt_xlate = str.maketrans('-', '_')35 36 37class FancyGetopt:38 """Wrapper around the standard 'getopt()' module that provides some39 handy extra functionality:40 * short and long options are tied together41 * options have help strings, and help text can be assembled42 from them43 * options set attributes of a passed-in object44 * boolean options can have "negative aliases" -- eg. if45 --quiet is the "negative alias" of --verbose, then "--quiet"46 on the command line sets 'verbose' to false47 """48 49 def __init__(self, option_table=None):50 # The option table is (currently) a list of tuples. The51 # tuples may have 3 or four values:52 # (long_option, short_option, help_string [, repeatable])53 # if an option takes an argument, its long_option should have '='54 # appended; short_option should just be a single character, no ':'55 # in any case. If a long_option doesn't have a corresponding56 # short_option, short_option should be None. All option tuples57 # must have long options.58 self.option_table = option_table59 60 # 'option_index' maps long option names to entries in the option61 # table (ie. those 3-tuples).62 self.option_index = {}63 if self.option_table:64 self._build_index()65 66 # 'alias' records (duh) alias options; {'foo': 'bar'} means67 # --foo is an alias for --bar68 self.alias = {}69 70 # 'negative_alias' keeps track of options that are the boolean71 # opposite of some other option72 self.negative_alias = {}73 74 # These keep track of the information in the option table. We75 # don't actually populate these structures until we're ready to76 # parse the command-line, since the 'option_table' passed in here77 # isn't necessarily the final word.78 self.short_opts = []79 self.long_opts = []80 self.short2long = {}81 self.attr_name = {}82 self.takes_arg = {}83 84 # And 'option_order' is filled up in 'getopt()'; it records the85 # original order of options (and their values) on the command-line,86 # but expands short options, converts aliases, etc.87 self.option_order = []88 89 def _build_index(self):90 self.option_index.clear()91 for option in self.option_table:92 self.option_index[option[0]] = option93 94 def set_option_table(self, option_table):95 self.option_table = option_table96 self._build_index()97 98 def add_option(self, long_option, short_option=None, help_string=None):99 if long_option in self.option_index:100 raise DistutilsGetoptError(101 f"option conflict: already an option '{long_option}'"102 )103 else:104 option = (long_option, short_option, help_string)105 self.option_table.append(option)106 self.option_index[long_option] = option107 108 def has_option(self, long_option):109 """Return true if the option table for this parser has an110 option with long name 'long_option'."""111 return long_option in self.option_index112 113 def get_attr_name(self, long_option):114 """Translate long option name 'long_option' to the form it115 has as an attribute of some object: ie., translate hyphens116 to underscores."""117 return long_option.translate(longopt_xlate)118 119 def _check_alias_dict(self, aliases, what):120 assert isinstance(aliases, dict)121 for alias, opt in aliases.items():122 if alias not in self.option_index:123 raise DistutilsGetoptError(124 f"invalid {what} '{alias}': option '{alias}' not defined"125 )126 if opt not in self.option_index:127 raise DistutilsGetoptError(128 f"invalid {what} '{alias}': aliased option '{opt}' not defined"129 )130 131 def set_aliases(self, alias):132 """Set the aliases for this option parser."""133 self._check_alias_dict(alias, "alias")134 self.alias = alias135 136 def set_negative_aliases(self, negative_alias):137 """Set the negative aliases for this option parser.138 'negative_alias' should be a dictionary mapping option names to139 option names, both the key and value must already be defined140 in the option table."""141 self._check_alias_dict(negative_alias, "negative alias")142 self.negative_alias = negative_alias143 144 def _grok_option_table(self): # noqa: C901145 """Populate the various data structures that keep tabs on the146 option table. Called by 'getopt()' before it can do anything147 worthwhile.148 """149 self.long_opts = []150 self.short_opts = []151 self.short2long.clear()152 self.repeat = {}153 154 for option in self.option_table:155 if len(option) == 3:156 long, short, help = option157 repeat = 0158 elif len(option) == 4:159 long, short, help, repeat = option160 else:161 # the option table is part of the code, so simply162 # assert that it is correct163 raise ValueError(f"invalid option tuple: {option!r}")164 165 # Type- and value-check the option names166 if not isinstance(long, str) or len(long) < 2:167 raise DistutilsGetoptError(168 f"invalid long option '{long}': must be a string of length >= 2"169 )170 171 if not ((short is None) or (isinstance(short, str) and len(short) == 1)):172 raise DistutilsGetoptError(173 f"invalid short option '{short}': must a single character or None"174 )175 176 self.repeat[long] = repeat177 self.long_opts.append(long)178 179 if long[-1] == '=': # option takes an argument?180 if short:181 short = short + ':'182 long = long[0:-1]183 self.takes_arg[long] = True184 else:185 # Is option is a "negative alias" for some other option (eg.186 # "quiet" == "!verbose")?187 alias_to = self.negative_alias.get(long)188 if alias_to is not None:189 if self.takes_arg[alias_to]:190 raise DistutilsGetoptError(191 f"invalid negative alias '{long}': "192 f"aliased option '{alias_to}' takes a value"193 )194 195 self.long_opts[-1] = long # XXX redundant?!196 self.takes_arg[long] = False197 198 # If this is an alias option, make sure its "takes arg" flag is199 # the same as the option it's aliased to.200 alias_to = self.alias.get(long)201 if alias_to is not None:202 if self.takes_arg[long] != self.takes_arg[alias_to]:203 raise DistutilsGetoptError(204 f"invalid alias '{long}': inconsistent with "205 f"aliased option '{alias_to}' (one of them takes a value, "206 "the other doesn't"207 )208 209 # Now enforce some bondage on the long option name, so we can210 # later translate it to an attribute name on some object. Have211 # to do this a bit late to make sure we've removed any trailing212 # '='.213 if not longopt_re.match(long):214 raise DistutilsGetoptError(215 f"invalid long option name '{long}' "216 "(must be letters, numbers, hyphens only"217 )218 219 self.attr_name[long] = self.get_attr_name(long)220 if short:221 self.short_opts.append(short)222 self.short2long[short[0]] = long223 224 def getopt(self, args: Sequence[str] | None = None, object=None): # noqa: C901225 """Parse command-line options in args. Store as attributes on object.226 227 If 'args' is None or not supplied, uses 'sys.argv[1:]'. If228 'object' is None or not supplied, creates a new OptionDummy229 object, stores option values there, and returns a tuple (args,230 object). If 'object' is supplied, it is modified in place and231 'getopt()' just returns 'args'; in both cases, the returned232 'args' is a modified copy of the passed-in 'args' list, which233 is left untouched.234 """235 if args is None:236 args = sys.argv[1:]237 if object is None:238 object = OptionDummy()239 created_object = True240 else:241 created_object = False242 243 self._grok_option_table()244 245 short_opts = ' '.join(self.short_opts)246 try:247 opts, args = getopt.getopt(args, short_opts, self.long_opts)248 except getopt.error as msg:249 raise DistutilsArgError(msg)250 251 for opt, val in opts:252 if len(opt) == 2 and opt[0] == '-': # it's a short option253 opt = self.short2long[opt[1]]254 else:255 assert len(opt) > 2 and opt[:2] == '--'256 opt = opt[2:]257 258 alias = self.alias.get(opt)259 if alias:260 opt = alias261 262 if not self.takes_arg[opt]: # boolean option?263 assert val == '', "boolean option can't have value"264 alias = self.negative_alias.get(opt)265 if alias:266 opt = alias267 val = 0268 else:269 val = 1270 271 attr = self.attr_name[opt]272 # The only repeating option at the moment is 'verbose'.273 # It has a negative option -q quiet, which should set verbose = False.274 if val and self.repeat.get(attr) is not None:275 val = getattr(object, attr, 0) + 1276 setattr(object, attr, val)277 self.option_order.append((opt, val))278 279 # for opts280 if created_object:281 return args, object282 else:283 return args284 285 def get_option_order(self):286 """Returns the list of (option, value) tuples processed by the287 previous run of 'getopt()'. Raises RuntimeError if288 'getopt()' hasn't been called yet.289 """290 if self.option_order is None:291 raise RuntimeError("'getopt()' hasn't been called yet")292 else:293 return self.option_order294 295 def generate_help(self, header=None): # noqa: C901296 """Generate help text (a list of strings, one per suggested line of297 output) from the option table for this FancyGetopt object.298 """299 # Blithely assume the option table is good: probably wouldn't call300 # 'generate_help()' unless you've already called 'getopt()'.301 302 # First pass: determine maximum length of long option names303 max_opt = 0304 for option in self.option_table:305 long = option[0]306 short = option[1]307 ell = len(long)308 if long[-1] == '=':309 ell = ell - 1310 if short is not None:311 ell = ell + 5 # " (-x)" where short == 'x'312 if ell > max_opt:313 max_opt = ell314 315 opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter316 317 # Typical help block looks like this:318 # --foo controls foonabulation319 # Help block for longest option looks like this:320 # --flimflam set the flim-flam level321 # and with wrapped text:322 # --flimflam set the flim-flam level (must be between323 # 0 and 100, except on Tuesdays)324 # Options with short names will have the short name shown (but325 # it doesn't contribute to max_opt):326 # --foo (-f) controls foonabulation327 # If adding the short option would make the left column too wide,328 # we push the explanation off to the next line329 # --flimflam (-l)330 # set the flim-flam level331 # Important parameters:332 # - 2 spaces before option block start lines333 # - 2 dashes for each long option name334 # - min. 2 spaces between option and explanation (gutter)335 # - 5 characters (incl. space) for short option name336 337 # Now generate lines of help text. (If 80 columns were good enough338 # for Jesus, then 78 columns are good enough for me!)339 line_width = 78340 text_width = line_width - opt_width341 big_indent = ' ' * opt_width342 if header:343 lines = [header]344 else:345 lines = ['Option summary:']346 347 for option in self.option_table:348 long, short, help = option[:3]349 text = wrap_text(help, text_width)350 if long[-1] == '=':351 long = long[0:-1]352 353 # Case 1: no short option at all (makes life easy)354 if short is None:355 if text:356 lines.append(f" --{long:<{max_opt}} {text[0]}")357 else:358 lines.append(f" --{long:<{max_opt}}")359 360 # Case 2: we have a short option, so we have to include it361 # just after the long option362 else:363 opt_names = f"{long} (-{short})"364 if text:365 lines.append(f" --{opt_names:<{max_opt}} {text[0]}")366 else:367 lines.append(f" --{opt_names:<{max_opt}}")368 369 for ell in text[1:]:370 lines.append(big_indent + ell)371 return lines372 373 def print_help(self, header=None, file=None):374 if file is None:375 file = sys.stdout376 for line in self.generate_help(header):377 file.write(line + "\n")378 379 380def fancy_getopt(options, negative_opt, object, args: Sequence[str] | None):381 parser = FancyGetopt(options)382 parser.set_negative_aliases(negative_opt)383 return parser.getopt(args, object)384 385 386WS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace}387 388 389def wrap_text(text, width):390 """wrap_text(text : string, width : int) -> [string]391 392 Split 'text' into multiple lines of no more than 'width' characters393 each, and return the list of strings that results.394 """395 if text is None:396 return []397 if len(text) <= width:398 return [text]399 400 text = text.expandtabs()401 text = text.translate(WS_TRANS)402 chunks = re.split(r'( +|-+)', text)403 chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings404 lines = []405 406 while chunks:407 cur_line = [] # list of chunks (to-be-joined)408 cur_len = 0 # length of current line409 410 while chunks:411 ell = len(chunks[0])412 if cur_len + ell <= width: # can squeeze (at least) this chunk in413 cur_line.append(chunks[0])414 del chunks[0]415 cur_len = cur_len + ell416 else: # this line is full417 # drop last chunk if all space418 if cur_line and cur_line[-1][0] == ' ':419 del cur_line[-1]420 break421 422 if chunks: # any chunks left to process?423 # if the current line is still empty, then we had a single424 # chunk that's too big too fit on a line -- so we break425 # down and break it up at the line width426 if cur_len == 0:427 cur_line.append(chunks[0][0:width])428 chunks[0] = chunks[0][width:]429 430 # all-whitespace chunks at the end of a line can be discarded431 # (and we know from the re.split above that if a chunk has432 # *any* whitespace, it is *all* whitespace)433 if chunks[0][0] == ' ':434 del chunks[0]435 436 # and store this line in the list-of-all-lines -- as a single437 # string, of course!438 lines.append(''.join(cur_line))439 440 return lines441 442 443def translate_longopt(opt):444 """Convert a long option name to a valid Python identifier by445 changing "-" to "_".446 """447 return opt.translate(longopt_xlate)448 449 450class OptionDummy:451 """Dummy class just used as a place to hold command-line option452 values as instance attributes."""453 454 def __init__(self, options: Sequence[Any] = []):455 """Create a new OptionDummy instance. The attributes listed in456 'options' will be initialized to None."""457 for opt in options:458 setattr(self, opt, None)459 460 461if __name__ == "__main__":462 text = """\463Tra-la-la, supercalifragilisticexpialidocious.464How *do* you spell that odd word, anyways?465(Someone ask Mary -- she'll know [or she'll466say, "How should I know?"].)"""467 468 for w in (10, 20, 30, 40):469 print(f"width: {w}")470 print("\n".join(wrap_text(text, w)))471 print()472 