04c9cb9f365472fe4a06c9428c81f061ddcd41ae
[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, force_permissive=False, force_properties=None,
218                  validate=True):
219         """use getattr instead of _getattr
220         """
221         return self.getattr(name, force_permissive, force_properties, validate)
222
223     def getattr(self, name, force_permissive=False, force_properties=None,
224                 validate=True):
225         """
226         attribute notation mechanism for accessing the value of an option
227         :param name: attribute name
228         :return: option's value if name is an option name, OptionDescription
229                  otherwise
230         """
231         #FIXME force_properties vraiment utile maintenant ?
232         # attribute access by passing a path,
233         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
234         if '.' in name:
235             homeconfig, name = self.cfgimpl_get_home_by_path(
236                 name, force_permissive=force_permissive,
237                 force_properties=force_properties)
238             return homeconfig.getattr(name, force_permissive=force_permissive,
239                                       force_properties=force_properties,
240                                       validate=validate)
241         opt_or_descr = getattr(self.cfgimpl_get_description(), name)
242         if self._impl_path is None:
243             subpath = name
244         else:
245             subpath = self._impl_path + '.' + name
246         # symlink options
247         #FIXME a gerer plutot dans l'option ca ...
248         #FIXME je n'en sais rien en fait ... :/
249         if isinstance(opt_or_descr, SymLinkOption):
250             context = self._cfgimpl_get_context()
251             path = context.cfgimpl_get_description().impl_get_path_by_opt(
252                 opt_or_descr._opt)
253             return context.getattr(path, validate=validate,
254                                    force_properties=force_properties,
255                                    force_permissive=force_permissive)
256         elif isinstance(opt_or_descr, OptionDescription):
257             self.cfgimpl_get_settings().validate_properties(
258                 opt_or_descr, True, False, path=subpath,
259                 force_permissive=force_permissive,
260                 force_properties=force_properties)
261             return SubConfig(opt_or_descr, self._impl_context, subpath)
262         else:
263             return self.cfgimpl_get_values()._get_cached_item(
264                 opt_or_descr, path=subpath,
265                 validate=validate,
266                 force_properties=force_properties,
267                 force_permissive=force_permissive)
268
269     def find(self, bytype=None, byname=None, byvalue=None, type_='option',
270              check_properties=True, force_permissive=False):
271         """
272             finds a list of options recursively in the config
273
274             :param bytype: Option class (BoolOption, StrOption, ...)
275             :param byname: filter by Option._name
276             :param byvalue: filter by the option's value
277             :returns: list of matching Option objects
278         """
279         return self._cfgimpl_get_context()._find(bytype, byname, byvalue,
280                                                  first=False,
281                                                  type_=type_,
282                                                  _subpath=self.cfgimpl_get_path(),
283                                                  check_properties=check_properties,
284                                                  force_permissive=force_permissive)
285
286     def find_first(self, bytype=None, byname=None, byvalue=None,
287                    type_='option', display_error=True, check_properties=True,
288                    force_permissive=False):
289         """
290             finds an option recursively in the config
291
292             :param bytype: Option class (BoolOption, StrOption, ...)
293             :param byname: filter by Option._name
294             :param byvalue: filter by the option's value
295             :returns: list of matching Option objects
296         """
297         return self._cfgimpl_get_context()._find(
298             bytype, byname, byvalue, first=True, type_=type_,
299             _subpath=self.cfgimpl_get_path(), display_error=display_error,
300             check_properties=check_properties,
301             force_permissive=force_permissive)
302
303     def _find(self, bytype, byname, byvalue, first, type_='option',
304               _subpath=None, check_properties=True, display_error=True,
305               force_permissive=False):
306         """
307         convenience method for finding an option that lives only in the subtree
308
309         :param first: return only one option if True, a list otherwise
310         :return: find list or an exception if nothing has been found
311         """
312         def _filter_by_name():
313             if byname is None or path == byname or \
314                     path.endswith('.' + byname):
315                 return True
316             return False
317
318         def _filter_by_value():
319             if byvalue is None:
320                 return True
321             try:
322                 value = self.getattr(path, force_permissive=force_permissive)
323                 if isinstance(value, Multi):
324                     return byvalue in value
325                 else:
326                     return value == byvalue
327             except PropertiesOptionError:  # a property is a restriction
328                                            # upon the access of the value
329                 return False
330
331         def _filter_by_type():
332             if bytype is None:
333                 return True
334             if isinstance(option, bytype):
335                 return True
336             return False
337
338         if type_ not in ('option', 'path', 'value'):
339             raise ValueError(_('unknown type_ type {0}'
340                                'for _find').format(type_))
341         find_results = []
342         opts, paths = self.cfgimpl_get_description()._cache_paths
343         for index in range(0, len(paths)):
344             option = opts[index]
345             if isinstance(option, OptionDescription):
346                 continue
347             path = paths[index]
348             if _subpath is not None and not path.startswith(_subpath + '.'):
349                 continue
350             if not _filter_by_name():
351                 continue
352             if not _filter_by_value():
353                 continue
354             if not _filter_by_type():
355                 continue
356             #remove option with propertyerror, ...
357             if byvalue is None and check_properties:
358                 try:
359                     value = self.getattr(path,
360                                          force_permissive=force_permissive)
361                 except PropertiesOptionError:
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 == []:
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=None, 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 None:
429             raise ValueError(_("make_dict can't filtering with value without "
430                                "option"))
431         if withoption is not None:
432             mypath = self.cfgimpl_get_path()
433             for path in self._cfgimpl_get_context()._find(bytype=Option,
434                                                           byname=withoption,
435                                                           byvalue=withvalue,
436                                                           first=False,
437                                                           type_='path',
438                                                           _subpath=mypath,
439                                                           force_permissive=force_permissive):
440                 path = '.'.join(path.split('.')[:-1])
441                 opt = self._cfgimpl_get_context().cfgimpl_get_description(
442                 ).impl_get_opt_by_path(path)
443                 if mypath is not None:
444                     if mypath == path:
445                         withoption = None
446                         withvalue = None
447                         break
448                     else:
449                         tmypath = mypath + '.'
450                         if not path.startswith(tmypath):
451                             raise AttributeError(_('unexpected path {0}, '
452                                                    'should start with {1}'
453                                                    '').format(path, mypath))
454                         path = path[len(tmypath):]
455                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
456                                     force_permissive=force_permissive)
457         #withoption can be set to None below !
458         if withoption is None:
459             for opt in self.cfgimpl_get_description().impl_getchildren():
460                 path = opt._name
461                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
462                                     force_permissive=force_permissive)
463         if _currpath == []:
464             options = dict(pathsvalues)
465             return options
466         return pathsvalues
467
468     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten,
469                        force_permissive=False):
470         try:
471             if isinstance(opt, OptionDescription):
472                 pathsvalues += self.getattr(path,
473                                             force_permissive=force_permissive).make_dict(
474                                                 flatten,
475                                                 _currpath + path.split('.'),
476                                                 force_permissive=force_permissive)
477             else:
478                 value = self.getattr(opt._name,
479                                      force_permissive=force_permissive)
480                 if flatten:
481                     name = opt._name
482                 else:
483                     name = '.'.join(_currpath + [opt._name])
484                 pathsvalues.append((name, value))
485         except PropertiesOptionError:
486             pass
487
488     def cfgimpl_get_path(self):
489         descr = self.cfgimpl_get_description()
490         context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
491         return context_descr.impl_get_path_by_opt(descr)
492
493
494 class _CommonConfig(SubConfig):
495     "abstract base class for the Config, GroupConfig and the MetaConfig"
496     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
497
498     def _impl_build_all_paths(self):
499         self.cfgimpl_get_description().impl_build_cache()
500
501     def read_only(self):
502         "read only is a global config's setting, see `settings.py`"
503         self.cfgimpl_get_settings().read_only()
504
505     def read_write(self):
506         "read write is a global config's setting, see `settings.py`"
507         self.cfgimpl_get_settings().read_write()
508
509     def getowner(self, opt, force_permissive=False):
510         """convenience method to retrieve an option's owner
511         from the config itself
512         """
513         if not isinstance(opt, Option) and not isinstance(opt, SymLinkOption):
514             raise TypeError(_('opt in getowner must be an option not {0}'
515                               '').format(type(opt)))
516         return self.cfgimpl_get_values().getowner(opt,
517                                                   force_permissive=force_permissive)
518
519     def unwrap_from_path(self, path, force_permissive=False):
520         """convenience method to extract and Option() object from the Config()
521         and it is **fast**: finds the option directly in the appropriate
522         namespace
523
524         :returns: Option()
525         """
526         if '.' in path:
527             homeconfig, path = self.cfgimpl_get_home_by_path(
528                 path, force_permissive=force_permissive)
529             return getattr(homeconfig.cfgimpl_get_description(), path)
530         return getattr(self.cfgimpl_get_description(), path)
531
532     def cfgimpl_get_path(self):
533         return None
534
535     def cfgimpl_get_meta(self):
536         if self._impl_meta is not None:
537             return self._impl_meta()
538
539     # information
540     def impl_set_information(self, key, value):
541         """updates the information's attribute
542
543         :param key: information's key (ex: "help", "doc"
544         :param value: information's value (ex: "the help string")
545         """
546         self._impl_values.set_information(key, value)
547
548     def impl_get_information(self, key, default=None):
549         """retrieves one information's item
550
551         :param key: the item string (ex: "help")
552         """
553         return self._impl_values.get_information(key, default)
554
555     # ----- state
556     def __getstate__(self):
557         if self._impl_meta is not None:
558             raise ConfigError(_('cannot serialize Config with MetaConfig'))
559         slots = set()
560         for subclass in self.__class__.__mro__:
561             if subclass is not object:
562                 slots.update(subclass.__slots__)
563         slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
564         state = {}
565         for slot in slots:
566             try:
567                 state[slot] = getattr(self, slot)
568             except AttributeError:
569                 pass
570         storage = self._impl_values._p_._storage
571         if not storage.serializable:
572             raise ConfigError(_('this storage is not serialisable, could be a '
573                               'none persistent storage'))
574         state['_storage'] = {'session_id': storage.session_id,
575                              'persistent': storage.persistent}
576         state['_impl_setting'] = _impl_getstate_setting()
577         return state
578
579     def __setstate__(self, state):
580         for key, value in state.items():
581             if key not in ['_storage', '_impl_setting']:
582                 setattr(self, key, value)
583         set_storage(**state['_impl_setting'])
584         self._impl_context = weakref.ref(self)
585         self._impl_settings.context = weakref.ref(self)
586         self._impl_values.context = weakref.ref(self)
587         storage = get_storage(test=self._impl_test, **state['_storage'])
588         self._impl_values._impl_setstate(storage)
589         self._impl_settings._impl_setstate(storage)
590         self._impl_meta = None
591
592
593 # ____________________________________________________________
594 class Config(_CommonConfig):
595     "main configuration management entry"
596     __slots__ = ('__weakref__',)
597
598     def __init__(self, descr, session_id=None, persistent=False):
599         """ Configuration option management master class
600
601         :param descr: describes the configuration schema
602         :type descr: an instance of ``option.OptionDescription``
603         :param context: the current root config
604         :type context: `Config`
605         :param session_id: session ID is import with persistent Config to
606         retrieve good session
607         :type session_id: `str`
608         :param persistent: if persistent, don't delete storage when leaving
609         :type persistent: `boolean`
610         """
611         settings, values = get_storages(self, session_id, persistent)
612         self._impl_settings = Settings(self, settings)
613         self._impl_values = Values(self, values)
614         super(Config, self).__init__(descr, weakref.ref(self))
615         self._impl_build_all_paths()
616         self._impl_meta = None
617         #undocumented option used only in test script
618         self._impl_test = False
619
620     def cfgimpl_reset_cache(self,
621                             only_expired=False,
622                             only=('values', 'settings')):
623         if 'values' in only:
624             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
625         if 'settings' in only:
626             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
627
628
629 class GroupConfig(_CommonConfig):
630     __slots__ = ('_impl_children', '__weakref__')
631
632     def __init__(self, children, session_id=None, persistent=False,
633                  _descr=None):
634         if not isinstance(children, list):
635             raise ValueError(_("metaconfig's children must be a list"))
636         self._impl_children = children
637         settings, values = get_storages(self, session_id, persistent)
638         self._impl_settings = Settings(self, settings)
639         self._impl_values = Values(self, values)
640         super(GroupConfig, self).__init__(_descr, weakref.ref(self))
641         self._impl_meta = None
642         #undocumented option used only in test script
643         self._impl_test = False
644
645     def cfgimpl_get_children(self):
646         return self._impl_children
647
648     #def cfgimpl_get_context(self):
649     #    "a meta config is a config which has a setting, that is itself"
650     #    return self
651     #
652     def cfgimpl_reset_cache(self,
653                             only_expired=False,
654                             only=('values', 'settings')):
655         if 'values' in only:
656             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
657         if 'settings' in only:
658             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
659         for child in self._impl_children:
660             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
661
662     def setattrs(self, path, value):
663         """Setattr not in current GroupConfig, but in each children
664         """
665         for child in self._impl_children:
666             try:
667                 if not isinstance(child, GroupConfig):
668                     setattr(child, path, value)
669                 else:
670                     child.setattrs(path, value)
671             except PropertiesOptionError:
672                 pass
673
674     def find_firsts(self, byname=None, bypath=None, byvalue=None,
675                     type_='path', display_error=True):
676         """Find first not in current GroupConfig, but in each children
677         """
678         ret = []
679         #if MetaConfig, all children have same OptionDescription as context
680         #so search only one time for all children
681         try:
682             if bypath is None and byname is not None and \
683                     isinstance(self, MetaConfig):
684                 bypath = self._find(bytype=None, byvalue=None, byname=byname,
685                                     first=True, type_='path',
686                                     check_properties=False,
687                                     display_error=display_error)
688                 byname = None
689         except AttributeError:
690             pass
691         for child in self._impl_children:
692             try:
693                 if not isinstance(child, MetaConfig):
694                     if bypath is not None:
695                         #if byvalue is None, try if not raise
696                         value = getattr(child, bypath)
697                         if byvalue is not None:
698                             if isinstance(value, Multi):
699                                 if byvalue in value:
700                                     ret.append(child)
701                             else:
702                                 if value == byvalue:
703                                     ret.append(child)
704                         else:
705                             ret.append(child)
706                     else:
707                         ret.append(child.find_first(byname=byname,
708                                                     byvalue=byvalue,
709                                                     type_=type_,
710                                                     display_error=False))
711                 else:
712                     ret.extend(child.find_firsts(byname=byname,
713                                                  bypath=bypath,
714                                                  byvalue=byvalue,
715                                                  type_=type_,
716                                                  display_error=False))
717             except AttributeError:
718                 pass
719         return self._find_return_results(ret, display_error)
720
721
722 class MetaConfig(GroupConfig):
723     __slots__ = tuple()
724
725     def __init__(self, children, session_id=None, persistent=False):
726         descr = None
727         for child in children:
728             if not isinstance(child, _CommonConfig):
729                 raise TypeError(_("metaconfig's children "
730                                   "should be config, not {0}"
731                                   ).format(type(child)))
732             if child.cfgimpl_get_meta() is not None:
733                 raise ValueError(_("child has already a metaconfig's"))
734             if descr is None:
735                 descr = child.cfgimpl_get_description()
736             elif not descr is child.cfgimpl_get_description():
737                 raise ValueError(_('all config in metaconfig must '
738                                    'have the same optiondescription'))
739             child._impl_meta = weakref.ref(self)
740
741         super(MetaConfig, self).__init__(children, session_id, persistent, descr)
742
743
744 def mandatory_warnings(config):
745     #only for retro-compatibility
746     return config.cfgimpl_get_values().mandatory_warnings()