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