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