| 1 | from optparse import Option, OptionParser, _match_abbrev
|
|---|
| 2 |
|
|---|
| 3 | # This case-insensitive option parser relies on having a
|
|---|
| 4 | # case-insensitive dictionary type available. Here's one
|
|---|
| 5 | # for Python 2.2. Note that a *real* case-insensitive
|
|---|
| 6 | # dictionary type would also have to implement __new__(),
|
|---|
| 7 | # update(), and setdefault() -- but that's not the point
|
|---|
| 8 | # of this exercise.
|
|---|
| 9 |
|
|---|
| 10 | class caseless_dict (dict):
|
|---|
| 11 | def __setitem__ (self, key, value):
|
|---|
| 12 | dict.__setitem__(self, key.lower(), value)
|
|---|
| 13 |
|
|---|
| 14 | def __getitem__ (self, key):
|
|---|
| 15 | return dict.__getitem__(self, key.lower())
|
|---|
| 16 |
|
|---|
| 17 | def get (self, key, default=None):
|
|---|
| 18 | return dict.get(self, key.lower())
|
|---|
| 19 |
|
|---|
| 20 | def has_key (self, key):
|
|---|
| 21 | return dict.has_key(self, key.lower())
|
|---|
| 22 |
|
|---|
| 23 |
|
|---|
| 24 | class CaselessOptionParser (OptionParser):
|
|---|
| 25 |
|
|---|
| 26 | def _create_option_list (self):
|
|---|
| 27 | self.option_list = []
|
|---|
| 28 | self._short_opt = caseless_dict()
|
|---|
| 29 | self._long_opt = caseless_dict()
|
|---|
| 30 | self._long_opts = []
|
|---|
| 31 | self.defaults = {}
|
|---|
| 32 |
|
|---|
| 33 | def _match_long_opt (self, opt):
|
|---|
| 34 | return _match_abbrev(opt.lower(), self._long_opt.keys())
|
|---|
| 35 |
|
|---|
| 36 |
|
|---|
| 37 | if __name__ == "__main__":
|
|---|
| 38 | from optik.errors import OptionConflictError
|
|---|
| 39 |
|
|---|
| 40 | # test 1: no options to start with
|
|---|
| 41 | parser = CaselessOptionParser()
|
|---|
| 42 | try:
|
|---|
| 43 | parser.add_option("-H", dest="blah")
|
|---|
| 44 | except OptionConflictError:
|
|---|
| 45 | print "ok: got OptionConflictError for -H"
|
|---|
| 46 | else:
|
|---|
| 47 | print "not ok: no conflict between -h and -H"
|
|---|
| 48 |
|
|---|
| 49 | parser.add_option("-f", "--file", dest="file")
|
|---|
| 50 | #print repr(parser.get_option("-f"))
|
|---|
| 51 | #print repr(parser.get_option("-F"))
|
|---|
| 52 | #print repr(parser.get_option("--file"))
|
|---|
| 53 | #print repr(parser.get_option("--fIlE"))
|
|---|
| 54 | (options, args) = parser.parse_args(["--FiLe", "foo"])
|
|---|
| 55 | assert options.file == "foo", options.file
|
|---|
| 56 | print "ok: case insensitive long options work"
|
|---|
| 57 |
|
|---|
| 58 | (options, args) = parser.parse_args(["-F", "bar"])
|
|---|
| 59 | assert options.file == "bar", options.file
|
|---|
| 60 | print "ok: case insensitive short options work"
|
|---|