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