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