diff options
Diffstat (limited to 'Lib/distutils/fancy_getopt.py')
-rw-r--r-- | Lib/distutils/fancy_getopt.py | 167 |
1 files changed, 70 insertions, 97 deletions
diff --git a/Lib/distutils/fancy_getopt.py b/Lib/distutils/fancy_getopt.py index 2dea9480259..7d170dd2773 100644 --- a/Lib/distutils/fancy_getopt.py +++ b/Lib/distutils/fancy_getopt.py @@ -8,13 +8,9 @@ additional features: * options set attributes of a passed-in object """ -__revision__ = "$Id$" - -import sys -import string -import re +import sys, string, re import getopt -from distutils.errors import DistutilsGetoptError, DistutilsArgError +from distutils.errors import * # Much like command_re in distutils.core, this is close to but not quite # the same as a Python NAME -- except, in the spirit of most GNU @@ -28,7 +24,7 @@ neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat)) # This is used to translate long options to legitimate Python identifiers # (for use as attributes of some object). -longopt_xlate = string.maketrans('-', '_') +longopt_xlate = str.maketrans('-', '_') class FancyGetopt: """Wrapper around the standard 'getopt()' module that provides some @@ -42,8 +38,7 @@ class FancyGetopt: on the command line sets 'verbose' to false """ - def __init__ (self, option_table=None): - + def __init__(self, option_table=None): # The option table is (currently) a list of tuples. The # tuples may have 3 or four values: # (long_option, short_option, help_string [, repeatable]) @@ -83,58 +78,51 @@ class FancyGetopt: # but expands short options, converts aliases, etc. self.option_order = [] - # __init__ () - - - def _build_index (self): + def _build_index(self): self.option_index.clear() for option in self.option_table: self.option_index[option[0]] = option - def set_option_table (self, option_table): + def set_option_table(self, option_table): self.option_table = option_table self._build_index() - def add_option (self, long_option, short_option=None, help_string=None): + def add_option(self, long_option, short_option=None, help_string=None): if long_option in self.option_index: - raise DistutilsGetoptError, \ - "option conflict: already an option '%s'" % long_option + raise DistutilsGetoptError( + "option conflict: already an option '%s'" % long_option) else: option = (long_option, short_option, help_string) self.option_table.append(option) self.option_index[long_option] = option - - def has_option (self, long_option): + def has_option(self, long_option): """Return true if the option table for this parser has an option with long name 'long_option'.""" return long_option in self.option_index - def get_attr_name (self, long_option): + def get_attr_name(self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" - return string.translate(long_option, longopt_xlate) - + return long_option.translate(longopt_xlate) - def _check_alias_dict (self, aliases, what): + def _check_alias_dict(self, aliases, what): assert isinstance(aliases, dict) for (alias, opt) in aliases.items(): if alias not in self.option_index: - raise DistutilsGetoptError, \ - ("invalid %s '%s': " - "option '%s' not defined") % (what, alias, alias) + raise DistutilsGetoptError(("invalid %s '%s': " + "option '%s' not defined") % (what, alias, alias)) if opt not in self.option_index: - raise DistutilsGetoptError, \ - ("invalid %s '%s': " - "aliased option '%s' not defined") % (what, alias, opt) + raise DistutilsGetoptError(("invalid %s '%s': " + "aliased option '%s' not defined") % (what, alias, opt)) - def set_aliases (self, alias): + def set_aliases(self, alias): """Set the aliases for this option parser.""" self._check_alias_dict(alias, "alias") self.alias = alias - def set_negative_aliases (self, negative_alias): + def set_negative_aliases(self, negative_alias): """Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined @@ -142,8 +130,7 @@ class FancyGetopt: self._check_alias_dict(negative_alias, "negative alias") self.negative_alias = negative_alias - - def _grok_option_table (self): + def _grok_option_table(self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. @@ -162,19 +149,17 @@ class FancyGetopt: else: # the option table is part of the code, so simply # assert that it is correct - raise ValueError, "invalid option tuple: %r" % (option,) + raise ValueError("invalid option tuple: %r" % (option,)) # Type- and value-check the option names if not isinstance(long, str) or len(long) < 2: - raise DistutilsGetoptError, \ - ("invalid long option '%s': " - "must be a string of length >= 2") % long + raise DistutilsGetoptError(("invalid long option '%s': " + "must be a string of length >= 2") % long) if (not ((short is None) or (isinstance(short, str) and len(short) == 1))): - raise DistutilsGetoptError, \ - ("invalid short option '%s': " - "must a single character or None") % short + raise DistutilsGetoptError("invalid short option '%s': " + "must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) @@ -184,54 +169,45 @@ class FancyGetopt: long = long[0:-1] self.takes_arg[long] = 1 else: - # Is option is a "negative alias" for some other option (eg. # "quiet" == "!verbose")? alias_to = self.negative_alias.get(long) if alias_to is not None: if self.takes_arg[alias_to]: - raise DistutilsGetoptError, \ - ("invalid negative alias '%s': " - "aliased option '%s' takes a value") % \ - (long, alias_to) + raise DistutilsGetoptError( + "invalid negative alias '%s': " + "aliased option '%s' takes a value" + % (long, alias_to)) self.long_opts[-1] = long # XXX redundant?! - self.takes_arg[long] = 0 - - else: - self.takes_arg[long] = 0 + self.takes_arg[long] = 0 # If this is an alias option, make sure its "takes arg" flag is # the same as the option it's aliased to. alias_to = self.alias.get(long) if alias_to is not None: if self.takes_arg[long] != self.takes_arg[alias_to]: - raise DistutilsGetoptError, \ - ("invalid alias '%s': inconsistent with " - "aliased option '%s' (one of them takes a value, " - "the other doesn't") % (long, alias_to) - + raise DistutilsGetoptError( + "invalid alias '%s': inconsistent with " + "aliased option '%s' (one of them takes a value, " + "the other doesn't" + % (long, alias_to)) # Now enforce some bondage on the long option name, so we can # later translate it to an attribute name on some object. Have # to do this a bit late to make sure we've removed any trailing # '='. if not longopt_re.match(long): - raise DistutilsGetoptError, \ - ("invalid long option name '%s' " + - "(must be letters, numbers, hyphens only") % long + raise DistutilsGetoptError( + "invalid long option name '%s' " + "(must be letters, numbers, hyphens only" % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long - # for option_table - - # _grok_option_table() - - - def getopt (self, args=None, object=None): + def getopt(self, args=None, object=None): """Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If @@ -246,17 +222,17 @@ class FancyGetopt: args = sys.argv[1:] if object is None: object = OptionDummy() - created_object = 1 + created_object = True else: - created_object = 0 + created_object = False self._grok_option_table() - short_opts = string.join(self.short_opts) + short_opts = ' '.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) - except getopt.error, msg: - raise DistutilsArgError, msg + except getopt.error as msg: + raise DistutilsArgError(msg) for opt, val in opts: if len(opt) == 2 and opt[0] == '-': # it's a short option @@ -292,21 +268,17 @@ class FancyGetopt: else: return args - # getopt() - - - def get_option_order (self): + def get_option_order(self): """Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet. """ if self.option_order is None: - raise RuntimeError, "'getopt()' hasn't been called yet" + raise RuntimeError("'getopt()' hasn't been called yet") else: return self.option_order - - def generate_help (self, header=None): + def generate_help(self, header=None): """Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. """ @@ -383,50 +355,41 @@ class FancyGetopt: for l in text[1:]: lines.append(big_indent + l) - - # for self.option_table - return lines - # generate_help () - - def print_help (self, header=None, file=None): + def print_help(self, header=None, file=None): if file is None: file = sys.stdout for line in self.generate_help(header): file.write(line + "\n") -# class FancyGetopt - -def fancy_getopt (options, negative_opt, object, args): +def fancy_getopt(options, negative_opt, object, args): parser = FancyGetopt(options) parser.set_negative_aliases(negative_opt) return parser.getopt(args, object) -WS_TRANS = string.maketrans(string.whitespace, ' ' * len(string.whitespace)) +WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace} -def wrap_text (text, width): +def wrap_text(text, width): """wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results. """ - if text is None: return [] if len(text) <= width: return [text] - text = string.expandtabs(text) - text = string.translate(text, WS_TRANS) + text = text.expandtabs() + text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) - chunks = filter(None, chunks) # ' - ' results in empty strings + chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings lines = [] while chunks: - cur_line = [] # list of chunks (to-be-joined) cur_len = 0 # length of current line @@ -443,7 +406,6 @@ def wrap_text (text, width): break if chunks: # any chunks left to process? - # if the current line is still empty, then we had a single # chunk that's too big too fit on a line -- so we break # down and break it up at the line width @@ -459,9 +421,7 @@ def wrap_text (text, width): # and store this line in the list-of-all-lines -- as a single # string, of course! - lines.append(string.join(cur_line, '')) - - # while chunks + lines.append(''.join(cur_line)) return lines @@ -470,15 +430,28 @@ def translate_longopt(opt): """Convert a long option name to a valid Python identifier by changing "-" to "_". """ - return string.translate(opt, longopt_xlate) + return opt.translate(longopt_xlate) class OptionDummy: """Dummy class just used as a place to hold command-line option values as instance attributes.""" - def __init__ (self, options=[]): + def __init__(self, options=[]): """Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.""" for opt in options: setattr(self, opt, None) + + +if __name__ == "__main__": + text = """\ +Tra-la-la, supercalifragilisticexpialidocious. +How *do* you spell that odd word, anyways? +(Someone ask Mary -- she'll know [or she'll +say, "How should I know?"].)""" + + for w in (10, 20, 30, 40): + print("width: %d" % w) + print("\n".join(wrap_text(text, w))) + print() |