summaryrefslogtreecommitdiff
path: root/Lib/distutils/fancy_getopt.py
diff options
context:
space:
mode:
authorCollin Winter <collinw@gmail.com>2007-08-30 03:52:21 +0000
committerCollin Winter <collinw@gmail.com>2007-08-30 03:52:21 +0000
commit883762c51d8aac2a3ce120690116eaae718c7854 (patch)
treec6c41bcf9a23212daa9cfcbc4c480481a5426311 /Lib/distutils/fancy_getopt.py
parent3d97e02b0ee277cbfee3f2de4f74e64d7269c40c (diff)
downloadcpython-883762c51d8aac2a3ce120690116eaae718c7854.tar.gz
General cleanup, raise normalization in Lib/distutils.
Diffstat (limited to 'Lib/distutils/fancy_getopt.py')
-rw-r--r--Lib/distutils/fancy_getopt.py137
1 files changed, 47 insertions, 90 deletions
diff --git a/Lib/distutils/fancy_getopt.py b/Lib/distutils/fancy_getopt.py
index 82e1f4d1dc..5434334e79 100644
--- a/Lib/distutils/fancy_getopt.py
+++ b/Lib/distutils/fancy_getopt.py
@@ -8,12 +8,9 @@ additional features:
* options set attributes of a passed-in object
"""
-# This module should be kept compatible with Python 2.1.
-
__revision__ = "$Id$"
import sys, string, re
-from types import *
import getopt
from distutils.errors import *
@@ -43,8 +40,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])
@@ -84,58 +80,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 long_option.translate(longopt_xlate)
-
- def _check_alias_dict (self, aliases, what):
- assert type(aliases) is DictionaryType
+ 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
@@ -143,8 +132,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.
@@ -163,19 +151,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, basestring) 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, basestring) 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)
@@ -185,54 +171,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
@@ -247,9 +224,9 @@ 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()
@@ -257,7 +234,7 @@ class FancyGetopt:
try:
opts, args = getopt.getopt(args, short_opts, self.long_opts)
except getopt.error as msg:
- raise DistutilsArgError, msg
+ raise DistutilsArgError(msg)
for opt, val in opts:
if len(opt) == 2 and opt[0] == '-': # it's a short option
@@ -293,21 +270,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.
"""
@@ -384,23 +357,16 @@ 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)
@@ -408,13 +374,12 @@ def fancy_getopt (options, negative_opt, object, args):
WS_TRANS = string.maketrans(string.whitespace, ' ' * len(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:
@@ -427,7 +392,6 @@ def wrap_text (text, width):
lines = []
while chunks:
-
cur_line = [] # list of chunks (to-be-joined)
cur_len = 0 # length of current line
@@ -444,7 +408,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
@@ -462,14 +425,10 @@ def wrap_text (text, width):
# string, of course!
lines.append(''.join(cur_line))
- # while chunks
-
return lines
-# wrap_text ()
-
-def translate_longopt (opt):
+def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
@@ -480,14 +439,12 @@ 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)
-# class OptionDummy
-
if __name__ == "__main__":
text = """\