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