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 from __future__ import print_function
50
51 __docformat__ = "restructuredtext en"
52
53 import re
54 import sys
55 import time
56 from copy import copy
57 from os.path import exists
58
59
60 from optparse import OptionParser as BaseParser, Option as BaseOption, \
61 OptionGroup, OptionContainer, OptionValueError, OptionError, \
62 Values, HelpFormatter, NO_DEFAULT, SUPPRESS_HELP
63
64 try:
65 from mx import DateTime
66 HAS_MX_DATETIME = True
67 except ImportError:
68 HAS_MX_DATETIME = False
69
70 from logilab.common.textutils import splitstrip, TIME_UNITS, BYTE_UNITS, \
71 apply_units
72
73
75 """check a regexp value by trying to compile it
76 return the compiled regexp
77 """
78 if hasattr(value, 'pattern'):
79 return value
80 try:
81 return re.compile(value)
82 except ValueError:
83 raise OptionValueError(
84 "option %s: invalid regexp value: %r" % (opt, value))
85
87 """check a csv value by trying to split it
88 return the list of separated values
89 """
90 if isinstance(value, (list, tuple)):
91 return value
92 try:
93 return splitstrip(value)
94 except ValueError:
95 raise OptionValueError(
96 "option %s: invalid csv value: %r" % (opt, value))
97
99 """check a yn value
100 return true for yes and false for no
101 """
102 if isinstance(value, int):
103 return bool(value)
104 if value in ('y', 'yes'):
105 return True
106 if value in ('n', 'no'):
107 return False
108 msg = "option %s: invalid yn value %r, should be in (y, yes, n, no)"
109 raise OptionValueError(msg % (opt, value))
110
112 """check a named value
113 return a dictionary containing (name, value) associations
114 """
115 if isinstance(value, dict):
116 return value
117 values = []
118 for value in check_csv(option, opt, value):
119 if value.find('=') != -1:
120 values.append(value.split('=', 1))
121 elif value.find(':') != -1:
122 values.append(value.split(':', 1))
123 if values:
124 return dict(values)
125 msg = "option %s: invalid named value %r, should be <NAME>=<VALUE> or \
126 <NAME>:<VALUE>"
127 raise OptionValueError(msg % (opt, value))
128
130 """check a password value (can't be empty)
131 """
132
133 return value
134
136 """check a file value
137 return the filepath
138 """
139 if exists(value):
140 return value
141 msg = "option %s: file %r does not exist"
142 raise OptionValueError(msg % (opt, value))
143
144
146 """check a file value
147 return the filepath
148 """
149 try:
150 return DateTime.strptime(value, "%Y/%m/%d")
151 except DateTime.Error :
152 raise OptionValueError(
153 "expected format of %s is yyyy/mm/dd" % opt)
154
156 """check a color value and returns it
157 /!\ does *not* check color labels (like 'red', 'green'), only
158 checks hexadecimal forms
159 """
160
161 if re.match('[a-z0-9 ]+$', value, re.I):
162 return value
163
164 if re.match('#[a-f0-9]{6}', value, re.I):
165 return value
166
167 msg = "option %s: invalid color : %r, should be either hexadecimal \
168 value or predefined color"
169 raise OptionValueError(msg % (opt, value))
170
175
180
181
183 """override optik.Option to add some new option types
184 """
185 TYPES = BaseOption.TYPES + ('regexp', 'csv', 'yn', 'named', 'password',
186 'multiple_choice', 'file', 'color',
187 'time', 'bytes')
188 ATTRS = BaseOption.ATTRS + ['hide', 'level']
189 TYPE_CHECKER = copy(BaseOption.TYPE_CHECKER)
190 TYPE_CHECKER['regexp'] = check_regexp
191 TYPE_CHECKER['csv'] = check_csv
192 TYPE_CHECKER['yn'] = check_yn
193 TYPE_CHECKER['named'] = check_named
194 TYPE_CHECKER['multiple_choice'] = check_csv
195 TYPE_CHECKER['file'] = check_file
196 TYPE_CHECKER['color'] = check_color
197 TYPE_CHECKER['password'] = check_password
198 TYPE_CHECKER['time'] = check_time
199 TYPE_CHECKER['bytes'] = check_bytes
200 if HAS_MX_DATETIME:
201 TYPES += ('date',)
202 TYPE_CHECKER['date'] = check_date
203
205 BaseOption.__init__(self, *opts, **attrs)
206 if hasattr(self, "hide") and self.hide:
207 self.help = SUPPRESS_HELP
208
210 """FIXME: need to override this due to optik misdesign"""
211 if self.type in ("choice", "multiple_choice"):
212 if self.choices is None:
213 raise OptionError(
214 "must supply a list of choices for type 'choice'", self)
215 elif not isinstance(self.choices, (tuple, list)):
216 raise OptionError(
217 "choices must be a list of strings ('%s' supplied)"
218 % str(type(self.choices)).split("'")[1], self)
219 elif self.choices is not None:
220 raise OptionError(
221 "must not supply choices for type %r" % self.type, self)
222 BaseOption.CHECK_METHODS[2] = _check_choice
223
224
225 - def process(self, opt, value, values, parser):
226
227
228 value = self.convert_value(opt, value)
229 if self.type == 'named':
230 existant = getattr(values, self.dest)
231 if existant:
232 existant.update(value)
233 value = existant
234
235
236
237 return self.take_action(
238 self.action, self.dest, opt, value, values, parser)
239
240
242 """override optik.OptionParser to use our Option class
243 """
246
266
267
268 OptionGroup.level = 0
269
271 return [option for option in group.option_list
272 if (getattr(option, 'level', 0) or 0) <= outputlevel
273 and not option.help is SUPPRESS_HELP]
274
281 OptionContainer.format_option_help = format_option_help
282
283
380
381 -def generate_manpage(optparser, pkginfo, section=1, stream=sys.stdout, level=0):
382 """generate a man page from an optik parser"""
383 formatter = ManHelpFormatter()
384 formatter.output_level = level
385 formatter.parser = optparser
386 print(formatter.format_head(optparser, pkginfo, section), file=stream)
387 print(optparser.format_option_help(formatter), file=stream)
388 print(formatter.format_tail(pkginfo), file=stream)
389
390
391 __all__ = ('OptionParser', 'Option', 'OptionGroup', 'OptionValueError',
392 'Values')
393