1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 """Add an abstraction level to transparently import optik classes from optparse
19 (python >= 2.3) or the optik package.
20
21 It also defines three new types for optik/optparse command line parser :
22
23 * regexp
24 argument of this type will be converted using re.compile
25 * csv
26 argument of this type will be converted using split(',')
27 * yn
28 argument of this type will be true if 'y' or 'yes', false if 'n' or 'no'
29 * named
30 argument of this type are in the form <NAME>=<VALUE> or <NAME>:<VALUE>
31 * password
32 argument of this type wont be converted but this is used by other tools
33 such as interactive prompt for configuration to double check value and
34 use an invisible field
35 * multiple_choice
36 same as default "choice" type but multiple choices allowed
37 * file
38 argument of this type wont be converted but checked that the given file exists
39 * color
40 argument of this type wont be converted but checked its either a
41 named color or a color specified using hexadecimal notation (preceded by a #)
42 * time
43 argument of this type will be converted to a float value in seconds
44 according to time units (ms, s, min, h, d)
45 * bytes
46 argument of this type will be converted to a float value in bytes
47 according to byte units (b, kb, mb, gb, tb)
48 """
49 __docformat__ = "restructuredtext en"
50
51 import re
52 import sys
53 import time
54 from copy import copy
55 from os.path import exists
56
57
58 from optparse import OptionParser as BaseParser, Option as BaseOption, \
59 OptionGroup, OptionContainer, OptionValueError, OptionError, \
60 Values, HelpFormatter, NO_DEFAULT, SUPPRESS_HELP
61
62 try:
63 from mx import DateTime
64 HAS_MX_DATETIME = True
65 except ImportError:
66 HAS_MX_DATETIME = False
67
68
69 OPTPARSE_FORMAT_DEFAULT = sys.version_info >= (2, 4)
70
71 from logilab.common.textutils import splitstrip
72
74 """check a regexp value by trying to compile it
75 return the compiled regexp
76 """
77 if hasattr(value, 'pattern'):
78 return value
79 try:
80 return re.compile(value)
81 except ValueError:
82 raise OptionValueError(
83 "option %s: invalid regexp value: %r" % (opt, value))
84
86 """check a csv value by trying to split it
87 return the list of separated values
88 """
89 if isinstance(value, (list, tuple)):
90 return value
91 try:
92 return splitstrip(value)
93 except ValueError:
94 raise OptionValueError(
95 "option %s: invalid csv value: %r" % (opt, value))
96
98 """check a yn value
99 return true for yes and false for no
100 """
101 if isinstance(value, int):
102 return bool(value)
103 if value in ('y', 'yes'):
104 return True
105 if value in ('n', 'no'):
106 return False
107 msg = "option %s: invalid yn value %r, should be in (y, yes, n, no)"
108 raise OptionValueError(msg % (opt, value))
109
111 """check a named value
112 return a dictionary containing (name, value) associations
113 """
114 if isinstance(value, dict):
115 return value
116 values = []
117 for value in check_csv(option, opt, value):
118 if value.find('=') != -1:
119 values.append(value.split('=', 1))
120 elif value.find(':') != -1:
121 values.append(value.split(':', 1))
122 if values:
123 return dict(values)
124 msg = "option %s: invalid named value %r, should be <NAME>=<VALUE> or \
125 <NAME>:<VALUE>"
126 raise OptionValueError(msg % (opt, value))
127
129 """check a password value (can't be empty)
130 """
131
132 return value
133
135 """check a file value
136 return the filepath
137 """
138 if exists(value):
139 return value
140 msg = "option %s: file %r does not exist"
141 raise OptionValueError(msg % (opt, value))
142
143
145 """check a file value
146 return the filepath
147 """
148 try:
149 return DateTime.strptime(value, "%Y/%m/%d")
150 except DateTime.Error :
151 raise OptionValueError(
152 "expected format of %s is yyyy/mm/dd" % opt)
153
155 """check a color value and returns it
156 /!\ does *not* check color labels (like 'red', 'green'), only
157 checks hexadecimal forms
158 """
159
160 if re.match('[a-z0-9 ]+$', value, re.I):
161 return value
162
163 if re.match('#[a-f0-9]{6}', value, re.I):
164 return value
165
166 msg = "option %s: invalid color : %r, should be either hexadecimal \
167 value or predefined color"
168 raise OptionValueError(msg % (opt, value))
169
175
181
182 import types
183
185 """override optik.Option to add some new option types
186 """
187 TYPES = BaseOption.TYPES + ('regexp', 'csv', 'yn', 'named', 'password',
188 'multiple_choice', 'file', 'color',
189 'time', 'bytes')
190 ATTRS = BaseOption.ATTRS + ['hide', 'level']
191 TYPE_CHECKER = copy(BaseOption.TYPE_CHECKER)
192 TYPE_CHECKER['regexp'] = check_regexp
193 TYPE_CHECKER['csv'] = check_csv
194 TYPE_CHECKER['yn'] = check_yn
195 TYPE_CHECKER['named'] = check_named
196 TYPE_CHECKER['multiple_choice'] = check_csv
197 TYPE_CHECKER['file'] = check_file
198 TYPE_CHECKER['color'] = check_color
199 TYPE_CHECKER['password'] = check_password
200 TYPE_CHECKER['time'] = check_time
201 TYPE_CHECKER['bytes'] = check_bytes
202 if HAS_MX_DATETIME:
203 TYPES += ('date',)
204 TYPE_CHECKER['date'] = check_date
205
207 BaseOption.__init__(self, *opts, **attrs)
208 if hasattr(self, "hide") and self.hide:
209 self.help = SUPPRESS_HELP
210
212 """FIXME: need to override this due to optik misdesign"""
213 if self.type in ("choice", "multiple_choice"):
214 if self.choices is None:
215 raise OptionError(
216 "must supply a list of choices for type 'choice'", self)
217 elif type(self.choices) not in (types.TupleType, types.ListType):
218 raise OptionError(
219 "choices must be a list of strings ('%s' supplied)"
220 % str(type(self.choices)).split("'")[1], self)
221 elif self.choices is not None:
222 raise OptionError(
223 "must not supply choices for type %r" % self.type, self)
224 BaseOption.CHECK_METHODS[2] = _check_choice
225
226
227 - def process(self, opt, value, values, parser):
228
229
230 try:
231 value = self.convert_value(opt, value)
232 except AttributeError:
233 value = self.check_value(opt, value)
234 if self.type == 'named':
235 existant = getattr(values, self.dest)
236 if existant:
237 existant.update(value)
238 value = existant
239
240
241
242 return self.take_action(
243 self.action, self.dest, opt, value, values, parser)
244
245
247 """override optik.OptionParser to use our Option class
248 """
251
271
272
273 OptionGroup.level = 0
274
276 return [option for option in group.option_list
277 if (getattr(option, 'level', 0) or 0) <= outputlevel
278 and not option.help is SUPPRESS_HELP]
279
286 OptionContainer.format_option_help = format_option_help
287
288
385
386 -def generate_manpage(optparser, pkginfo, section=1, stream=sys.stdout, level=0):
387 """generate a man page from an optik parser"""
388 formatter = ManHelpFormatter()
389 formatter.output_level = level
390 formatter.parser = optparser
391 print >> stream, formatter.format_head(optparser, pkginfo, section)
392 print >> stream, optparser.format_option_help(formatter)
393 print >> stream, formatter.format_tail(pkginfo)
394
395
396 __all__ = ('OptionParser', 'Option', 'OptionGroup', 'OptionValueError',
397 'Values')
398