58279ecbde031a750e58c2db8b9c8431e2a142dd
[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._impl_getopt())
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__(
257             name, context=context)
258         subpath = self._get_subpath(name)
259         if isinstance(opt_or_descr, DynSymLinkOption):
260             return self.cfgimpl_get_values()._get_cached_item(
261                 opt_or_descr, path=subpath,
262                 validate=validate,
263                 force_permissive=force_permissive)
264         elif isinstance(opt_or_descr, SymLinkOption):  # pragma: no dynoptiondescription cover
265             path = context.cfgimpl_get_description().impl_get_path_by_opt(
266                 opt_or_descr._impl_getopt())
267             return context.getattr(path, validate=validate,
268                                    force_permissive=force_permissive)
269         elif opt_or_descr.impl_is_optiondescription():
270             self.cfgimpl_get_settings().validate_properties(
271                 opt_or_descr, True, False, path=subpath,
272                 force_permissive=force_permissive)
273             return SubConfig(opt_or_descr, self._impl_context, subpath)
274         else:
275             return self.cfgimpl_get_values()._get_cached_item(
276                 opt_or_descr, path=subpath,
277                 validate=validate,
278                 force_permissive=force_permissive)
279
280     def find(self, bytype=None, byname=None, byvalue=undefined, type_='option',
281              check_properties=True, force_permissive=False):
282         """
283             finds a list of options recursively in the config
284
285             :param bytype: Option class (BoolOption, StrOption, ...)
286             :param byname: filter by Option.impl_getname()
287             :param byvalue: filter by the option's value
288             :returns: list of matching Option objects
289         """
290         return self._cfgimpl_get_context()._find(bytype, byname, byvalue,
291                                                  first=False,
292                                                  type_=type_,
293                                                  _subpath=self.cfgimpl_get_path(False),
294                                                  check_properties=check_properties,
295                                                  force_permissive=force_permissive)
296
297     def find_first(self, bytype=None, byname=None, byvalue=undefined,
298                    type_='option', display_error=True, check_properties=True,
299                    force_permissive=False):
300         """
301             finds an option recursively in the config
302
303             :param bytype: Option class (BoolOption, StrOption, ...)
304             :param byname: filter by Option.impl_getname()
305             :param byvalue: filter by the option's value
306             :returns: list of matching Option objects
307         """
308         return self._cfgimpl_get_context()._find(
309             bytype, byname, byvalue, first=True, type_=type_,
310             _subpath=self.cfgimpl_get_path(False), display_error=display_error,
311             check_properties=check_properties,
312             force_permissive=force_permissive)
313
314     def _find(self, bytype, byname, byvalue, first, type_='option',
315               _subpath=None, check_properties=True, display_error=True,
316               force_permissive=False):
317         """
318         convenience method for finding an option that lives only in the subtree
319
320         :param first: return only one option if True, a list otherwise
321         :return: find list or an exception if nothing has been found
322         """
323
324         def _filter_by_value():
325             if byvalue is undefined:
326                 return True
327             try:
328                 value = self.getattr(path, force_permissive=force_permissive)
329                 if isinstance(value, Multi):
330                     return byvalue in value
331                 else:
332                     return value == byvalue
333             # a property is a restriction upon the access of the value
334             except PropertiesOptionError:  # pragma: optional cover
335                 return False
336
337         if type_ not in ('option', 'path', 'value'):  # pragma: optional cover
338             raise ValueError(_('unknown type_ type {0}'
339                                'for _find').format(type_))
340         find_results = []
341         # if value and/or check_properties are set, need all avalaible option
342         # If first one has no good value or not good property check second one
343         # and so on
344         only_first = first is True and byvalue is None and check_properties is None
345         options = self.cfgimpl_get_description().impl_get_options_paths(
346             bytype, byname, _subpath, only_first, self._cfgimpl_get_context())
347         for path, option in options:
348             if not _filter_by_value():
349                 continue
350             #remove option with propertyerror, ...
351             if byvalue is undefined and check_properties:
352                 try:
353                     value = self.getattr(path,
354                                          force_permissive=force_permissive)
355                 except PropertiesOptionError:  # pragma: optional cover
356                     # a property restricts the access of the value
357                     continue
358             if type_ == 'value':
359                 retval = value
360             elif type_ == 'path':
361                 retval = path
362             elif type_ == 'option':
363                 retval = option
364             if first:
365                 return retval
366             else:
367                 find_results.append(retval)
368         return self._find_return_results(find_results, display_error)
369
370     def _find_return_results(self, find_results, display_error):
371         if find_results == []:  # pragma: optional cover
372             if display_error:
373                 raise AttributeError(_("no option found in config"
374                                        " with these criteria"))
375             else:
376                 # translation is slow
377                 raise AttributeError()
378         else:
379             return find_results
380
381     def make_dict(self, flatten=False, _currpath=None, withoption=None,
382                   withvalue=undefined, force_permissive=False):
383         """exports the whole config into a `dict`, for example:
384
385         >>> print cfg.make_dict()
386         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
387
388
389
390         :param flatten: returns a dict(name=value) instead of a dict(path=value)
391                         ::
392
393                             >>> print cfg.make_dict(flatten=True)
394                             {'var5': None, 'var4': None, 'var6': None}
395
396         :param withoption: returns the options that are present in the very same
397                            `OptionDescription` than the `withoption` itself::
398
399                                 >>> print cfg.make_dict(withoption='var1')
400                                 {'od2.var4': None, 'od2.var5': None,
401                                 'od2.var6': None,
402                                 'od2.var1': u'value',
403                                 'od1.var1': None,
404                                 'od1.var3': None,
405                                 'od1.var2': None}
406
407         :param withvalue: returns the options that have the value `withvalue`
408                           ::
409
410                             >>> print c.make_dict(withoption='var1',
411                                                   withvalue=u'value')
412                             {'od2.var4': None,
413                             'od2.var5': None,
414                             'od2.var6': None,
415                             'od2.var1': u'value'}
416
417         :returns: dict of Option's name (or path) and values
418         """
419         pathsvalues = []
420         if _currpath is None:
421             _currpath = []
422         if withoption is None and withvalue is not undefined:  # pragma: optional cover
423             raise ValueError(_("make_dict can't filtering with value without "
424                                "option"))
425         if withoption is not None:
426             context = self._cfgimpl_get_context()
427             for path in context._find(bytype=None, byname=withoption,
428                                       byvalue=withvalue, first=False,
429                                       type_='path', _subpath=self.cfgimpl_get_path(False),
430                                       force_permissive=force_permissive):
431                 path = '.'.join(path.split('.')[:-1])
432                 opt = context.unwrap_from_path(path, force_permissive=True)
433                 mypath = self.cfgimpl_get_path()
434                 if mypath is not None:
435                     if mypath == path:
436                         withoption = None
437                         withvalue = undefined
438                         break
439                     else:
440                         tmypath = mypath + '.'
441                         if not path.startswith(tmypath):  # pragma: optional cover
442                             raise AttributeError(_('unexpected path {0}, '
443                                                    'should start with {1}'
444                                                    '').format(path, mypath))
445                         path = path[len(tmypath):]
446                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
447                                     force_permissive=force_permissive)
448         #withoption can be set to None below !
449         if withoption is None:
450             for opt in self.cfgimpl_get_description().impl_getchildren():
451                 path = opt.impl_getname()
452                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
453                                     force_permissive=force_permissive)
454         if _currpath == []:
455             options = dict(pathsvalues)
456             return options
457         return pathsvalues
458
459     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten,
460                        force_permissive=False):
461         try:
462             if opt.impl_is_optiondescription():
463                 pathsvalues += self.getattr(path,
464                                             force_permissive=force_permissive).make_dict(
465                                                 flatten,
466                                                 _currpath + path.split('.'),
467                                                 force_permissive=force_permissive)
468             else:
469                 value = self.getattr(opt.impl_getname(),
470                                      force_permissive=force_permissive)
471                 if flatten:
472                     name = opt.impl_getname()
473                 else:
474                     name = '.'.join(_currpath + [opt.impl_getname()])
475                 pathsvalues.append((name, value))
476         except PropertiesOptionError:  # pragma: optional cover
477             pass
478
479     def cfgimpl_get_path(self, dyn=True):
480         descr = self.cfgimpl_get_description()
481         if not dyn and descr.impl_is_dynoptiondescription():
482             context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
483             return context_descr.impl_get_path_by_opt(descr._impl_getopt())
484         return self._impl_path
485
486
487 class _CommonConfig(SubConfig):
488     "abstract base class for the Config, GroupConfig and the MetaConfig"
489     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
490
491     def _impl_build_all_caches(self):
492         if not self.cfgimpl_get_description().impl_already_build_caches():
493             self.cfgimpl_get_description().impl_build_cache_consistency()
494             self.cfgimpl_get_description().impl_build_cache_option()
495             self.cfgimpl_get_description().impl_validate_options()
496
497     def read_only(self):
498         "read only is a global config's setting, see `settings.py`"
499         self.cfgimpl_get_settings().read_only()
500
501     def read_write(self):
502         "read write is a global config's setting, see `settings.py`"
503         self.cfgimpl_get_settings().read_write()
504
505     def getowner(self, opt, force_permissive=False):
506         """convenience method to retrieve an option's owner
507         from the config itself
508         """
509         if not isinstance(opt, Option) and \
510                 not isinstance(opt, SymLinkOption) and \
511                 not isinstance(opt, DynSymLinkOption):  # pragma: optional cover
512             raise TypeError(_('opt in getowner must be an option not {0}'
513                               '').format(type(opt)))
514         return self.cfgimpl_get_values().getowner(opt,
515                                                   force_permissive=force_permissive)
516
517     def unwrap_from_path(self, path, force_permissive=False):
518         """convenience method to extract and Option() object from the Config()
519         and it is **fast**: finds the option directly in the appropriate
520         namespace
521
522         :returns: Option()
523         """
524         context = self._cfgimpl_get_context()
525         if '.' in path:
526             homeconfig, path = self.cfgimpl_get_home_by_path(
527                 path, force_permissive=force_permissive)
528             return homeconfig.cfgimpl_get_description().__getattr__(path, context=context)
529         return self.cfgimpl_get_description().__getattr__(path, context=context)
530
531     def cfgimpl_get_path(self, dyn=True):
532         return None
533
534     def cfgimpl_get_meta(self):
535         if self._impl_meta is not None:
536             return self._impl_meta()
537
538     # information
539     def impl_set_information(self, key, value):
540         """updates the information's attribute
541
542         :param key: information's key (ex: "help", "doc"
543         :param value: information's value (ex: "the help string")
544         """
545         self._impl_values.set_information(key, value)
546
547     def impl_get_information(self, key, default=undefined):
548         """retrieves one information's item
549
550         :param key: the item string (ex: "help")
551         """
552         return self._impl_values.get_information(key, default)
553
554     # ----- state
555     def __getstate__(self):
556         if self._impl_meta is not None:
557             raise ConfigError(_('cannot serialize Config with MetaConfig'))  # pragma: optional cover
558         slots = set()
559         for subclass in self.__class__.__mro__:
560             if subclass is not object:
561                 slots.update(subclass.__slots__)
562         slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
563         state = {}
564         for slot in slots:
565             try:
566                 state[slot] = getattr(self, slot)
567             except AttributeError:  # pragma: optional cover
568                 pass
569         storage = self._impl_values._p_._storage
570         if not storage.serializable:
571             raise ConfigError(_('this storage is not serialisable, could be a '
572                               'none persistent storage'))  # pragma: optional cover
573         state['_storage'] = {'session_id': storage.session_id,
574                              'persistent': storage.persistent}
575         state['_impl_setting'] = _impl_getstate_setting()
576         return state
577
578     def __setstate__(self, state):
579         for key, value in state.items():
580             if key not in ['_storage', '_impl_setting']:
581                 setattr(self, key, value)
582         set_storage('config', **state['_impl_setting'])
583         self._impl_context = weakref.ref(self)
584         self._impl_settings.context = weakref.ref(self)
585         self._impl_values.context = weakref.ref(self)
586         storage = get_storage('config', test=self._impl_test, **state['_storage'])
587         self._impl_values._impl_setstate(storage)
588         self._impl_settings._impl_setstate(storage)
589         self._impl_meta = None
590
591
592 # ____________________________________________________________
593 class Config(_CommonConfig):
594     "main configuration management entry"
595     __slots__ = ('__weakref__', '_impl_test')
596
597     def __init__(self, descr, session_id=None, persistent=False):
598         """ Configuration option management master class
599
600         :param descr: describes the configuration schema
601         :type descr: an instance of ``option.OptionDescription``
602         :param context: the current root config
603         :type context: `Config`
604         :param session_id: session ID is import with persistent Config to
605         retrieve good session
606         :type session_id: `str`
607         :param persistent: if persistent, don't delete storage when leaving
608         :type persistent: `boolean`
609         """
610         settings, values = get_storages(self, session_id, persistent)
611         self._impl_settings = Settings(self, settings)
612         self._impl_values = Values(self, values)
613         super(Config, self).__init__(descr, weakref.ref(self))
614         self._impl_build_all_caches()
615         self._impl_meta = None
616         #undocumented option used only in test script
617         self._impl_test = False
618
619     def cfgimpl_reset_cache(self,
620                             only_expired=False,
621                             only=('values', 'settings')):
622         if 'values' in only:
623             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
624         if 'settings' in only:
625             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
626
627
628 class GroupConfig(_CommonConfig):
629     __slots__ = ('_impl_children', '__weakref__')
630
631     def __init__(self, children, session_id=None, persistent=False,
632                  _descr=None):
633         if not isinstance(children, list):
634             raise ValueError(_("metaconfig's children must be a list"))
635         self._impl_children = children
636         settings, values = get_storages(self, session_id, persistent)
637         self._impl_settings = Settings(self, settings)
638         self._impl_values = Values(self, values)
639         super(GroupConfig, self).__init__(_descr, weakref.ref(self))
640         self._impl_meta = None
641         #undocumented option used only in test script
642         self._impl_test = False
643
644     def cfgimpl_get_children(self):
645         return self._impl_children
646
647     #def cfgimpl_get_context(self):
648     #    "a meta config is a config which has a setting, that is itself"
649     #    return self
650     #
651     def cfgimpl_reset_cache(self,
652                             only_expired=False,
653                             only=('values', 'settings')):
654         if 'values' in only:
655             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
656         if 'settings' in only:
657             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
658         for child in self._impl_children:
659             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
660
661     def setattrs(self, path, value):
662         """Setattr not in current GroupConfig, but in each children
663         """
664         for child in self._impl_children:
665             try:
666                 if not isinstance(child, GroupConfig):
667                     setattr(child, path, value)
668                 else:
669                     child.setattrs(path, value)
670             except PropertiesOptionError:
671                 pass
672
673     def find_firsts(self, byname=None, bypath=None, byvalue=undefined,
674                     type_='path', display_error=True):
675         """Find first not in current GroupConfig, but in each children
676         """
677         ret = []
678         #if MetaConfig, all children have same OptionDescription as context
679         #so search only one time for all children
680         try:
681             if bypath is None and byname is not None and \
682                     isinstance(self, MetaConfig):
683                 bypath = self._find(bytype=None, byvalue=undefined, byname=byname,
684                                     first=True, type_='path',
685                                     check_properties=False,
686                                     display_error=display_error)
687                 byname = None
688         except AttributeError:
689             pass
690         for child in self._impl_children:
691             try:
692                 if not isinstance(child, MetaConfig):
693                     if bypath is not None:
694                         #if byvalue is None, try if not raise
695                         value = getattr(child, bypath)
696                         if byvalue is not undefined:
697                             if isinstance(value, Multi):
698                                 if byvalue in value:
699                                     ret.append(child)
700                             else:
701                                 if value == byvalue:
702                                     ret.append(child)
703                         else:
704                             ret.append(child)
705                     else:
706                         ret.append(child.find_first(byname=byname,
707                                                     byvalue=byvalue,
708                                                     type_=type_,
709                                                     display_error=False))
710                 else:
711                     ret.extend(child.find_firsts(byname=byname,
712                                                  bypath=bypath,
713                                                  byvalue=byvalue,
714                                                  type_=type_,
715                                                  display_error=False))
716             except AttributeError:
717                 pass
718         return self._find_return_results(ret, display_error)
719
720
721 class MetaConfig(GroupConfig):
722     __slots__ = tuple()
723
724     def __init__(self, children, session_id=None, persistent=False):
725         descr = None
726         for child in children:
727             if not isinstance(child, _CommonConfig):
728                 raise TypeError(_("metaconfig's children "
729                                   "should be config, not {0}"
730                                   ).format(type(child)))
731             if child.cfgimpl_get_meta() is not None:
732                 raise ValueError(_("child has already a metaconfig's"))
733             if descr is None:
734                 descr = child.cfgimpl_get_description()
735             elif not descr is child.cfgimpl_get_description():
736                 raise ValueError(_('all config in metaconfig must '
737                                    'have the same optiondescription'))
738             child._impl_meta = weakref.ref(self)
739
740         super(MetaConfig, self).__init__(children, session_id, persistent, descr)