af7266ebb9b211602e0cd98241435f3e6462ef45
[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 from tiramisu.setting import groups, Settings, default_encoding
26 from tiramisu.storage import get_storages, get_storage, set_storage, \
27     _impl_getstate_setting
28 from tiramisu.value import Values, Multi
29 from tiramisu.i18n import _
30
31
32 class SubConfig(object):
33     """Sub configuration management entry.
34     Tree if OptionDescription's responsability. SubConfig are generated
35     on-demand. A Config is also a SubConfig.
36     Root Config is call context below
37     """
38     __slots__ = ('_impl_context', '_impl_descr', '_impl_path')
39
40     def __init__(self, descr, context, subpath=None):
41         """ Configuration option management master class
42
43         :param descr: describes the configuration schema
44         :type descr: an instance of ``option.OptionDescription``
45         :param context: the current root config
46         :type context: `Config`
47         :type subpath: `str` with the path name
48         """
49         # main option description
50         if descr is not None and not isinstance(descr, OptionDescription):
51             raise TypeError(_('descr must be an optiondescription, not {0}'
52                               ).format(type(descr)))
53         self._impl_descr = descr
54         # sub option descriptions
55         if not isinstance(context, weakref.ReferenceType):
56             raise ValueError('context must be a Weakref')
57         self._impl_context = context
58         self._impl_path = subpath
59
60     def cfgimpl_reset_cache(self, only_expired=False, only=('values',
61                                                             'settings')):
62         "remove cache (in context)"
63         self._cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
64
65     def cfgimpl_get_home_by_path(self, path, force_permissive=False,
66                                  force_properties=None):
67         """:returns: tuple (config, name)"""
68         path = path.split('.')
69         for step in path[:-1]:
70             self = self.getattr(step,
71                                 force_permissive=force_permissive,
72                                 force_properties=force_properties)
73         return self, path[-1]
74
75     def __hash__(self):
76         return hash(self.cfgimpl_get_description().impl_getkey(self))
77
78     def __eq__(self, other):
79         "Config's comparison"
80         if not isinstance(other, Config):
81             return False
82         return self.cfgimpl_get_description().impl_getkey(self) == \
83             other.cfgimpl_get_description().impl_getkey(other)
84
85     def __ne__(self, other):
86         "Config's comparison"
87         if not isinstance(other, Config):
88             return True
89         return not self == other
90
91     # ______________________________________________________________________
92     def __iter__(self):
93         """Pythonesque way of parsing group's ordered options.
94         iteration only on Options (not OptionDescriptions)"""
95         for child in self.cfgimpl_get_description().impl_getchildren():
96             if not isinstance(child, OptionDescription):
97                 try:
98                     yield child._name, getattr(self, child._name)
99                 except GeneratorExit:
100                     raise StopIteration
101                 except PropertiesOptionError:
102                     pass  # option with properties
103
104     def iter_all(self, force_permissive=False):
105         """A way of parsing options **and** groups.
106         iteration on Options and OptionDescriptions."""
107         for child in self.cfgimpl_get_description().impl_getchildren():
108             try:
109                 yield child._name, self.getattr(child._name,
110                                                 force_permissive=force_permissive)
111             except GeneratorExit:
112                 raise StopIteration
113             except PropertiesOptionError:
114                 pass  # option with properties
115
116     def iter_groups(self, group_type=None, force_permissive=False):
117         """iteration on groups objects only.
118         All groups are returned if `group_type` is `None`, otherwise the groups
119         can be filtered by categories (families, or whatever).
120
121         :param group_type: if defined, is an instance of `groups.GroupType`
122                            or `groups.MasterGroupType` that lives in
123                            `setting.groups`
124         """
125         if group_type is not None and not isinstance(group_type,
126                                                      groups.GroupType):
127             raise TypeError(_("unknown group_type: {0}").format(group_type))
128         for child in self.cfgimpl_get_description().impl_getchildren():
129             if isinstance(child, OptionDescription):
130                 try:
131                     if group_type is None or (group_type is not None and
132                                               child.impl_get_group_type()
133                                               == group_type):
134                         yield child._name, self.getattr(child._name,
135                                                         force_permissive=force_permissive)
136                 except GeneratorExit:
137                     raise StopIteration
138                 except PropertiesOptionError:
139                     pass
140     # ______________________________________________________________________
141
142     def __str__(self):
143         "Config's string representation"
144         lines = []
145         for name, grp in self.iter_groups():
146             lines.append("[{0}]".format(name))
147         for name, value in self:
148             try:
149                 lines.append("{0} = {1}".format(name, value))
150             except UnicodeEncodeError:
151                 lines.append("{0} = {1}".format(name,
152                                                 value.encode(default_encoding)))
153         return '\n'.join(lines)
154
155     __repr__ = __str__
156
157     def _cfgimpl_get_context(self):
158         """context could be None, we need to test it
159         context is None only if all reference to `Config` object is deleted
160         (for example we delete a `Config` and we manipulate a reference to
161         old `SubConfig`, `Values`, `Multi` or `Settings`)
162         """
163         context = self._impl_context()
164         if context is None:
165             raise ConfigError(_('the context does not exist anymore'))
166         return context
167
168     def cfgimpl_get_description(self):
169         if self._impl_descr is None:
170             raise ConfigError(_('no option description found for this config'
171                                 ' (may be GroupConfig)'))
172         else:
173             return self._impl_descr
174
175     def cfgimpl_get_settings(self):
176         return self._cfgimpl_get_context()._impl_settings
177
178     def cfgimpl_get_values(self):
179         return self._cfgimpl_get_context()._impl_values
180
181     # ____________________________________________________________
182     # attribute methods
183     def __setattr__(self, name, value):
184         "attribute notation mechanism for the setting of the value of an option"
185         if name.startswith('_impl_'):
186             object.__setattr__(self, name, value)
187             return
188         self._setattr(name, value)
189
190     def _setattr(self, name, value, force_permissive=False):
191         if '.' in name:
192             homeconfig, name = self.cfgimpl_get_home_by_path(name)
193             return homeconfig.__setattr__(name, value)
194         child = getattr(self.cfgimpl_get_description(), name)
195         if isinstance(child, OptionDescription):
196             raise TypeError(_("can't assign to an OptionDescription"))
197         elif not isinstance(child, SymLinkOption):
198             if self._impl_path is None:
199                 path = name
200             else:
201                 path = self._impl_path + '.' + name
202             self.cfgimpl_get_values().setitem(child, value, path,
203                                               force_permissive=force_permissive)
204         else:
205             context = self._cfgimpl_get_context()
206             path = context.cfgimpl_get_description().impl_get_path_by_opt(
207                 child._opt)
208             context._setattr(path, value, force_permissive=force_permissive)
209
210     def __delattr__(self, name):
211         child = getattr(self.cfgimpl_get_description(), name)
212         self.cfgimpl_get_values().__delitem__(child)
213
214     def __getattr__(self, name):
215         return self.getattr(name)
216
217     def _getattr(self, name):
218         """use getattr instead of _getattr
219         """
220         return self.getattr(name)
221
222     def getattr(self, name, force_permissive=False, force_properties=None,
223                 validate=True):
224         """
225         attribute notation mechanism for accessing the value of an option
226         :param name: attribute name
227         :return: option's value if name is an option name, OptionDescription
228                  otherwise
229         """
230         # attribute access by passing a path,
231         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
232         if '.' in name:
233             homeconfig, name = self.cfgimpl_get_home_by_path(
234                 name, force_permissive=force_permissive,
235                 force_properties=force_properties)
236             return homeconfig.getattr(name, force_permissive=force_permissive,
237                                       force_properties=force_properties,
238                                       validate=validate)
239         opt_or_descr = getattr(self.cfgimpl_get_description(), name)
240         if self._impl_path is None:
241             subpath = name
242         else:
243             subpath = self._impl_path + '.' + name
244         # symlink options
245         if isinstance(opt_or_descr, SymLinkOption):
246             context = self._cfgimpl_get_context()
247             path = context.cfgimpl_get_description().impl_get_path_by_opt(
248                 opt_or_descr._opt)
249             return context.getattr(path, validate=validate,
250                                    force_properties=force_properties,
251                                    force_permissive=force_permissive)
252         elif isinstance(opt_or_descr, OptionDescription):
253             self.cfgimpl_get_settings().validate_properties(
254                 opt_or_descr, True, False, path=subpath,
255                 force_permissive=force_permissive,
256                 force_properties=force_properties)
257             return SubConfig(opt_or_descr, self._impl_context, subpath)
258         else:
259             return self.cfgimpl_get_values().getitem(
260                 opt_or_descr, path=subpath,
261                 validate=validate,
262                 force_properties=force_properties,
263                 force_permissive=force_permissive)
264
265     def find(self, bytype=None, byname=None, byvalue=None, type_='option',
266              check_properties=True, force_permissive=False):
267         """
268             finds a list of options recursively in the config
269
270             :param bytype: Option class (BoolOption, StrOption, ...)
271             :param byname: filter by Option._name
272             :param byvalue: filter by the option's value
273             :returns: list of matching Option objects
274         """
275         return self._cfgimpl_get_context()._find(bytype, byname, byvalue,
276                                                  first=False,
277                                                  type_=type_,
278                                                  _subpath=self.cfgimpl_get_path(),
279                                                  check_properties=check_properties,
280                                                  force_permissive=force_permissive)
281
282     def find_first(self, bytype=None, byname=None, byvalue=None,
283                    type_='option', display_error=True, check_properties=True,
284                    force_permissive=False):
285         """
286             finds an option recursively in the config
287
288             :param bytype: Option class (BoolOption, StrOption, ...)
289             :param byname: filter by Option._name
290             :param byvalue: filter by the option's value
291             :returns: list of matching Option objects
292         """
293         return self._cfgimpl_get_context()._find(
294             bytype, byname, byvalue, first=True, type_=type_,
295             _subpath=self.cfgimpl_get_path(), display_error=display_error,
296             check_properties=check_properties,
297             force_permissive=force_permissive)
298
299     def _find(self, bytype, byname, byvalue, first, type_='option',
300               _subpath=None, check_properties=True, display_error=True,
301               force_permissive=False):
302         """
303         convenience method for finding an option that lives only in the subtree
304
305         :param first: return only one option if True, a list otherwise
306         :return: find list or an exception if nothing has been found
307         """
308         def _filter_by_name():
309             if byname is None or path == byname or \
310                     path.endswith('.' + byname):
311                 return True
312             return False
313
314         def _filter_by_value():
315             if byvalue is None:
316                 return True
317             try:
318                 value = self.getattr(path, force_permissive=force_permissive)
319                 if isinstance(value, Multi):
320                     return byvalue in value
321                 else:
322                     return value == byvalue
323             except PropertiesOptionError:  # a property is a restriction
324                                            # upon the access of the value
325                 return False
326
327         def _filter_by_type():
328             if bytype is None:
329                 return True
330             if isinstance(option, bytype):
331                 return True
332             return False
333
334         if type_ not in ('option', 'path', 'value'):
335             raise ValueError(_('unknown type_ type {0}'
336                                'for _find').format(type_))
337         find_results = []
338         opts, paths = self.cfgimpl_get_description()._cache_paths
339         for index in range(0, len(paths)):
340             option = opts[index]
341             if isinstance(option, OptionDescription):
342                 continue
343             path = paths[index]
344             if _subpath is not None and not path.startswith(_subpath + '.'):
345                 continue
346             if not _filter_by_name():
347                 continue
348             if not _filter_by_value():
349                 continue
350             if not _filter_by_type():
351                 continue
352             #remove option with propertyerror, ...
353             if byvalue is None and check_properties:
354                 try:
355                     value = self.getattr(path,
356                                          force_permissive=force_permissive)
357                 except PropertiesOptionError:
358                     # a property restricts the access of the value
359                     continue
360             if type_ == 'value':
361                 retval = value
362             elif type_ == 'path':
363                 retval = path
364             elif type_ == 'option':
365                 retval = option
366             if first:
367                 return retval
368             else:
369                 find_results.append(retval)
370         return self._find_return_results(find_results, display_error)
371
372     def _find_return_results(self, find_results, display_error):
373         if find_results == []:
374             if display_error:
375                 raise AttributeError(_("no option found in config"
376                                        " with these criteria"))
377             else:
378                 # translation is slow
379                 raise AttributeError()
380         else:
381             return find_results
382
383     def make_dict(self, flatten=False, _currpath=None, withoption=None,
384                   withvalue=None, force_permissive=False):
385         """exports the whole config into a `dict`, for example:
386
387         >>> print cfg.make_dict()
388         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
389
390
391
392         :param flatten: returns a dict(name=value) instead of a dict(path=value)
393                         ::
394
395                             >>> print cfg.make_dict(flatten=True)
396                             {'var5': None, 'var4': None, 'var6': None}
397
398         :param withoption: returns the options that are present in the very same
399                            `OptionDescription` than the `withoption` itself::
400
401                                 >>> print cfg.make_dict(withoption='var1')
402                                 {'od2.var4': None, 'od2.var5': None,
403                                 'od2.var6': None,
404                                 'od2.var1': u'value',
405                                 'od1.var1': None,
406                                 'od1.var3': None,
407                                 'od1.var2': None}
408
409         :param withvalue: returns the options that have the value `withvalue`
410                           ::
411
412                             >>> print c.make_dict(withoption='var1',
413                                                   withvalue=u'value')
414                             {'od2.var4': None,
415                             'od2.var5': None,
416                             'od2.var6': None,
417                             'od2.var1': u'value'}
418
419         :returns: dict of Option's name (or path) and values
420         """
421         pathsvalues = []
422         if _currpath is None:
423             _currpath = []
424         if withoption is None and withvalue is not None:
425             raise ValueError(_("make_dict can't filtering with value without "
426                                "option"))
427         if withoption is not None:
428             mypath = self.cfgimpl_get_path()
429             for path in self._cfgimpl_get_context()._find(bytype=Option,
430                                                           byname=withoption,
431                                                           byvalue=withvalue,
432                                                           first=False,
433                                                           type_='path',
434                                                           _subpath=mypath,
435                                                           force_permissive=force_permissive):
436                 path = '.'.join(path.split('.')[:-1])
437                 opt = self._cfgimpl_get_context().cfgimpl_get_description(
438                 ).impl_get_opt_by_path(path)
439                 if mypath is not None:
440                     if mypath == path:
441                         withoption = None
442                         withvalue = None
443                         break
444                     else:
445                         tmypath = mypath + '.'
446                         if not path.startswith(tmypath):
447                             raise AttributeError(_('unexpected path {0}, '
448                                                    'should start with {1}'
449                                                    '').format(path, mypath))
450                         path = path[len(tmypath):]
451                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
452                                     force_permissive=force_permissive)
453         #withoption can be set to None below !
454         if withoption is None:
455             for opt in self.cfgimpl_get_description().impl_getchildren():
456                 path = opt._name
457                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
458                                     force_permissive=force_permissive)
459         if _currpath == []:
460             options = dict(pathsvalues)
461             return options
462         return pathsvalues
463
464     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten,
465                        force_permissive=False):
466         try:
467             if isinstance(opt, OptionDescription):
468                 pathsvalues += self.getattr(path,
469                                             force_permissive=force_permissive).make_dict(
470                                                 flatten,
471                                                 _currpath + path.split('.'),
472                                                 force_permissive=force_permissive)
473             else:
474                 value = self.getattr(opt._name,
475                                      force_permissive=force_permissive)
476                 if flatten:
477                     name = opt._name
478                 else:
479                     name = '.'.join(_currpath + [opt._name])
480                 pathsvalues.append((name, value))
481         except PropertiesOptionError:
482             pass
483
484     def cfgimpl_get_path(self):
485         descr = self.cfgimpl_get_description()
486         context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
487         return context_descr.impl_get_path_by_opt(descr)
488
489
490 class _CommonConfig(SubConfig):
491     "abstract base class for the Config, GroupConfig and the MetaConfig"
492     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
493
494     def _impl_build_all_paths(self):
495         self.cfgimpl_get_description().impl_build_cache()
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):
506         """convenience method to retrieve an option's owner
507         from the config itself
508         """
509         if not isinstance(opt, Option) and not isinstance(opt, SymLinkOption):
510             raise TypeError(_('opt in getowner must be an option not {0}'
511                               '').format(type(opt)))
512         return self.cfgimpl_get_values().getowner(opt)
513
514     def unwrap_from_path(self, path, force_permissive=False):
515         """convenience method to extract and Option() object from the Config()
516         and it is **fast**: finds the option directly in the appropriate
517         namespace
518
519         :returns: Option()
520         """
521         if '.' in path:
522             homeconfig, path = self.cfgimpl_get_home_by_path(
523                 path, force_permissive=force_permissive)
524             return getattr(homeconfig.cfgimpl_get_description(), path)
525         return getattr(self.cfgimpl_get_description(), path)
526
527     def cfgimpl_get_path(self):
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=None):
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'))
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:
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'))
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(**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(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__',)
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_paths()
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=None,
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=None, 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 None:
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):
740     #only for retro-compatibility
741     return config.cfgimpl_get_values().mandatory_warnings()