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             pathsvalues += getattr(self, path).make_dict(flatten,
438                                                          _currpath +
439                                                          path.split('.'))
440         else:
441             try:
442                 value = self._getattr(opt.impl_getname())
443                 if flatten:
444                     name = opt.impl_getname()
445                 else:
446                     name = '.'.join(_currpath + [opt.impl_getname()])
447                 pathsvalues.append((name, value))
448             except PropertiesOptionError:
449                 pass  # this just a hidden or disabled option
450
451     def cfgimpl_get_path(self):
452         descr = self.cfgimpl_get_description()
453         context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
454         return context_descr.impl_get_path_by_opt(descr)
455
456
457 class _CommonConfig(SubConfig):
458     "abstract base class for the Config, GroupConfig and the MetaConfig"
459     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
460
461     def _impl_build_all_caches(self):
462         if not self.cfgimpl_get_description().impl_already_build_caches():
463             self.cfgimpl_get_description().impl_build_cache_consistency()
464             self.cfgimpl_get_description().impl_validate_options()
465             self.cfgimpl_get_description().impl_build_cache_option()
466
467     def read_only(self):
468         "read only is a global config's setting, see `settings.py`"
469         self.cfgimpl_get_settings().read_only()
470
471     def read_write(self):
472         "read write is a global config's setting, see `settings.py`"
473         self.cfgimpl_get_settings().read_write()
474
475     def getowner(self, opt):
476         """convenience method to retrieve an option's owner
477         from the config itself
478         """
479         if not isinstance(opt, Option) and not isinstance(opt, SymLinkOption):
480             raise TypeError(_('opt in getowner must be an option not {0}'
481                               '').format(type(opt)))
482         return self.cfgimpl_get_values().getowner(opt)
483
484     def unwrap_from_path(self, path, force_permissive=False):
485         """convenience method to extract and Option() object from the Config()
486         and it is **fast**: finds the option directly in the appropriate
487         namespace
488
489         :returns: Option()
490         """
491         if '.' in path:
492             homeconfig, path = self.cfgimpl_get_home_by_path(
493                 path, force_permissive=force_permissive)
494             return getattr(homeconfig.cfgimpl_get_description(), path)
495         return getattr(self.cfgimpl_get_description(), path)
496
497     def cfgimpl_get_path(self):
498         return None
499
500     def cfgimpl_get_meta(self):
501         if self._impl_meta is not None:
502             return self._impl_meta()
503
504     # information
505     def impl_set_information(self, key, value):
506         """updates the information's attribute
507
508         :param key: information's key (ex: "help", "doc"
509         :param value: information's value (ex: "the help string")
510         """
511         self._impl_values.set_information(key, value)
512
513     def impl_get_information(self, key, default=None):
514         """retrieves one information's item
515
516         :param key: the item string (ex: "help")
517         """
518         return self._impl_values.get_information(key, default)
519
520     # ----- state
521     def __getstate__(self):
522         if self._impl_meta is not None:
523             raise ConfigError(_('cannot serialize Config with MetaConfig'))
524         slots = set()
525         for subclass in self.__class__.__mro__:
526             if subclass is not object:
527                 slots.update(subclass.__slots__)
528         slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
529         state = {}
530         for slot in slots:
531             try:
532                 state[slot] = getattr(self, slot)
533             except AttributeError:
534                 pass
535         storage = self._impl_values._p_._storage
536         if not storage.serializable:
537             raise ConfigError(_('this storage is not serialisable, could be a '
538                               'none persistent storage'))
539         state['_storage'] = {'session_id': storage.session_id,
540                              'persistent': storage.persistent}
541         state['_impl_setting'] = _impl_getstate_setting()
542         return state
543
544     def __setstate__(self, state):
545         for key, value in state.items():
546             if key not in ['_storage', '_impl_setting']:
547                 setattr(self, key, value)
548         set_storage(**state['_impl_setting'])
549         self._impl_context = weakref.ref(self)
550         self._impl_settings.context = weakref.ref(self)
551         self._impl_values.context = weakref.ref(self)
552         storage = get_storage(test=self._impl_test, **state['_storage'])
553         self._impl_values._impl_setstate(storage)
554         self._impl_settings._impl_setstate(storage)
555         self._impl_meta = None
556
557
558 # ____________________________________________________________
559 class Config(_CommonConfig):
560     "main configuration management entry"
561     __slots__ = ('__weakref__', '_impl_test')
562
563     def __init__(self, descr, session_id=None, persistent=False):
564         """ Configuration option management master class
565
566         :param descr: describes the configuration schema
567         :type descr: an instance of ``option.OptionDescription``
568         :param context: the current root config
569         :type context: `Config`
570         :param session_id: session ID is import with persistent Config to
571         retrieve good session
572         :type session_id: `str`
573         :param persistent: if persistent, don't delete storage when leaving
574         :type persistent: `boolean`
575         """
576         settings, values = get_storages(self, session_id, persistent)
577         self._impl_settings = Settings(self, settings)
578         self._impl_values = Values(self, values)
579         super(Config, self).__init__(descr, weakref.ref(self))
580         self._impl_build_all_caches()
581         self._impl_meta = None
582         #undocumented option used only in test script
583         self._impl_test = False
584
585     def cfgimpl_reset_cache(self,
586                             only_expired=False,
587                             only=('values', 'settings')):
588         if 'values' in only:
589             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
590         if 'settings' in only:
591             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
592
593
594 class GroupConfig(_CommonConfig):
595     __slots__ = ('_impl_children', '__weakref__')
596
597     def __init__(self, children, session_id=None, persistent=False,
598                  _descr=None):
599         if not isinstance(children, list):
600             raise ValueError(_("metaconfig's children must be a list"))
601         self._impl_children = children
602         settings, values = get_storages(self, session_id, persistent)
603         self._impl_settings = Settings(self, settings)
604         self._impl_values = Values(self, values)
605         super(GroupConfig, self).__init__(_descr, weakref.ref(self))
606         self._impl_meta = None
607         #undocumented option used only in test script
608         self._impl_test = False
609
610     def cfgimpl_get_children(self):
611         return self._impl_children
612
613     #def cfgimpl_get_context(self):
614     #    "a meta config is a config which has a setting, that is itself"
615     #    return self
616     #
617     def cfgimpl_reset_cache(self,
618                             only_expired=False,
619                             only=('values', 'settings')):
620         if 'values' in only:
621             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
622         if 'settings' in only:
623             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
624         for child in self._impl_children:
625             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
626
627     def setattrs(self, path, value):
628         """Setattr not in current GroupConfig, but in each children
629         """
630         for child in self._impl_children:
631             try:
632                 if not isinstance(child, GroupConfig):
633                     setattr(child, path, value)
634                 else:
635                     child.setattrs(path, value)
636             except PropertiesOptionError:
637                 pass
638
639     def find_firsts(self, byname=None, bypath=None, byvalue=None,
640                     type_='path', display_error=True):
641         """Find first not in current GroupConfig, but in each children
642         """
643         ret = []
644         #if MetaConfig, all children have same OptionDescription as context
645         #so search only one time for all children
646         try:
647             if bypath is None and byname is not None and \
648                     isinstance(self, MetaConfig):
649                 bypath = self._find(bytype=None, byvalue=None, byname=byname,
650                                     first=True, type_='path',
651                                     check_properties=False,
652                                     display_error=display_error)
653                 byname = None
654         except AttributeError:
655             pass
656         for child in self._impl_children:
657             try:
658                 if not isinstance(child, MetaConfig):
659                     if bypath is not None:
660                         #if byvalue is None, try if not raise
661                         value = getattr(child, bypath)
662                         if byvalue is not None:
663                             if isinstance(value, Multi):
664                                 if byvalue in value:
665                                     ret.append(child)
666                             else:
667                                 if value == byvalue:
668                                     ret.append(child)
669                         else:
670                             ret.append(child)
671                     else:
672                         ret.append(child.find_first(byname=byname,
673                                                     byvalue=byvalue,
674                                                     type_=type_,
675                                                     display_error=False))
676                 else:
677                     ret.extend(child.find_firsts(byname=byname,
678                                                  bypath=bypath,
679                                                  byvalue=byvalue,
680                                                  type_=type_,
681                                                  display_error=False))
682             except AttributeError:
683                 pass
684         return self._find_return_results(ret, display_error)
685
686
687 class MetaConfig(GroupConfig):
688     __slots__ = tuple()
689
690     def __init__(self, children, session_id=None, persistent=False):
691         descr = None
692         for child in children:
693             if not isinstance(child, _CommonConfig):
694                 raise TypeError(_("metaconfig's children "
695                                   "should be config, not {0}"
696                                   ).format(type(child)))
697             if child.cfgimpl_get_meta() is not None:
698                 raise ValueError(_("child has already a metaconfig's"))
699             if descr is None:
700                 descr = child.cfgimpl_get_description()
701             elif not descr is child.cfgimpl_get_description():
702                 raise ValueError(_('all config in metaconfig must '
703                                    'have the same optiondescription'))
704             child._impl_meta = weakref.ref(self)
705
706         super(MetaConfig, self).__init__(children, session_id, persistent, descr)
707
708
709 def mandatory_warnings(config):
710     """convenience function to trace Options that are mandatory and
711     where no value has been set
712
713     :returns: generator of mandatory Option's path
714
715     """
716     #if value in cache, properties are not calculated
717     config.cfgimpl_reset_cache(only=('values',))
718     for path in config.cfgimpl_get_description().impl_getpaths(
719             include_groups=True):
720         try:
721             config._getattr(path, force_properties=frozenset(('mandatory',)))
722         except PropertiesOptionError as err:
723             if err.proptype == ['mandatory']:
724                 yield path
725     config.cfgimpl_reset_cache(only=('values',))