d6347c8261ff181644636087e9e15b1cba858d40
[tiramisu.git] / tiramisu / config.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
3 #
4 # This program is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Lesser General Public License as published by the
6 # Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17 # The original `Config` design model is unproudly borrowed from
18 # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
19 # the whole pypy projet is under MIT licence
20 # ____________________________________________________________
21 "options handler global entry point"
22 import weakref
23 from tiramisu.error import PropertiesOptionError, ConfigError
24 from tiramisu.option import OptionDescription, Option, SymLinkOption, \
25     DynSymLinkOption
26 from tiramisu.setting import groups, Settings, default_encoding, undefined
27 from tiramisu.storage import get_storages, get_storage, set_storage, \
28     _impl_getstate_setting
29 from tiramisu.value import Values, Multi
30 from tiramisu.i18n import _
31
32
33 class SubConfig(object):
34     """Sub configuration management entry.
35     Tree if OptionDescription's responsability. SubConfig are generated
36     on-demand. A Config is also a SubConfig.
37     Root Config is call context below
38     """
39     __slots__ = ('_impl_context', '_impl_descr', '_impl_path')
40
41     def __init__(self, descr, context, subpath=None):
42         """ Configuration option management master class
43
44         :param descr: describes the configuration schema
45         :type descr: an instance of ``option.OptionDescription``
46         :param context: the current root config
47         :type context: `Config`
48         :type subpath: `str` with the path name
49         """
50         # main option description
51         error = False
52         try:
53             if descr is not None and not descr.impl_is_optiondescription():  # pragma: optional cover
54                 error = True
55         except AttributeError:
56             error = True
57         if error:
58             raise TypeError(_('descr must be an optiondescription, not {0}'
59                               ).format(type(descr)))
60         self._impl_descr = descr
61         # sub option descriptions
62         if not isinstance(context, weakref.ReferenceType):  # pragma: optional cover
63             raise ValueError('context must be a Weakref')
64         self._impl_context = context
65         self._impl_path = subpath
66
67     def cfgimpl_reset_cache(self, only_expired=False, only=('values',
68                                                             'settings')):
69         "remove cache (in context)"
70         self._cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)  # pragma: optional cover
71
72     def cfgimpl_get_home_by_path(self, path, force_permissive=False):
73         """:returns: tuple (config, name)"""
74         path = path.split('.')
75         for step in path[:-1]:
76             self = self.getattr(step,
77                                 force_permissive=force_permissive)
78         return self, path[-1]
79
80     #def __hash__(self):
81     #FIXME
82     #    return hash(self.cfgimpl_get_description().impl_getkey(self))
83
84     #def __eq__(self, other):
85     #FIXME
86     #    "Config's comparison"
87     #    if not isinstance(other, Config):
88     #        return False
89     #    return self.cfgimpl_get_description().impl_getkey(self) == \
90     #        other.cfgimpl_get_description().impl_getkey(other)
91
92     #def __ne__(self, other):
93     #FIXME
94     #    "Config's comparison"
95     #    if not isinstance(other, Config):
96     #        return True
97     #    return not self == other
98
99     # ______________________________________________________________________
100     def __iter__(self):
101         """Pythonesque way of parsing group's ordered options.
102         iteration only on Options (not OptionDescriptions)"""
103         for child in self.cfgimpl_get_description()._impl_getchildren(
104                 context=self._cfgimpl_get_context()):
105             if not child.impl_is_optiondescription():
106                 try:
107                     name = child.impl_getname()
108                     yield name, getattr(self, name)
109                 except GeneratorExit:  # pragma: optional cover
110                     raise StopIteration
111                 except PropertiesOptionError:  # pragma: optional cover
112                     pass  # option with properties
113
114     def iter_all(self, force_permissive=False):
115         """A way of parsing options **and** groups.
116         iteration on Options and OptionDescriptions."""
117         for child in self.cfgimpl_get_description().impl_getchildren():
118             try:
119                 yield child.impl_getname(), self.getattr(child.impl_getname(),
120                                                          force_permissive=force_permissive)
121             except GeneratorExit:  # pragma: optional cover
122                 raise StopIteration
123             except PropertiesOptionError:  # pragma: optional cover
124                 pass  # option with properties
125
126     def iter_groups(self, group_type=None, force_permissive=False):
127         """iteration on groups objects only.
128         All groups are returned if `group_type` is `None`, otherwise the groups
129         can be filtered by categories (families, or whatever).
130
131         :param group_type: if defined, is an instance of `groups.GroupType`
132                            or `groups.MasterGroupType` that lives in
133                            `setting.groups`
134         """
135         if group_type is not None and not isinstance(group_type,
136                                                      groups.GroupType):  # pragma: optional cover
137             raise TypeError(_("unknown group_type: {0}").format(group_type))
138         for child in self.cfgimpl_get_description()._impl_getchildren(
139                 context=self._cfgimpl_get_context()):
140             if child.impl_is_optiondescription():
141                 try:
142                     if group_type is None or (group_type is not None and
143                                               child.impl_get_group_type()
144                                               == group_type):
145                         name = child.impl_getname()
146                         yield name, self.getattr(name, force_permissive=force_permissive)
147                 except GeneratorExit:  # pragma: optional cover
148                     raise StopIteration
149                 except PropertiesOptionError:  # pragma: optional cover
150                     pass
151     # ______________________________________________________________________
152
153     def __str__(self):
154         "Config's string representation"
155         lines = []
156         for name, grp in self.iter_groups():
157             lines.append("[{0}]".format(name))
158         for name, value in self:
159             try:
160                 lines.append("{0} = {1}".format(name, value))
161             except UnicodeEncodeError:  # pragma: optional cover
162                 lines.append("{0} = {1}".format(name,
163                                                 value.encode(default_encoding)))
164         return '\n'.join(lines)
165
166     __repr__ = __str__
167
168     def _cfgimpl_get_context(self):
169         """context could be None, we need to test it
170         context is None only if all reference to `Config` object is deleted
171         (for example we delete a `Config` and we manipulate a reference to
172         old `SubConfig`, `Values`, `Multi` or `Settings`)
173         """
174         context = self._impl_context()
175         if context is None:  # pragma: optional cover
176             raise ConfigError(_('the context does not exist anymore'))
177         return context
178
179     def cfgimpl_get_description(self):
180         if self._impl_descr is None:  # pragma: optional cover
181             raise ConfigError(_('no option description found for this config'
182                                 ' (may be GroupConfig)'))
183         else:
184             return self._impl_descr
185
186     def cfgimpl_get_settings(self):
187         return self._cfgimpl_get_context()._impl_settings
188
189     def cfgimpl_get_values(self):
190         return self._cfgimpl_get_context()._impl_values
191
192     # ____________________________________________________________
193     # attribute methods
194     def __setattr__(self, name, value):
195         "attribute notation mechanism for the setting of the value of an option"
196         self._setattr(name, value)
197
198     def _setattr(self, name, value, force_permissive=False):
199         if name.startswith('_impl_'):
200             object.__setattr__(self, name, value)
201             return
202         if '.' in name:  # pragma: optional cover
203             homeconfig, name = self.cfgimpl_get_home_by_path(name)
204             return homeconfig._setattr(name, value, force_permissive)
205         context = self._cfgimpl_get_context()
206         child = self.cfgimpl_get_description().__getattr__(name,
207                                                            context=context)
208         if isinstance(child, OptionDescription):
209             raise TypeError(_("can't assign to an OptionDescription"))  # pragma: optional cover
210         elif isinstance(child, SymLinkOption) and \
211                 not isinstance(child, DynSymLinkOption):  # pragma: no dynoptiondescription cover
212             path = context.cfgimpl_get_description().impl_get_path_by_opt(
213                 child._opt)
214             context._setattr(path, value, force_permissive=force_permissive)
215         else:
216             subpath = self._get_subpath(name)
217             self.cfgimpl_get_values().setitem(child, value, subpath,
218                                               force_permissive=force_permissive)
219
220     def __delattr__(self, name):
221         context = self._cfgimpl_get_context()
222         child = self.cfgimpl_get_description().__getattr__(name, context)
223         self.cfgimpl_get_values().__delitem__(child)
224
225     def __getattr__(self, name):
226         return self.getattr(name)
227
228     def _getattr(self, name, force_permissive=False, validate=True):  # pragma: optional cover
229         """use getattr instead of _getattr
230         """
231         return self.getattr(name, force_permissive, validate)
232
233     def _get_subpath(self, name):
234         if self._impl_path is None:
235             subpath = name
236         else:
237             subpath = self._impl_path + '.' + name
238         return subpath
239
240     def getattr(self, name, force_permissive=False, validate=True):
241         """
242         attribute notation mechanism for accessing the value of an option
243         :param name: attribute name
244         :return: option's value if name is an option name, OptionDescription
245                  otherwise
246         """
247         # attribute access by passing a path,
248         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
249         if '.' in name:
250             homeconfig, name = self.cfgimpl_get_home_by_path(
251                 name, force_permissive=force_permissive)
252             return homeconfig.getattr(name, force_permissive=force_permissive,
253                                       validate=validate)
254         context = self._cfgimpl_get_context()
255         opt_or_descr = self.cfgimpl_get_description().__getattr__(name, context=context)
256         subpath = self._get_subpath(name)
257         if isinstance(opt_or_descr, DynSymLinkOption):
258             return self.cfgimpl_get_values()._get_cached_item(
259                 opt_or_descr, path=subpath,
260                 validate=validate,
261                 force_permissive=force_permissive)
262         elif isinstance(opt_or_descr, SymLinkOption):  # pragma: no dynoptiondescription cover
263             path = context.cfgimpl_get_description().impl_get_path_by_opt(
264                 opt_or_descr._opt)
265             return context.getattr(path, validate=validate,
266                                    force_permissive=force_permissive)
267         elif opt_or_descr.impl_is_optiondescription():
268             self.cfgimpl_get_settings().validate_properties(
269                 opt_or_descr, True, False, path=subpath,
270                 force_permissive=force_permissive)
271             return SubConfig(opt_or_descr, self._impl_context, subpath)
272         else:
273             return self.cfgimpl_get_values()._get_cached_item(
274                 opt_or_descr, path=subpath,
275                 validate=validate,
276                 force_permissive=force_permissive)
277
278     def find(self, bytype=None, byname=None, byvalue=undefined, type_='option',
279              check_properties=True, force_permissive=False):
280         """
281             finds a list of options recursively in the config
282
283             :param bytype: Option class (BoolOption, StrOption, ...)
284             :param byname: filter by Option.impl_getname()
285             :param byvalue: filter by the option's value
286             :returns: list of matching Option objects
287         """
288         return self._cfgimpl_get_context()._find(bytype, byname, byvalue,
289                                                  first=False,
290                                                  type_=type_,
291                                                  _subpath=self.cfgimpl_get_path(False),
292                                                  check_properties=check_properties,
293                                                  force_permissive=force_permissive)
294
295     def find_first(self, bytype=None, byname=None, byvalue=undefined,
296                    type_='option', display_error=True, check_properties=True,
297                    force_permissive=False):
298         """
299             finds an option recursively in the config
300
301             :param bytype: Option class (BoolOption, StrOption, ...)
302             :param byname: filter by Option.impl_getname()
303             :param byvalue: filter by the option's value
304             :returns: list of matching Option objects
305         """
306         return self._cfgimpl_get_context()._find(
307             bytype, byname, byvalue, first=True, type_=type_,
308             _subpath=self.cfgimpl_get_path(False), display_error=display_error,
309             check_properties=check_properties,
310             force_permissive=force_permissive)
311
312     def _find(self, bytype, byname, byvalue, first, type_='option',
313               _subpath=None, check_properties=True, display_error=True,
314               force_permissive=False):
315         """
316         convenience method for finding an option that lives only in the subtree
317
318         :param first: return only one option if True, a list otherwise
319         :return: find list or an exception if nothing has been found
320         """
321         def _filter_by_value():
322             if byvalue is undefined:
323                 return True
324             try:
325                 value = self.getattr(path, force_permissive=force_permissive)
326                 if isinstance(value, Multi):
327                     return byvalue in value
328                 else:
329                     return value == byvalue
330             # a property is a restriction upon the access of the value
331             except PropertiesOptionError:  # pragma: optional cover
332                 return False
333
334         if type_ not in ('option', 'path', 'value'):  # pragma: optional cover
335             raise ValueError(_('unknown type_ type {0}'
336                                'for _find').format(type_))
337         find_results = []
338         # if value and/or check_properties are set, need all avalaible option
339         # If first one has no good value or not good property check second one
340         # and so on
341         only_first = first is True and byvalue is None and check_properties is None
342         options = self.cfgimpl_get_description().impl_get_options_paths(
343             bytype, byname, _subpath, only_first, self._cfgimpl_get_context())
344         for path, option in options:
345             if not _filter_by_value():
346                 continue
347             #remove option with propertyerror, ...
348             if byvalue is undefined and check_properties:
349                 try:
350                     value = self.getattr(path,
351                                          force_permissive=force_permissive)
352                 except PropertiesOptionError:  # pragma: optional cover
353                     # a property restricts the access of the value
354                     continue
355             if type_ == 'value':
356                 retval = value
357             elif type_ == 'path':
358                 retval = path
359             elif type_ == 'option':
360                 retval = option
361             if first:
362                 return retval
363             else:
364                 find_results.append(retval)
365         return self._find_return_results(find_results, display_error)
366
367     def _find_return_results(self, find_results, display_error):
368         if find_results == []:  # pragma: optional cover
369             if display_error:
370                 raise AttributeError(_("no option found in config"
371                                        " with these criteria"))
372             else:
373                 # translation is slow
374                 raise AttributeError()
375         else:
376             return find_results
377
378     def make_dict(self, flatten=False, _currpath=None, withoption=None,
379                   withvalue=undefined, force_permissive=False):
380         """exports the whole config into a `dict`, for example:
381
382         >>> print cfg.make_dict()
383         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
384
385
386
387         :param flatten: returns a dict(name=value) instead of a dict(path=value)
388                         ::
389
390                             >>> print cfg.make_dict(flatten=True)
391                             {'var5': None, 'var4': None, 'var6': None}
392
393         :param withoption: returns the options that are present in the very same
394                            `OptionDescription` than the `withoption` itself::
395
396                                 >>> print cfg.make_dict(withoption='var1')
397                                 {'od2.var4': None, 'od2.var5': None,
398                                 'od2.var6': None,
399                                 'od2.var1': u'value',
400                                 'od1.var1': None,
401                                 'od1.var3': None,
402                                 'od1.var2': None}
403
404         :param withvalue: returns the options that have the value `withvalue`
405                           ::
406
407                             >>> print c.make_dict(withoption='var1',
408                                                   withvalue=u'value')
409                             {'od2.var4': None,
410                             'od2.var5': None,
411                             'od2.var6': None,
412                             'od2.var1': u'value'}
413
414         :returns: dict of Option's name (or path) and values
415         """
416         pathsvalues = []
417         if _currpath is None:
418             _currpath = []
419         if withoption is None and withvalue is not undefined:  # pragma: optional cover
420             raise ValueError(_("make_dict can't filtering with value without "
421                                "option"))
422         if withoption is not None:
423             context = self._cfgimpl_get_context()
424             for path in context._find(bytype=None, byname=withoption,
425                                       byvalue=withvalue, first=False,
426                                       type_='path', _subpath=self.cfgimpl_get_path(False),
427                                       force_permissive=force_permissive):
428                 path = '.'.join(path.split('.')[:-1])
429                 opt = context.unwrap_from_path(path, force_permissive=True)
430                 mypath = self.cfgimpl_get_path()
431                 if mypath is not None:
432                     if mypath == path:
433                         withoption = None
434                         withvalue = undefined
435                         break
436                     else:
437                         tmypath = mypath + '.'
438                         if not path.startswith(tmypath):  # pragma: optional cover
439                             raise AttributeError(_('unexpected path {0}, '
440                                                    'should start with {1}'
441                                                    '').format(path, mypath))
442                         path = path[len(tmypath):]
443                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
444                                     force_permissive=force_permissive)
445         #withoption can be set to None below !
446         if withoption is None:
447             for opt in self.cfgimpl_get_description().impl_getchildren():
448                 path = opt.impl_getname()
449                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
450                                     force_permissive=force_permissive)
451         if _currpath == []:
452             options = dict(pathsvalues)
453             return options
454         return pathsvalues
455
456     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten,
457                        force_permissive=False):
458         try:
459             if opt.impl_is_optiondescription():
460                 pathsvalues += self.getattr(path,
461                                             force_permissive=force_permissive).make_dict(
462                                                 flatten,
463                                                 _currpath + path.split('.'),
464                                                 force_permissive=force_permissive)
465             else:
466                 value = self.getattr(opt.impl_getname(),
467                                      force_permissive=force_permissive)
468                 if flatten:
469                     name = opt.impl_getname()
470                 else:
471                     name = '.'.join(_currpath + [opt.impl_getname()])
472                 pathsvalues.append((name, value))
473         except PropertiesOptionError:  # pragma: optional cover
474             pass
475
476     def cfgimpl_get_path(self, dyn=True):
477         descr = self.cfgimpl_get_description()
478         if not dyn and descr.impl_is_dynoptiondescription():
479             context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
480             return context_descr.impl_get_path_by_opt(descr._opt)
481         return self._impl_path
482
483
484 class _CommonConfig(SubConfig):
485     "abstract base class for the Config, GroupConfig and the MetaConfig"
486     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
487
488     def _impl_build_all_caches(self):
489         if not self.cfgimpl_get_description().impl_already_build_caches():
490             self.cfgimpl_get_description().impl_build_cache_consistency()
491             self.cfgimpl_get_description().impl_validate_options()
492             self.cfgimpl_get_description().impl_build_cache_option()
493
494     def read_only(self):
495         "read only is a global config's setting, see `settings.py`"
496         self.cfgimpl_get_settings().read_only()
497
498     def read_write(self):
499         "read write is a global config's setting, see `settings.py`"
500         self.cfgimpl_get_settings().read_write()
501
502     def getowner(self, opt, force_permissive=False):
503         """convenience method to retrieve an option's owner
504         from the config itself
505         """
506         if not isinstance(opt, Option) and not isinstance(opt, SymLinkOption):  # pragma: optional cover
507             raise TypeError(_('opt in getowner must be an option not {0}'
508                               '').format(type(opt)))
509         return self.cfgimpl_get_values().getowner(opt,
510                                                   force_permissive=force_permissive)
511
512     def unwrap_from_path(self, path, force_permissive=False):
513         """convenience method to extract and Option() object from the Config()
514         and it is **fast**: finds the option directly in the appropriate
515         namespace
516
517         :returns: Option()
518         """
519         context = self._cfgimpl_get_context()
520         if '.' in path:
521             homeconfig, path = self.cfgimpl_get_home_by_path(
522                 path, force_permissive=force_permissive)
523             return homeconfig.cfgimpl_get_description().__getattr__(path, context=context)
524         return self.cfgimpl_get_description().__getattr__(path, context=context)
525
526     def cfgimpl_get_path(self, dyn=True):
527         return None
528
529     def cfgimpl_get_meta(self):
530         if self._impl_meta is not None:
531             return self._impl_meta()
532
533     # information
534     def impl_set_information(self, key, value):
535         """updates the information's attribute
536
537         :param key: information's key (ex: "help", "doc"
538         :param value: information's value (ex: "the help string")
539         """
540         self._impl_values.set_information(key, value)
541
542     def impl_get_information(self, key, default=undefined):
543         """retrieves one information's item
544
545         :param key: the item string (ex: "help")
546         """
547         return self._impl_values.get_information(key, default)
548
549     # ----- state
550     def __getstate__(self):
551         if self._impl_meta is not None:
552             raise ConfigError(_('cannot serialize Config with MetaConfig'))  # pragma: optional cover
553         slots = set()
554         for subclass in self.__class__.__mro__:
555             if subclass is not object:
556                 slots.update(subclass.__slots__)
557         slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
558         state = {}
559         for slot in slots:
560             try:
561                 state[slot] = getattr(self, slot)
562             except AttributeError:  # pragma: optional cover
563                 pass
564         storage = self._impl_values._p_._storage
565         if not storage.serializable:
566             raise ConfigError(_('this storage is not serialisable, could be a '
567                               'none persistent storage'))  # pragma: optional cover
568         state['_storage'] = {'session_id': storage.session_id,
569                              'persistent': storage.persistent}
570         state['_impl_setting'] = _impl_getstate_setting()
571         return state
572
573     def __setstate__(self, state):
574         for key, value in state.items():
575             if key not in ['_storage', '_impl_setting']:
576                 setattr(self, key, value)
577         set_storage('config', **state['_impl_setting'])
578         self._impl_context = weakref.ref(self)
579         self._impl_settings.context = weakref.ref(self)
580         self._impl_values.context = weakref.ref(self)
581         storage = get_storage('config', test=self._impl_test, **state['_storage'])
582         self._impl_values._impl_setstate(storage)
583         self._impl_settings._impl_setstate(storage)
584         self._impl_meta = None
585
586
587 # ____________________________________________________________
588 class Config(_CommonConfig):
589     "main configuration management entry"
590     __slots__ = ('__weakref__', '_impl_test')
591
592     def __init__(self, descr, session_id=None, persistent=False):
593         """ Configuration option management master class
594
595         :param descr: describes the configuration schema
596         :type descr: an instance of ``option.OptionDescription``
597         :param context: the current root config
598         :type context: `Config`
599         :param session_id: session ID is import with persistent Config to
600         retrieve good session
601         :type session_id: `str`
602         :param persistent: if persistent, don't delete storage when leaving
603         :type persistent: `boolean`
604         """
605         settings, values = get_storages(self, session_id, persistent)
606         self._impl_settings = Settings(self, settings)
607         self._impl_values = Values(self, values)
608         super(Config, self).__init__(descr, weakref.ref(self))
609         self._impl_build_all_caches()
610         self._impl_meta = None
611         #undocumented option used only in test script
612         self._impl_test = False
613
614     def cfgimpl_reset_cache(self,
615                             only_expired=False,
616                             only=('values', 'settings')):
617         if 'values' in only:
618             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
619         if 'settings' in only:
620             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
621
622
623 class GroupConfig(_CommonConfig):
624     __slots__ = ('_impl_children', '__weakref__')
625
626     def __init__(self, children, session_id=None, persistent=False,
627                  _descr=None):
628         if not isinstance(children, list):
629             raise ValueError(_("metaconfig's children must be a list"))
630         self._impl_children = children
631         settings, values = get_storages(self, session_id, persistent)
632         self._impl_settings = Settings(self, settings)
633         self._impl_values = Values(self, values)
634         super(GroupConfig, self).__init__(_descr, weakref.ref(self))
635         self._impl_meta = None
636         #undocumented option used only in test script
637         self._impl_test = False
638
639     def cfgimpl_get_children(self):
640         return self._impl_children
641
642     #def cfgimpl_get_context(self):
643     #    "a meta config is a config which has a setting, that is itself"
644     #    return self
645     #
646     def cfgimpl_reset_cache(self,
647                             only_expired=False,
648                             only=('values', 'settings')):
649         if 'values' in only:
650             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
651         if 'settings' in only:
652             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
653         for child in self._impl_children:
654             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
655
656     def setattrs(self, path, value):
657         """Setattr not in current GroupConfig, but in each children
658         """
659         for child in self._impl_children:
660             try:
661                 if not isinstance(child, GroupConfig):
662                     setattr(child, path, value)
663                 else:
664                     child.setattrs(path, value)
665             except PropertiesOptionError:
666                 pass
667
668     def find_firsts(self, byname=None, bypath=None, byvalue=undefined,
669                     type_='path', display_error=True):
670         """Find first not in current GroupConfig, but in each children
671         """
672         ret = []
673         #if MetaConfig, all children have same OptionDescription as context
674         #so search only one time for all children
675         try:
676             if bypath is None and byname is not None and \
677                     isinstance(self, MetaConfig):
678                 bypath = self._find(bytype=None, byvalue=undefined, byname=byname,
679                                     first=True, type_='path',
680                                     check_properties=False,
681                                     display_error=display_error)
682                 byname = None
683         except AttributeError:
684             pass
685         for child in self._impl_children:
686             try:
687                 if not isinstance(child, MetaConfig):
688                     if bypath is not None:
689                         #if byvalue is None, try if not raise
690                         value = getattr(child, bypath)
691                         if byvalue is not undefined:
692                             if isinstance(value, Multi):
693                                 if byvalue in value:
694                                     ret.append(child)
695                             else:
696                                 if value == byvalue:
697                                     ret.append(child)
698                         else:
699                             ret.append(child)
700                     else:
701                         ret.append(child.find_first(byname=byname,
702                                                     byvalue=byvalue,
703                                                     type_=type_,
704                                                     display_error=False))
705                 else:
706                     ret.extend(child.find_firsts(byname=byname,
707                                                  bypath=bypath,
708                                                  byvalue=byvalue,
709                                                  type_=type_,
710                                                  display_error=False))
711             except AttributeError:
712                 pass
713         return self._find_return_results(ret, display_error)
714
715
716 class MetaConfig(GroupConfig):
717     __slots__ = tuple()
718
719     def __init__(self, children, session_id=None, persistent=False):
720         descr = None
721         for child in children:
722             if not isinstance(child, _CommonConfig):
723                 raise TypeError(_("metaconfig's children "
724                                   "should be config, not {0}"
725                                   ).format(type(child)))
726             if child.cfgimpl_get_meta() is not None:
727                 raise ValueError(_("child has already a metaconfig's"))
728             if descr is None:
729                 descr = child.cfgimpl_get_description()
730             elif not descr is child.cfgimpl_get_description():
731                 raise ValueError(_('all config in metaconfig must '
732                                    'have the same optiondescription'))
733             child._impl_meta = weakref.ref(self)
734
735         super(MetaConfig, self).__init__(children, session_id, persistent, descr)
736
737
738 def mandatory_warnings(config):  # pragma: optional cover
739     #only for retro-compatibility
740     return config.cfgimpl_get_values().mandatory_warnings()