##// END OF EJS Templates
fancyopts: lots of cleanups
Matt Mackall -
r5638:a9b7e425 default
parent child Browse files
Show More
@@ -1,35 +1,74 b''
1 import getopt
1 import getopt
2
2
3 def fancyopts(args, options, state):
3 def fancyopts(args, options, state):
4 long = []
4 """
5 short = ''
5 read args, parse options, and store options in state
6 map = {}
6
7 dt = {}
7 each option is a tuple of:
8
9 short option or ''
10 long option
11 default value
12 description
13
14 option types include:
15
16 boolean or none - option sets variable in state to true
17 string - parameter string is stored in state
18 list - parameter string is added to a list
19 integer - parameter strings is stored as int
20 function - call function with parameter
8
21
9 for s, l, d, c in options:
22 non-option args are returned
10 pl = l.replace('-', '_')
23 """
11 map['-'+s] = map['--'+l] = pl
24 namelist = []
12 if isinstance(d, list):
25 shortlist = ''
13 state[pl] = d[:]
26 argmap = {}
27 defmap = {}
28
29 for short, name, default, comment in options:
30 # convert opts to getopt format
31 oname = name
32 name = name.replace('-', '_')
33
34 argmap['-' + short] = argmap['--' + oname] = name
35 defmap[name] = default
36
37 # copy defaults to state
38 if isinstance(default, list):
39 state[name] = default[:]
40 elif callable(default):
41 print "whoa", name, default
42 state[name] = None
14 else:
43 else:
15 state[pl] = d
44 state[name] = default
16 dt[pl] = type(d)
17 if (d is not None and d is not True and d is not False and
18 not callable(d)):
19 if s: s += ':'
20 if l: l += '='
21 if s: short = short + s
22 if l: long.append(l)
23
45
24 opts, args = getopt.getopt(args, short, long)
46 # does it take a parameter?
47 if not (default is None or default is True or default is False):
48 if short: short += ':'
49 if oname: oname += '='
50 if short:
51 shortlist += short
52 if name:
53 namelist.append(oname)
54
55 # parse arguments
56 opts, args = getopt.getopt(args, shortlist, namelist)
25
57
26 for opt, arg in opts:
58 # transfer result to state
27 if dt[map[opt]] is type(fancyopts): state[map[opt]](state, map[opt], arg)
59 for opt, val in opts:
28 elif dt[map[opt]] is type(1): state[map[opt]] = int(arg)
60 name = argmap[opt]
29 elif dt[map[opt]] is type(''): state[map[opt]] = arg
61 t = type(defmap[name])
30 elif dt[map[opt]] is type([]): state[map[opt]].append(arg)
62 if t is type(fancyopts):
31 elif dt[map[opt]] is type(None): state[map[opt]] = True
63 state[name] = defmap[name](val)
32 elif dt[map[opt]] is type(False): state[map[opt]] = True
64 elif t is type(1):
65 state[name] = int(val)
66 elif t is type(''):
67 state[name] = val
68 elif t is type([]):
69 state[name].append(val)
70 elif t is type(None) or t is type(False):
71 state[name] = True
33
72
73 # return unparsed args
34 return args
74 return args
35
General Comments 0
You need to be logged in to leave comments. Login now