blob: cae94be911f87889079b308bb69a1bf0975fe392 [file] [log] [blame]
Neal Norwitz488609e2003-01-06 16:51:37 +00001from 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
10class 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
24class 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
37if __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"
Tim Peters3d7d3722004-07-18 06:25:50 +000048
Neal Norwitz488609e2003-01-06 16:51:37 +000049 parser.add_option("-f", "--file", dest="file")
Walter Dörwald70a6b492004-02-12 17:35:32 +000050 #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"))
Neal Norwitz488609e2003-01-06 16:51:37 +000054 (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"