Debian Codegraph @

rpython/config/config.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import optparse
4 from rpython.tool.pairtype import extendabletype
5
6 SUPPRESS_USAGE = optparse.SUPPRESS_USAGE
7
8 class AmbigousOptionError(Exception):
9 pass
10
11 class NoMatchingOptionFound(AttributeError):
12 pass
13
14 class ConfigError(Exception):
15 pass
16
17 class ConflictConfigError(ConfigError):
18 pass
19
20 class Config(object):
21 _cfgimpl_frozen = False
22
23 def __init__(self, descr, parent=None, **overrides):
24 self._cfgimpl_descr = descr
25 self._cfgimpl_value_owners = {}
26 self._cfgimpl_parent = parent
27 self._cfgimpl_values = {}
28 self._cfgimpl_warnings = []
29 self._cfgimpl_build(overrides)
30
31 def _cfgimpl_build(self, overrides):
32 for child in self._cfgimpl_descr._children:
33 if isinstance(child, Option):
34 self._cfgimpl_values[child._name] = child.getdefault()
35 self._cfgimpl_value_owners[child._name] = 'default'
36 elif isinstance(child, OptionDescription):
37 self._cfgimpl_values[child._name] = Config(child, parent=self)
38 self.override(overrides)
39
40 def override(self, overrides):
41 for name, value in overrides.iteritems():
42 homeconfig, name = self._cfgimpl_get_home_by_path(name)
43 homeconfig.setoption(name, value, 'default')
44
45 def copy(self, as_default=False, parent=None):
46 result = Config.__new__(self.__class__)
47 result._cfgimpl_descr = self._cfgimpl_descr
48 result._cfgimpl_value_owners = owners = {}
49 result._cfgimpl_parent = parent
50 result._cfgimpl_values = v = {}
51 for child in self._cfgimpl_descr._children:
52 if isinstance(child, Option):
53 v[child._name] = self._cfgimpl_values[child._name]
54 if as_default:
55 owners[child._name] = 'default'
56 else:
57 owners[child._name] = (
58 self._cfgimpl_value_owners[child._name])
59 elif isinstance(child, OptionDescription):
60 v[child._name] = self._cfgimpl_values[child._name].copy(
61 as_default, parent=result)
62 return result
63
64 def __setattr__(self, name, value):
65 if self._cfgimpl_frozen and getattr(self, name) != value:
66 raise TypeError("trying to change a frozen option object")
67 if name.startswith('_cfgimpl_'):
68 self.__dict__[name] = value
69 return
70 self.setoption(name, value, 'user')
71
72 def __getattr__(self, name):
73 if '.' in name:
74 homeconfig, name = self._cfgimpl_get_home_by_path(name)
75 return getattr(homeconfig, name)
76 if name.startswith('_cfgimpl_'):
77 # if it were in __dict__ it would have been found already
78 raise AttributeError("%s object has no attribute %s" %
79 (self.__class__, name))
80 if name not in self._cfgimpl_values:
81 raise AttributeError("%s object has no attribute %s" %
82 (self.__class__, name))
83 return self._cfgimpl_values[name]
84
85 def __dir__(self):
86 from_type = dir(type(self))
87 from_dict = list(self.__dict__)
88 extras = list(self._cfgimpl_values)
89 return sorted(set(extras + from_type + from_dict))
90
91 def __delattr__(self, name):
92 # XXX if you use delattr you are responsible for all bad things
93 # happening
94 if name.startswith('_cfgimpl_'):
95 del self.__dict__[name]
96 return
97 self._cfgimpl_value_owners[name] = 'default'
98 opt = getattr(self._cfgimpl_descr, name)
99 if isinstance(opt, OptionDescription):
100 raise AttributeError("can't option subgroup")
101 self._cfgimpl_values[name] = getattr(opt, 'default', None)
102
103 def setoption(self, name, value, who):
104 if name not in self._cfgimpl_values:
105 raise AttributeError('unknown option %s' % (name,))
106 child = getattr(self._cfgimpl_descr, name)
107 oldowner = self._cfgimpl_value_owners[child._name]
108 if oldowner not in ("default", "suggested"):
109 oldvalue = getattr(self, name)
110 if oldvalue == value or who in ("default", "suggested"):
111 return
112 raise ConflictConfigError('cannot override value to %s for '
113 'option %s' % (value, name))
114 child.setoption(self, value, who)
115 self._cfgimpl_value_owners[name] = who
116
117 def suggest(self, **kwargs):
118 for name, value in kwargs.items():
119 self.suggestoption(name, value)
120
121 def suggestoption(self, name, value):
122 try:
123 self.setoption(name, value, "suggested")
124 except ConflictConfigError:
125 # setting didn't work, but that is fine, since it is
126 # suggested only
127 pass
128
129 def set(self, **kwargs):
130 all_paths = [p.split(".") for p in self.getpaths()]
131 for key, value in kwargs.iteritems():
132 key_p = key.split('.')
133 candidates = [p for p in all_paths if p[-len(key_p):] == key_p]
134 if len(candidates) == 1:
135 name = '.'.join(candidates[0])
136 homeconfig, name = self._cfgimpl_get_home_by_path(name)
137 homeconfig.setoption(name, value, "user")
138 elif len(candidates) > 1:
139 raise AmbigousOptionError(
140 'more than one option that ends with %s' % (key, ))
141 else:
142 raise NoMatchingOptionFound(
143 'there is no option that matches %s' % (key, ))
144
145 def _cfgimpl_get_home_by_path(self, path):
146 """returns tuple (config, name)"""
147 path = path.split('.')
148 for step in path[:-1]:
149 self = getattr(self, step)
150 return self, path[-1]
151
152 def _cfgimpl_get_toplevel(self):
153 while self._cfgimpl_parent is not None:
154 self = self._cfgimpl_parent
155 return self
156
157 def add_warning(self, warning):
158 self._cfgimpl_get_toplevel()._cfgimpl_warnings.append(warning)
159
160 def get_warnings(self):
161 return self._cfgimpl_get_toplevel()._cfgimpl_warnings
162
163 def _freeze_(self):
164 self.__dict__['_cfgimpl_frozen'] = True
165 return True
166
167 def getkey(self):
168 return self._cfgimpl_descr.getkey(self)
169
170 def __hash__(self):
171 return hash(self.getkey())
172
173 def __eq__(self, other):
174 return self.getkey() == other.getkey()
175
176 def __ne__(self, other):
177 return not self == other
178
179 def __iter__(self):
180 for child in self._cfgimpl_descr._children:
181 if isinstance(child, Option):
182 yield child._name, getattr(self, child._name)
183
184 def __str__(self, indent=""):
185 lines = []
186 children = [(child._name, child)
187 for child in self._cfgimpl_descr._children]
188 children.sort()
189 for name, child in children:
190 if self._cfgimpl_value_owners.get(name, None) == 'default':
191 continue
192 value = getattr(self, name)
193 if isinstance(value, Config):
194 substr = value.__str__(indent + " ")
195 else:
196 substr = "%s %s = %s" % (indent, name, value)
197 if substr:
198 lines.append(substr)
199 if indent and not lines:
200 return '' # hide subgroups with all default values
201 lines.insert(0, "%s[%s]" % (indent, self._cfgimpl_descr._name,))
202 return '\n'.join(lines)
203
204 def getpaths(self, include_groups=False):
205 """returns a list of all paths in self, recursively
206 """
207 return self._cfgimpl_descr.getpaths(include_groups=include_groups)
208
209
210 DEFAULT_OPTION_NAME = object()
211
212
213 class Option(object):
214 __metaclass__ = extendabletype
215
216 def __init__(self, name, doc, cmdline=DEFAULT_OPTION_NAME):
217 self._name = name
218 self.doc = doc
219 self.cmdline = cmdline
220
221 def validate(self, value):
222 raise NotImplementedError('abstract base class')
223
224 def getdefault(self):
225 return self.default
226
227 def setoption(self, config, value, who):
228 name = self._name
229 if who == "default" and value is None:
230 pass
231 elif not self.validate(value):
232 raise ConfigError('invalid value %s for option %s' % (value, name))
233 config._cfgimpl_values[name] = value
234
235 def getkey(self, value):
236 return value
237
238 def convert_from_cmdline(self, value):
239 return value
240
241 def add_optparse_option(self, argnames, parser, config):
242 callback = ConfigUpdate(config, self)
243 parser.add_option(help=self.doc+" %default",
244 action='callback', type=self.opt_type,
245 callback=callback, metavar=self._name.upper(),
246 *argnames)
247
248
249 class ChoiceOption(Option):
250 opt_type = 'string'
251
252 def __init__(self, name, doc, values, default=None, requires=None,
253 suggests=None, cmdline=DEFAULT_OPTION_NAME):
254 super(ChoiceOption, self).__init__(name, doc, cmdline)
255 self.values = values
256 self.default = default
257 if requires is None:
258 requires = {}
259 self._requires = requires
260 if suggests is None:
261 suggests = {}
262 self._suggests = suggests
263
264 def setoption(self, config, value, who):
265 name = self._name
266 for path, reqvalue in self._requires.get(value, []):
267 toplevel = config._cfgimpl_get_toplevel()
268 homeconfig, name = toplevel._cfgimpl_get_home_by_path(path)
269 if who == 'default':
270 who2 = 'default'
271 else:
272 who2 = 'required'
273 homeconfig.setoption(name, reqvalue, who2)
274 for path, reqvalue in self._suggests.get(value, []):
275 toplevel = config._cfgimpl_get_toplevel()
276 homeconfig, name = toplevel._cfgimpl_get_home_by_path(path)
277 homeconfig.suggestoption(name, reqvalue)
278 super(ChoiceOption, self).setoption(config, value, who)
279
280 def validate(self, value):
281 return value is None or value in self.values
282
283 def convert_from_cmdline(self, value):
284 return value.strip()
285
286
287 def _getnegation(optname):
288 if optname.startswith("without"):
289 return "with" + optname[len("without"):]
290 if optname.startswith("with"):
291 return "without" + optname[len("with"):]
292 return "no-" + optname
293
294 class BoolOption(Option):
295 def __init__(self, name, doc, default=None, requires=None,
296 suggests=None, validator=None,
297 cmdline=DEFAULT_OPTION_NAME, negation=True):
298 super(BoolOption, self).__init__(name, doc, cmdline=cmdline)
299 self._requires = requires
300 self._suggests = suggests
301 self.default = default
302 self.negation = negation
303 self._validator = validator
304
305 def validate(self, value):
306 return isinstance(value, bool)
307
308 def setoption(self, config, value, who):
309 name = self._name
310 if value and self._validator is not None:
311 toplevel = config._cfgimpl_get_toplevel()
312 self._validator(toplevel)
313 if value and self._requires is not None:
314 for path, reqvalue in self._requires:
315 toplevel = config._cfgimpl_get_toplevel()
316 homeconfig, name = toplevel._cfgimpl_get_home_by_path(path)
317 if who == 'default':
318 who2 = 'default'
319 else:
320 who2 = 'required'
321 homeconfig.setoption(name, reqvalue, who2)
322 if value and self._suggests is not None:
323 for path, reqvalue in self._suggests:
324 toplevel = config._cfgimpl_get_toplevel()
325 homeconfig, name = toplevel._cfgimpl_get_home_by_path(path)
326 homeconfig.suggestoption(name, reqvalue)
327
328 super(BoolOption, self).setoption(config, value, who)
329
330 def add_optparse_option(self, argnames, parser, config):
331 callback = BoolConfigUpdate(config, self, True)
332 parser.add_option(help=self.doc+" %default",
333 action='callback',
334 callback=callback, *argnames)
335 if not self.negation:
336 return
337 no_argnames = ["--" + _getnegation(argname.lstrip("-"))
338 for argname in argnames
339 if argname.startswith("--")]
340 if len(no_argnames) == 0:
341 no_argnames = ["--" + _getnegation(argname.lstrip("-"))
342 for argname in argnames]
343 callback = BoolConfigUpdate(config, self, False)
344 parser.add_option(help="unset option set by %s %%default" % (argname, ),
345 action='callback',
346 callback=callback, *no_argnames)
347
348
349 class IntOption(Option):
350 opt_type = 'int'
351
352 def __init__(self, name, doc, default=None, cmdline=DEFAULT_OPTION_NAME):
353 super(IntOption, self).__init__(name, doc, cmdline)
354 self.default = default
355
356 def validate(self, value):
357 try:
358 int(value)
359 except TypeError:
360 return False
361 return True
362
363 def setoption(self, config, value, who):
364 try:
365 super(IntOption, self).setoption(config, int(value), who)
366 except TypeError as e:
367 raise ConfigError(*e.args)
368
369
370 class FloatOption(Option):
371 opt_type = 'float'
372
373 def __init__(self, name, doc, default=None, cmdline=DEFAULT_OPTION_NAME):
374 super(FloatOption, self).__init__(name, doc, cmdline)
375 self.default = default
376
377 def validate(self, value):
378 try:
379 float(value)
380 except TypeError:
381 return False
382 return True
383
384 def setoption(self, config, value, who):
385 try:
386 super(FloatOption, self).setoption(config, float(value), who)
387 except TypeError as e:
388 raise ConfigError(*e.args)
389
390
391 class StrOption(Option):
392 opt_type = 'string'
393
394 def __init__(self, name, doc, default=None, cmdline=DEFAULT_OPTION_NAME):
395 super(StrOption, self).__init__(name, doc, cmdline)
396 self.default = default
397
398 def validate(self, value):
399 return isinstance(value, str)
400
401 def setoption(self, config, value, who):
402 try:
403 super(StrOption, self).setoption(config, value, who)
404 except TypeError as e:
405 raise ConfigError(*e.args)
406
407
408 class ArbitraryOption(Option):
409 def __init__(self, name, doc, default=None, defaultfactory=None):
410 super(ArbitraryOption, self).__init__(name, doc, cmdline=None)
411 self.default = default
412 self.defaultfactory = defaultfactory
413 if defaultfactory is not None:
414 assert default is None
415
416 def validate(self, value):
417 return True
418
419 def add_optparse_option(self, *args, **kwargs):
420 return
421
422 def getdefault(self):
423 if self.defaultfactory is not None:
424 return self.defaultfactory()
425 return self.default
426
427
428 class OptionDescription(object):
429 __metaclass__ = extendabletype
430
431 cmdline = None
432
433 def __init__(self, name, doc, children):
434 self._name = name
435 self.doc = doc
436 self._children = children
437 self._build()
438
439 def _build(self):
440 for child in self._children:
441 setattr(self, child._name, child)
442
443 def getkey(self, config):
444 return tuple([child.getkey(getattr(config, child._name))
445 for child in self._children])
446
447 def add_optparse_option(self, argnames, parser, config):
448 return
449
450 def getpaths(self, include_groups=False, currpath=None):
451 """returns a list of all paths in self, recursively
452
453 currpath should not be provided (helps with recursion)
454 """
455 if currpath is None:
456 currpath = []
457 paths = []
458 for option in self._children:
459 attr = option._name
460 if attr.startswith('_cfgimpl'):
461 continue
462 value = getattr(self, attr)
463 if isinstance(value, OptionDescription):
464 if include_groups:
465 paths.append('.'.join(currpath + [attr]))
466 currpath.append(attr)
467 paths += value.getpaths(include_groups=include_groups,
468 currpath=currpath)
469 currpath.pop()
470 else:
471 paths.append('.'.join(currpath + [attr]))
472 return paths
473
474
475 class OptHelpFormatter(optparse.TitledHelpFormatter):
476 extra_useage = None
477
478 def expand_default(self, option):
479 assert self.parser
480 dfls = self.parser.defaults
481 defl = ""
482 choices = None
483 if option.action == 'callback' and isinstance(option.callback, ConfigUpdate):
484 callback = option.callback
485 defl = callback.help_default()
486 if isinstance(callback.option, ChoiceOption):
487 choices = callback.option.values
488 else:
489 val = dfls.get(option.dest)
490 if val is None:
491 pass
492 elif isinstance(val, bool):
493 if val is True and option.action=="store_true":
494 defl = "default"
495 else:
496 defl = "default: %s" % val
497
498 if option.type == 'choice':
499 choices = option.choices
500
501 if choices is not None:
502 choices = "%s=%s" % (option.metavar, '|'.join(choices))
503 else:
504 choices = ""
505
506 if '%default' in option.help:
507 if choices and defl:
508 sep = ", "
509 else:
510 sep = ""
511 defl = '[%s%s%s]' % (choices, sep, defl)
512 if defl == '[]':
513 defl = ""
514 return option.help.replace("%default", defl)
515 elif choices:
516 return option.help + ' [%s]' % choices
517
518 return option.help
519
520 def format_usage(self, usage):
521 # XXX bit of a hack
522 result = optparse.TitledHelpFormatter.format_usage(self, usage)
523 if self.extra_useage is not None:
524 return result + "\n" + self.extra_useage + "\n\n"
525 return result
526
527
528
529 class ConfigUpdate(object):
530
531 def __init__(self, config, option):
532 self.config = config
533 self.option = option
534
535 def convert_from_cmdline(self, value):
536 return self.option.convert_from_cmdline(value)
537
538 def __call__(self, option, opt_str, value, parser, *args, **kwargs):
539 try:
540 value = self.convert_from_cmdline(value)
541 self.config.setoption(self.option._name, value, who='cmdline')
542 except ConfigError as e:
543 # This OptionValueError is going to exit the translate.py process.
544 # Now is the last chance to print the warnings, which might give
545 # more information... hack.
546 import sys
547 for warning in self.config.get_warnings():
548 print(warning, file=sys.stderr)
549 raise optparse.OptionValueError(e.args[0])
550
551 def help_default(self):
552 default = getattr(self.config, self.option._name)
553 owner = self.config._cfgimpl_value_owners[self.option._name]
554 if default is None:
555 if owner == 'default':
556 return ''
557 else:
558 default = '???'
559 return "%s: %s" % (owner, default)
560
561
562 class BoolConfigUpdate(ConfigUpdate):
563 def __init__(self, config, option, which_value):
564 super(BoolConfigUpdate, self).__init__(config, option)
565 self.which_value = which_value
566
567 def convert_from_cmdline(self, value):
568 return self.which_value
569
570 def help_default(self):
571 default = getattr(self.config, self.option._name)
572 owner = self.config._cfgimpl_value_owners[self.option._name]
573 if default == self.which_value:
574 return owner
575 else:
576 return ""
577
578
579 def to_optparse(config, useoptions=None, parser=None,
580 parserargs=None, parserkwargs=None, extra_useage=None):
581 grps = {}
582 def get_group(name, doc):
583 steps = name.split('.')
584 if len(steps) < 2:
585 return parser
586 grpname = steps[-2]
587 grp = grps.get(grpname, None)
588 if grp is None:
589 grp = grps[grpname] = parser.add_option_group(doc)
590 return grp
591
592 if parser is None:
593 if parserargs is None:
594 parserargs = []
595 if parserkwargs is None:
596 parserkwargs = {}
597 formatter = OptHelpFormatter()
598 formatter.extra_useage = extra_useage
599 parser = optparse.OptionParser(
600 formatter=formatter,
601 *parserargs, **parserkwargs)
602 if useoptions is None:
603 useoptions = config.getpaths(include_groups=True)
604 seen = {}
605 for path in useoptions:
606 if path.endswith(".*"):
607 path = path[:-2]
608 homeconf, name = config._cfgimpl_get_home_by_path(path)
609 subconf = getattr(homeconf, name)
610 children = [
611 path + "." + child
612 for child in subconf.getpaths()]
613 useoptions.extend(children)
614 else:
615 if path in seen:
616 continue
617 seen[path] = True
618 homeconf, name = config._cfgimpl_get_home_by_path(path)
619 option = getattr(homeconf._cfgimpl_descr, name)
620 if option.cmdline is DEFAULT_OPTION_NAME:
621 chunks = ('--%s' % (path.replace('.', '-'),),)
622 elif option.cmdline is None:
623 continue
624 else:
625 chunks = option.cmdline.split(' ')
626 grp = get_group(path, homeconf._cfgimpl_descr.doc)
627 option.add_optparse_option(chunks, grp, homeconf)
628 return parser
629
630
631 def make_dict(config):
632 paths = config.getpaths()
633 options = dict([(path, getattr(config, path)) for path in paths])
634 return options