Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
fancy_getopt.py470 linesDownload Raw Back to _distutils
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 11import getopt12import re13import string14import sys15from typing import Any, Sequence16 17from .errors import DistutilsArgError, DistutilsGetoptError18 19# Much like command_re in distutils.core, this is close to but not quite20# the same as a Python NAME -- except, in the spirit of most GNU21# utilities, we use '-' in place of '_'.  (The spirit of LISP lives on!)22# The similarities to NAME are again not a coincidence...23longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'24longopt_re = re.compile(r'^%s$' % longopt_pat)25 26# For recognizing "negative alias" options, eg. "quiet=!verbose"27neg_alias_re = re.compile(f"^({longopt_pat})=!({longopt_pat})$")28 29# This is used to translate long options to legitimate Python identifiers30# (for use as attributes of some object).31longopt_xlate = str.maketrans('-', '_')32 33 34class FancyGetopt:35    """Wrapper around the standard 'getopt()' module that provides some36    handy extra functionality:37      * short and long options are tied together38      * options have help strings, and help text can be assembled39        from them40      * options set attributes of a passed-in object41      * boolean options can have "negative aliases" -- eg. if42        --quiet is the "negative alias" of --verbose, then "--quiet"43        on the command line sets 'verbose' to false44    """45 46    def __init__(self, option_table=None):47        # The option table is (currently) a list of tuples.  The48        # tuples may have 3 or four values:49        #   (long_option, short_option, help_string [, repeatable])50        # if an option takes an argument, its long_option should have '='51        # appended; short_option should just be a single character, no ':'52        # in any case.  If a long_option doesn't have a corresponding53        # short_option, short_option should be None.  All option tuples54        # must have long options.55        self.option_table = option_table56 57        # 'option_index' maps long option names to entries in the option58        # table (ie. those 3-tuples).59        self.option_index = {}60        if self.option_table:61            self._build_index()62 63        # 'alias' records (duh) alias options; {'foo': 'bar'} means64        # --foo is an alias for --bar65        self.alias = {}66 67        # 'negative_alias' keeps track of options that are the boolean68        # opposite of some other option69        self.negative_alias = {}70 71        # These keep track of the information in the option table.  We72        # don't actually populate these structures until we're ready to73        # parse the command-line, since the 'option_table' passed in here74        # isn't necessarily the final word.75        self.short_opts = []76        self.long_opts = []77        self.short2long = {}78        self.attr_name = {}79        self.takes_arg = {}80 81        # And 'option_order' is filled up in 'getopt()'; it records the82        # original order of options (and their values) on the command-line,83        # but expands short options, converts aliases, etc.84        self.option_order = []85 86    def _build_index(self):87        self.option_index.clear()88        for option in self.option_table:89            self.option_index[option[0]] = option90 91    def set_option_table(self, option_table):92        self.option_table = option_table93        self._build_index()94 95    def add_option(self, long_option, short_option=None, help_string=None):96        if long_option in self.option_index:97            raise DistutilsGetoptError(98                "option conflict: already an option '%s'" % long_option99            )100        else:101            option = (long_option, short_option, help_string)102            self.option_table.append(option)103            self.option_index[long_option] = option104 105    def has_option(self, long_option):106        """Return true if the option table for this parser has an107        option with long name 'long_option'."""108        return long_option in self.option_index109 110    def get_attr_name(self, long_option):111        """Translate long option name 'long_option' to the form it112        has as an attribute of some object: ie., translate hyphens113        to underscores."""114        return long_option.translate(longopt_xlate)115 116    def _check_alias_dict(self, aliases, what):117        assert isinstance(aliases, dict)118        for alias, opt in aliases.items():119            if alias not in self.option_index:120                raise DistutilsGetoptError(121                    f"invalid {what} '{alias}': " f"option '{alias}' not defined"122                )123            if opt not in self.option_index:124                raise DistutilsGetoptError(125                    f"invalid {what} '{alias}': " f"aliased option '{opt}' not defined"126                )127 128    def set_aliases(self, alias):129        """Set the aliases for this option parser."""130        self._check_alias_dict(alias, "alias")131        self.alias = alias132 133    def set_negative_aliases(self, negative_alias):134        """Set the negative aliases for this option parser.135        'negative_alias' should be a dictionary mapping option names to136        option names, both the key and value must already be defined137        in the option table."""138        self._check_alias_dict(negative_alias, "negative alias")139        self.negative_alias = negative_alias140 141    def _grok_option_table(self):  # noqa: C901142        """Populate the various data structures that keep tabs on the143        option table.  Called by 'getopt()' before it can do anything144        worthwhile.145        """146        self.long_opts = []147        self.short_opts = []148        self.short2long.clear()149        self.repeat = {}150 151        for option in self.option_table:152            if len(option) == 3:153                long, short, help = option154                repeat = 0155            elif len(option) == 4:156                long, short, help, repeat = option157            else:158                # the option table is part of the code, so simply159                # assert that it is correct160                raise ValueError(f"invalid option tuple: {option!r}")161 162            # Type- and value-check the option names163            if not isinstance(long, str) or len(long) < 2:164                raise DistutilsGetoptError(165                    ("invalid long option '%s': must be a string of length >= 2") % long166                )167 168            if not ((short is None) or (isinstance(short, str) and len(short) == 1)):169                raise DistutilsGetoptError(170                    "invalid short option '%s': "171                    "must a single character or None" % short172                )173 174            self.repeat[long] = repeat175            self.long_opts.append(long)176 177            if long[-1] == '=':  # option takes an argument?178                if short:179                    short = short + ':'180                long = long[0:-1]181                self.takes_arg[long] = 1182            else:183                # Is option is a "negative alias" for some other option (eg.184                # "quiet" == "!verbose")?185                alias_to = self.negative_alias.get(long)186                if alias_to is not None:187                    if self.takes_arg[alias_to]:188                        raise DistutilsGetoptError(189                            f"invalid negative alias '{long}': "190                            f"aliased option '{alias_to}' takes a value"191                        )192 193                    self.long_opts[-1] = long  # XXX redundant?!194                self.takes_arg[long] = 0195 196            # If this is an alias option, make sure its "takes arg" flag is197            # the same as the option it's aliased to.198            alias_to = self.alias.get(long)199            if alias_to is not None:200                if self.takes_arg[long] != self.takes_arg[alias_to]:201                    raise DistutilsGetoptError(202                        f"invalid alias '{long}': inconsistent with "203                        f"aliased option '{alias_to}' (one of them takes a value, "204                        "the other doesn't"205                    )206 207            # Now enforce some bondage on the long option name, so we can208            # later translate it to an attribute name on some object.  Have209            # to do this a bit late to make sure we've removed any trailing210            # '='.211            if not longopt_re.match(long):212                raise DistutilsGetoptError(213                    "invalid long option name '%s' "214                    "(must be letters, numbers, hyphens only" % long215                )216 217            self.attr_name[long] = self.get_attr_name(long)218            if short:219                self.short_opts.append(short)220                self.short2long[short[0]] = long221 222    def getopt(self, args=None, object=None):  # noqa: C901223        """Parse command-line options in args. Store as attributes on object.224 225        If 'args' is None or not supplied, uses 'sys.argv[1:]'.  If226        'object' is None or not supplied, creates a new OptionDummy227        object, stores option values there, and returns a tuple (args,228        object).  If 'object' is supplied, it is modified in place and229        'getopt()' just returns 'args'; in both cases, the returned230        'args' is a modified copy of the passed-in 'args' list, which231        is left untouched.232        """233        if args is None:234            args = sys.argv[1:]235        if object is None:236            object = OptionDummy()237            created_object = True238        else:239            created_object = False240 241        self._grok_option_table()242 243        short_opts = ' '.join(self.short_opts)244        try:245            opts, args = getopt.getopt(args, short_opts, self.long_opts)246        except getopt.error as msg:247            raise DistutilsArgError(msg)248 249        for opt, val in opts:250            if len(opt) == 2 and opt[0] == '-':  # it's a short option251                opt = self.short2long[opt[1]]252            else:253                assert len(opt) > 2 and opt[:2] == '--'254                opt = opt[2:]255 256            alias = self.alias.get(opt)257            if alias:258                opt = alias259 260            if not self.takes_arg[opt]:  # boolean option?261                assert val == '', "boolean option can't have value"262                alias = self.negative_alias.get(opt)263                if alias:264                    opt = alias265                    val = 0266                else:267                    val = 1268 269            attr = self.attr_name[opt]270            # The only repeating option at the moment is 'verbose'.271            # It has a negative option -q quiet, which should set verbose = 0.272            if val and self.repeat.get(attr) is not None:273                val = getattr(object, attr, 0) + 1274            setattr(object, attr, val)275            self.option_order.append((opt, val))276 277        # for opts278        if created_object:279            return args, object280        else:281            return args282 283    def get_option_order(self):284        """Returns the list of (option, value) tuples processed by the285        previous run of 'getopt()'.  Raises RuntimeError if286        'getopt()' hasn't been called yet.287        """288        if self.option_order is None:289            raise RuntimeError("'getopt()' hasn't been called yet")290        else:291            return self.option_order292 293    def generate_help(self, header=None):  # noqa: C901294        """Generate help text (a list of strings, one per suggested line of295        output) from the option table for this FancyGetopt object.296        """297        # Blithely assume the option table is good: probably wouldn't call298        # 'generate_help()' unless you've already called 'getopt()'.299 300        # First pass: determine maximum length of long option names301        max_opt = 0302        for option in self.option_table:303            long = option[0]304            short = option[1]305            ell = len(long)306            if long[-1] == '=':307                ell = ell - 1308            if short is not None:309                ell = ell + 5  # " (-x)" where short == 'x'310            if ell > max_opt:311                max_opt = ell312 313        opt_width = max_opt + 2 + 2 + 2  # room for indent + dashes + gutter314 315        # Typical help block looks like this:316        #   --foo       controls foonabulation317        # Help block for longest option looks like this:318        #   --flimflam  set the flim-flam level319        # and with wrapped text:320        #   --flimflam  set the flim-flam level (must be between321        #               0 and 100, except on Tuesdays)322        # Options with short names will have the short name shown (but323        # it doesn't contribute to max_opt):324        #   --foo (-f)  controls foonabulation325        # If adding the short option would make the left column too wide,326        # we push the explanation off to the next line327        #   --flimflam (-l)328        #               set the flim-flam level329        # Important parameters:330        #   - 2 spaces before option block start lines331        #   - 2 dashes for each long option name332        #   - min. 2 spaces between option and explanation (gutter)333        #   - 5 characters (incl. space) for short option name334 335        # Now generate lines of help text.  (If 80 columns were good enough336        # for Jesus, then 78 columns are good enough for me!)337        line_width = 78338        text_width = line_width - opt_width339        big_indent = ' ' * opt_width340        if header:341            lines = [header]342        else:343            lines = ['Option summary:']344 345        for option in self.option_table:346            long, short, help = option[:3]347            text = wrap_text(help, text_width)348            if long[-1] == '=':349                long = long[0:-1]350 351            # Case 1: no short option at all (makes life easy)352            if short is None:353                if text:354                    lines.append("  --%-*s  %s" % (max_opt, long, text[0]))355                else:356                    lines.append("  --%-*s  " % (max_opt, long))357 358            # Case 2: we have a short option, so we have to include it359            # just after the long option360            else:361                opt_names = f"{long} (-{short})"362                if text:363                    lines.append("  --%-*s  %s" % (max_opt, opt_names, text[0]))364                else:365                    lines.append("  --%-*s" % opt_names)366 367            for ell in text[1:]:368                lines.append(big_indent + ell)369        return lines370 371    def print_help(self, header=None, file=None):372        if file is None:373            file = sys.stdout374        for line in self.generate_help(header):375            file.write(line + "\n")376 377 378def fancy_getopt(options, negative_opt, object, args):379    parser = FancyGetopt(options)380    parser.set_negative_aliases(negative_opt)381    return parser.getopt(args, object)382 383 384WS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace}385 386 387def wrap_text(text, width):388    """wrap_text(text : string, width : int) -> [string]389 390    Split 'text' into multiple lines of no more than 'width' characters391    each, and return the list of strings that results.392    """393    if text is None:394        return []395    if len(text) <= width:396        return [text]397 398    text = text.expandtabs()399    text = text.translate(WS_TRANS)400    chunks = re.split(r'( +|-+)', text)401    chunks = [ch for ch in chunks if ch]  # ' - ' results in empty strings402    lines = []403 404    while chunks:405        cur_line = []  # list of chunks (to-be-joined)406        cur_len = 0  # length of current line407 408        while chunks:409            ell = len(chunks[0])410            if cur_len + ell <= width:  # can squeeze (at least) this chunk in411                cur_line.append(chunks[0])412                del chunks[0]413                cur_len = cur_len + ell414            else:  # this line is full415                # drop last chunk if all space416                if cur_line and cur_line[-1][0] == ' ':417                    del cur_line[-1]418                break419 420        if chunks:  # any chunks left to process?421            # if the current line is still empty, then we had a single422            # chunk that's too big too fit on a line -- so we break423            # down and break it up at the line width424            if cur_len == 0:425                cur_line.append(chunks[0][0:width])426                chunks[0] = chunks[0][width:]427 428            # all-whitespace chunks at the end of a line can be discarded429            # (and we know from the re.split above that if a chunk has430            # *any* whitespace, it is *all* whitespace)431            if chunks[0][0] == ' ':432                del chunks[0]433 434        # and store this line in the list-of-all-lines -- as a single435        # string, of course!436        lines.append(''.join(cur_line))437 438    return lines439 440 441def translate_longopt(opt):442    """Convert a long option name to a valid Python identifier by443    changing "-" to "_".444    """445    return opt.translate(longopt_xlate)446 447 448class OptionDummy:449    """Dummy class just used as a place to hold command-line option450    values as instance attributes."""451 452    def __init__(self, options: Sequence[Any] = []):453        """Create a new OptionDummy instance.  The attributes listed in454        'options' will be initialized to None."""455        for opt in options:456            setattr(self, opt, None)457 458 459if __name__ == "__main__":460    text = """\461Tra-la-la, supercalifragilisticexpialidocious.462How *do* you spell that odd word, anyways?463(Someone ask Mary -- she'll know [or she'll464say, "How should I know?"].)"""465 466    for w in (10, 20, 30, 40):467        print("width: %d" % w)468        print("\n".join(wrap_text(text, w)))469        print()470 
codekingpro/portable-devtools · Team Ai