coverage
[tiramisu.git] / tiramisu / config.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
3 #
4 # This program is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Lesser General Public License as published by the
6 # Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17 # The original `Config` design model is unproudly borrowed from
18 # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
19 # the whole pypy projet is under MIT licence
20 # ____________________________________________________________
21 "options handler global entry point"
22 import weakref
23 import sys
24
25
26 from .error import PropertiesOptionError, ConfigError, ConflictError
27 from .option import OptionDescription, Option, SymLinkOption, \
28     DynSymLinkOption, SynDynOptionDescription
29 from .option.baseoption import valid_name
30 from .setting import groups, Settings, default_encoding, undefined
31 from .storage import get_storages, get_storage, set_storage, \
32     _impl_getstate_setting, get_storages_validation
33 from .value import Values, Multi
34 from .i18n import _
35
36
37 if sys.version_info[0] >= 3:  # pragma: optional cover
38     xrange = range
39
40
41 class SubConfig(object):
42     """Sub configuration management entry.
43     Tree if OptionDescription's responsability. SubConfig are generated
44     on-demand. A Config is also a SubConfig.
45     Root Config is call context below
46     """
47     __slots__ = ('_impl_context', '_impl_descr', '_impl_path')
48
49     def __init__(self, descr, context, subpath=None):
50         """ Configuration option management master class
51
52         :param descr: describes the configuration schema
53         :type descr: an instance of ``option.OptionDescription``
54         :param context: the current root config
55         :type context: `Config`
56         :type subpath: `str` with the path name
57         """
58         # main option description
59         error = False
60         if descr is not None and not isinstance(descr, OptionDescription) and \
61                 not isinstance(descr, SynDynOptionDescription):  # pragma: optional cover
62             error = True
63         if error:
64             raise TypeError(_('descr must be an optiondescription, not {0}'
65                               ).format(type(descr)))
66         self._impl_descr = descr
67         # sub option descriptions
68         if not isinstance(context, weakref.ReferenceType):  # pragma: optional cover
69             raise ValueError('context must be a Weakref')
70         self._impl_context = context
71         self._impl_path = subpath
72
73     def cfgimpl_reset_cache(self, only_expired=False, only=('values',
74                                                             'settings')):
75         "remove cache (in context)"
76         self._cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)  # pragma: optional cover
77
78     def cfgimpl_get_home_by_path(self, path, force_permissive=False,
79                                  returns_raise=False):
80         """:returns: tuple (config, name)"""
81         path = path.split('.')
82         for step in path[:-1]:
83             self = self.getattr(step,
84                                 force_permissive=force_permissive,
85                                 returns_raise=returns_raise)
86         return self, path[-1]
87
88     #def __hash__(self):
89     #FIXME
90     #    return hash(self.cfgimpl_get_description().impl_getkey(self))
91
92     #def __eq__(self, other):
93     #FIXME
94     #    "Config's comparison"
95     #    if not isinstance(other, Config):
96     #        return False
97     #    return self.cfgimpl_get_description().impl_getkey(self) == \
98     #        other.cfgimpl_get_description().impl_getkey(other)
99
100     #def __ne__(self, other):
101     #FIXME
102     #    "Config's comparison"
103     #    if not isinstance(other, Config):
104     #        return True
105     #    return not self == other
106
107     # ______________________________________________________________________
108     def __iter__(self, force_permissive=False):
109         """Pythonesque way of parsing group's ordered options.
110         iteration only on Options (not OptionDescriptions)"""
111         for child in self.cfgimpl_get_description()._impl_getchildren(
112                 context=self._cfgimpl_get_context()):
113             if not child.impl_is_optiondescription():
114                 try:
115                     name = child.impl_getname()
116                     yield name, self.getattr(name,
117                                              force_permissive=force_permissive)
118                 except GeneratorExit:  # pragma: optional cover
119                     raise StopIteration
120                 except PropertiesOptionError:  # pragma: optional cover
121                     pass  # option with properties
122
123     def iter_all(self, force_permissive=False):
124         """A way of parsing options **and** groups.
125         iteration on Options and OptionDescriptions."""
126         for child in self.cfgimpl_get_description().impl_getchildren():
127             try:
128                 yield child.impl_getname(), self.getattr(child.impl_getname(),
129                                                          force_permissive=force_permissive)
130             except GeneratorExit:  # pragma: optional cover
131                 raise StopIteration
132             except PropertiesOptionError:  # pragma: optional cover
133                 pass  # option with properties
134
135     def iter_groups(self, group_type=None, force_permissive=False):
136         """iteration on groups objects only.
137         All groups are returned if `group_type` is `None`, otherwise the groups
138         can be filtered by categories (families, or whatever).
139
140         :param group_type: if defined, is an instance of `groups.GroupType`
141                            or `groups.MasterGroupType` that lives in
142                            `setting.groups`
143         """
144         if group_type is not None and not isinstance(group_type,
145                                                      groups.GroupType):  # pragma: optional cover
146             raise TypeError(_("unknown group_type: {0}").format(group_type))
147         for child in self.cfgimpl_get_description()._impl_getchildren(
148                 context=self._cfgimpl_get_context()):
149             if child.impl_is_optiondescription():
150                 try:
151                     if group_type is None or (group_type is not None and
152                                               child.impl_get_group_type()
153                                               == group_type):
154                         name = child.impl_getname()
155                         yield name, self.getattr(name, force_permissive=force_permissive)
156                 except GeneratorExit:  # pragma: optional cover
157                     raise StopIteration
158                 except PropertiesOptionError:  # pragma: optional cover
159                     pass
160     # ______________________________________________________________________
161
162     def __str__(self):
163         "Config's string representation"
164         lines = []
165         for name, grp in self.iter_groups():
166             lines.append("[{0}]".format(name))
167         for name, value in self:
168             try:
169                 lines.append("{0} = {1}".format(name, value))
170             except UnicodeEncodeError:  # pragma: optional cover
171                 lines.append("{0} = {1}".format(name,
172                                                 value.encode(default_encoding)))
173         return '\n'.join(lines)
174
175     __repr__ = __str__
176
177     def _cfgimpl_get_context(self):
178         """context could be None, we need to test it
179         context is None only if all reference to `Config` object is deleted
180         (for example we delete a `Config` and we manipulate a reference to
181         old `SubConfig`, `Values`, `Multi` or `Settings`)
182         """
183         context = self._impl_context()
184         if context is None:  # pragma: optional cover
185             raise ConfigError(_('the context does not exist anymore'))
186         return context
187
188     def cfgimpl_get_description(self):
189         if self._impl_descr is None:  # pragma: optional cover
190             raise ConfigError(_('no option description found for this config'
191                                 ' (may be GroupConfig)'))
192         else:
193             return self._impl_descr
194
195     def cfgimpl_get_settings(self):
196         return self._cfgimpl_get_context()._impl_settings
197
198     def cfgimpl_get_values(self):
199         return self._cfgimpl_get_context()._impl_values
200
201     # ____________________________________________________________
202     # attribute methods
203     def __setattr__(self, name, value):
204         "attribute notation mechanism for the setting of the value of an option"
205         self.setattr(name, value)
206
207     def _setattr(self, name, value, force_permissive=False, not_raises=False):
208         """use setattr instead of _setattr
209         """
210         self.setattr(name, value, force_permissive=force_permissive,
211                      not_raises=not_raises)
212
213     def setattr(self, name, value, force_permissive=False, not_raises=False):
214         if name.startswith('_impl_'):
215             object.__setattr__(self, name, value)
216             return
217         if '.' in name:  # pragma: optional cover
218             homeconfig, name = self.cfgimpl_get_home_by_path(name,
219                                                              force_permissive=force_permissive)
220             return homeconfig.setattr(name, value, force_permissive,
221                                       not_raises)
222         context = self._cfgimpl_get_context()
223         child = self.cfgimpl_get_description().__getattr__(name,
224                                                            context=context)
225         if isinstance(child, OptionDescription) or isinstance(child, SynDynOptionDescription):
226             raise TypeError(_("can't assign to an OptionDescription"))  # pragma: optional cover
227         elif isinstance(child, SymLinkOption) and \
228                 not isinstance(child, DynSymLinkOption):  # pragma: no dynoptiondescription cover
229             path = context.cfgimpl_get_description().impl_get_path_by_opt(
230                 child._impl_getopt())
231             context.setattr(path, value, force_permissive, not_raises)
232         else:
233             subpath = self._get_subpath(name)
234             self.cfgimpl_get_values().setitem(child, value, subpath,
235                                               force_permissive=force_permissive,
236                                               not_raises=not_raises)
237
238     def __delattr__(self, name):
239         context = self._cfgimpl_get_context()
240         child = self.cfgimpl_get_description().__getattr__(name, context)
241         self.cfgimpl_get_values().__delitem__(child)
242
243     def __getattr__(self, name):
244         return self.getattr(name)
245
246     def _getattr(self, name, force_permissive=False, validate=True):  # pragma: optional cover
247         """use getattr instead of _getattr
248         """
249         return self.getattr(name, force_permissive, validate)
250
251     def _get_subpath(self, name):
252         if self._impl_path is None:
253             subpath = name
254         else:
255             subpath = self._impl_path + '.' + name
256         return subpath
257
258     def getattr(self, name, force_permissive=False, validate=True,
259                 _setting_properties=undefined, _self_properties=undefined, index=None,
260                 returns_raise=False):
261         """
262         attribute notation mechanism for accessing the value of an option
263         :param name: attribute name
264         :return: option's value if name is an option name, OptionDescription
265                  otherwise
266         """
267         # attribute access by passing a path,
268         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
269         if '.' in name:
270             homeconfig, name = self.cfgimpl_get_home_by_path(
271                 name, force_permissive=force_permissive,
272                 returns_raise=returns_raise)
273             cfg = homeconfig.getattr(name, force_permissive=force_permissive,
274                                      validate=validate,
275                                      _setting_properties=_setting_properties,
276                                      _self_properties=_self_properties,
277                                      index=index, returns_raise=returns_raise)
278         else:
279             context = self._cfgimpl_get_context()
280             option = self.cfgimpl_get_description().__getattr__(name,
281                                                                 context=context)
282             subpath = self._get_subpath(name)
283             if isinstance(option, DynSymLinkOption):
284                 cfg = self.cfgimpl_get_values()._get_cached_value(
285                     option, path=subpath,
286                     validate=validate,
287                     force_permissive=force_permissive,
288                     setting_properties=_setting_properties,
289                     self_properties=_self_properties,
290                     index=index)
291             elif isinstance(option, SymLinkOption):  # pragma: no dynoptiondescription cover
292                 path = context.cfgimpl_get_description().impl_get_path_by_opt(
293                     option._impl_getopt())
294                 cfg = context.getattr(path, validate=validate,
295                                        force_permissive=force_permissive,
296                                        _setting_properties=_setting_properties,
297                                        _self_properties=_self_properties,
298                                        index=index, returns_raise=True)
299             elif option.impl_is_optiondescription():
300                 props = self.cfgimpl_get_settings().validate_properties(
301                     option, True, False, path=subpath,
302                     force_permissive=force_permissive,
303                     self_properties=_self_properties,
304                     setting_properties=_setting_properties)
305                 if props:
306                     if returns_raise:
307                         return props
308                     else:
309                         raise props
310                 return SubConfig(option, self._impl_context, subpath)
311             else:
312                 cfg = self.cfgimpl_get_values()._get_cached_value(
313                     option, path=subpath,
314                     validate=validate,
315                     force_permissive=force_permissive,
316                     setting_properties=_setting_properties,
317                     self_properties=_self_properties,
318                     index=index)
319         if not returns_raise and isinstance(cfg, Exception):
320             raise cfg
321         return cfg
322
323     def find(self, bytype=None, byname=None, byvalue=undefined, type_='option',
324              check_properties=True, force_permissive=False):
325         """
326             finds a list of options recursively in the config
327
328             :param bytype: Option class (BoolOption, StrOption, ...)
329             :param byname: filter by Option.impl_getname()
330             :param byvalue: filter by the option's value
331             :returns: list of matching Option objects
332         """
333         return self._cfgimpl_get_context()._find(bytype, byname, byvalue,
334                                                  first=False,
335                                                  type_=type_,
336                                                  _subpath=self.cfgimpl_get_path(False),
337                                                  check_properties=check_properties,
338                                                  force_permissive=force_permissive)
339
340     def find_first(self, bytype=None, byname=None, byvalue=undefined,
341                    type_='option', raise_if_not_found=True, check_properties=True,
342                    force_permissive=False):
343         """
344             finds an option recursively in the config
345
346             :param bytype: Option class (BoolOption, StrOption, ...)
347             :param byname: filter by Option.impl_getname()
348             :param byvalue: filter by the option's value
349             :returns: list of matching Option objects
350         """
351         return self._cfgimpl_get_context()._find(
352             bytype, byname, byvalue, first=True, type_=type_,
353             _subpath=self.cfgimpl_get_path(False), raise_if_not_found=raise_if_not_found,
354             check_properties=check_properties,
355             force_permissive=force_permissive)
356
357     def _find(self, bytype, byname, byvalue, first, type_='option',
358               _subpath=None, check_properties=True, raise_if_not_found=True,
359               force_permissive=False, only_path=undefined,
360               only_option=undefined, setting_properties=undefined):
361         """
362         convenience method for finding an option that lives only in the subtree
363
364         :param first: return only one option if True, a list otherwise
365         :return: find list or an exception if nothing has been found
366         """
367
368         def _filter_by_value():
369             if byvalue is undefined:
370                 return True
371             value = self.getattr(path, force_permissive=force_permissive,
372                                  _setting_properties=setting_properties,
373                                  returns_raise=True)
374             if isinstance(value, Exception):
375                 if isinstance(value, PropertiesOptionError):
376                     return False
377                 raise value
378             elif isinstance(value, Multi):
379                 return byvalue in value
380             else:
381                 return value == byvalue
382
383         if type_ not in ('option', 'path', 'value'):  # pragma: optional cover
384             raise ValueError(_('unknown type_ type {0}'
385                                'for _find').format(type_))
386         find_results = []
387         # if value and/or check_properties are set, need all avalaible option
388         # If first one has no good value or not good property check second one
389         # and so on
390         only_first = first is True and byvalue is None and \
391             check_properties is None
392         if only_path is not undefined:
393             options = [(only_path, only_option)]
394         else:
395             options = self.cfgimpl_get_description().impl_get_options_paths(
396                 bytype, byname, _subpath, only_first,
397                 self._cfgimpl_get_context())
398         for path, option in options:
399             if not _filter_by_value():
400                 continue
401             #remove option with propertyerror, ...
402             if byvalue is undefined and check_properties:
403                 value = self.getattr(path,
404                                      force_permissive=force_permissive,
405                                      _setting_properties=setting_properties,
406                                      returns_raise=True)
407                 if isinstance(value, Exception):
408                     if isinstance(value, PropertiesOptionError):
409                         continue
410                     else:
411                         raise value
412             if type_ == 'value':
413                 retval = value
414             elif type_ == 'path':
415                 retval = path
416             elif type_ == 'option':
417                 retval = option
418             if first:
419                 return retval
420             else:
421                 find_results.append(retval)
422         return self._find_return_results(find_results, raise_if_not_found)
423
424     def _find_return_results(self, find_results, raise_if_not_found):
425         if find_results == []:  # pragma: optional cover
426             if raise_if_not_found:
427                 raise AttributeError(_("no option found in config"
428                                        " with these criteria"))
429         else:
430             return find_results
431
432     def make_dict(self, flatten=False, _currpath=None, withoption=None,
433                   withvalue=undefined, force_permissive=False,
434                   setting_properties=undefined):
435         """exports the whole config into a `dict`, for example:
436
437         >>> print cfg.make_dict()
438         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
439
440
441
442         :param flatten: returns a dict(name=value) instead of a dict(path=value)
443                         ::
444
445                             >>> print cfg.make_dict(flatten=True)
446                             {'var5': None, 'var4': None, 'var6': None}
447
448         :param withoption: returns the options that are present in the very same
449                            `OptionDescription` than the `withoption` itself::
450
451                                 >>> print cfg.make_dict(withoption='var1')
452                                 {'od2.var4': None, 'od2.var5': None,
453                                 'od2.var6': None,
454                                 'od2.var1': u'value',
455                                 'od1.var1': None,
456                                 'od1.var3': None,
457                                 'od1.var2': None}
458
459         :param withvalue: returns the options that have the value `withvalue`
460                           ::
461
462                             >>> print c.make_dict(withoption='var1',
463                                                   withvalue=u'value')
464                             {'od2.var4': None,
465                             'od2.var5': None,
466                             'od2.var6': None,
467                             'od2.var1': u'value'}
468
469         :returns: dict of Option's name (or path) and values
470         """
471         pathsvalues = []
472         if _currpath is None:
473             _currpath = []
474         if withoption is None and withvalue is not undefined:  # pragma: optional cover
475             raise ValueError(_("make_dict can't filtering with value without "
476                                "option"))
477         if setting_properties is undefined:
478             setting_properties = self.cfgimpl_get_settings()._getproperties(
479                 read_write=False)
480         if withoption is not None:
481             context = self._cfgimpl_get_context()
482             for path in context._find(bytype=None, byname=withoption,
483                                       byvalue=withvalue, first=False,
484                                       type_='path', _subpath=self.cfgimpl_get_path(False),
485                                       force_permissive=force_permissive,
486                                       setting_properties=setting_properties):
487                 path = '.'.join(path.split('.')[:-1])
488                 opt = context.unwrap_from_path(path, force_permissive=True)
489                 mypath = self.cfgimpl_get_path()
490                 if mypath is not None:
491                     if mypath == path:
492                         withoption = None
493                         withvalue = undefined
494                         break
495                     else:
496                         tmypath = mypath + '.'
497                         if not path.startswith(tmypath):  # pragma: optional cover
498                             raise AttributeError(_('unexpected path {0}, '
499                                                    'should start with {1}'
500                                                    '').format(path, mypath))
501                         path = path[len(tmypath):]
502                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
503                                     force_permissive=force_permissive,
504                                     setting_properties=setting_properties)
505         #withoption can be set to None below !
506         if withoption is None:
507             for opt in self.cfgimpl_get_description().impl_getchildren():
508                 path = opt.impl_getname()
509                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
510                                     force_permissive=force_permissive,
511                                     setting_properties=setting_properties)
512         if _currpath == []:
513             options = dict(pathsvalues)
514             return options
515         return pathsvalues
516
517     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten,
518                        setting_properties, force_permissive=False):
519         value = self.getattr(path,
520                              force_permissive=force_permissive,
521                              _setting_properties=setting_properties,
522                              returns_raise=True)
523         if isinstance(value, Exception):
524             if not isinstance(value, PropertiesOptionError):
525                 raise value
526         else:
527             if opt.impl_is_optiondescription():
528                     pathsvalues += value.make_dict(flatten,
529                                                    _currpath + path.split('.'),
530                                                    force_permissive=force_permissive,
531                                                    setting_properties=setting_properties)
532             else:
533                 if flatten:
534                     name = opt.impl_getname()
535                 else:
536                     name = '.'.join(_currpath + [opt.impl_getname()])
537                 pathsvalues.append((name, value))
538
539     def cfgimpl_get_path(self, dyn=True):
540         descr = self.cfgimpl_get_description()
541         if not dyn and descr.impl_is_dynoptiondescription():
542             context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
543             return context_descr.impl_get_path_by_opt(descr._impl_getopt())
544         return self._impl_path
545
546
547 class _CommonConfig(SubConfig):
548     "abstract base class for the Config, GroupConfig and the MetaConfig"
549     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
550
551     def _impl_build_all_caches(self):
552         descr = self.cfgimpl_get_description()
553         if not descr.impl_already_build_caches():
554             descr.impl_build_cache_option()
555             descr.impl_build_cache(self)
556         descr.impl_build_force_store_values(self)
557
558     def read_only(self):
559         "read only is a global config's setting, see `settings.py`"
560         self.cfgimpl_get_settings().read_only()
561
562     def read_write(self):
563         "read write is a global config's setting, see `settings.py`"
564         self.cfgimpl_get_settings().read_write()
565
566     def getowner(self, opt, index=None, force_permissive=False):
567         """convenience method to retrieve an option's owner
568         from the config itself
569         """
570         if not isinstance(opt, Option) and \
571                 not isinstance(opt, SymLinkOption) and \
572                 not isinstance(opt, DynSymLinkOption):  # pragma: optional cover
573             raise TypeError(_('opt in getowner must be an option not {0}'
574                               '').format(type(opt)))
575         return self.cfgimpl_get_values().getowner(opt, index=index,
576                                                   force_permissive=force_permissive)
577
578     def unwrap_from_path(self, path, force_permissive=False):
579         """convenience method to extract and Option() object from the Config()
580         and it is **fast**: finds the option directly in the appropriate
581         namespace
582
583         :returns: Option()
584         """
585         context = self._cfgimpl_get_context()
586         if '.' in path:
587             homeconfig, path = self.cfgimpl_get_home_by_path(
588                 path, force_permissive=force_permissive)
589             return homeconfig.cfgimpl_get_description().__getattr__(path, context=context)
590         return self.cfgimpl_get_description().__getattr__(path, context=context)
591
592     def cfgimpl_get_path(self, dyn=True):
593         return None
594
595     def cfgimpl_get_meta(self):
596         if self._impl_meta is not None:
597             return self._impl_meta()
598
599     # information
600     def impl_set_information(self, key, value):
601         """updates the information's attribute
602
603         :param key: information's key (ex: "help", "doc"
604         :param value: information's value (ex: "the help string")
605         """
606         self._impl_values.set_information(key, value)
607
608     def impl_get_information(self, key, default=undefined):
609         """retrieves one information's item
610
611         :param key: the item string (ex: "help")
612         """
613         return self._impl_values.get_information(key, default)
614
615     def impl_del_information(self, key, raises=True):
616         self._impl_values.del_information(key, raises)
617
618     # ----- state
619     def __getstate__(self):
620         if self._impl_meta is not None:
621             raise ConfigError(_('cannot serialize Config with MetaConfig'))  # pragma: optional cover
622         slots = set()
623         for subclass in self.__class__.__mro__:
624             if subclass is not object:
625                 slots.update(subclass.__slots__)
626         slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
627         state = {}
628         for slot in slots:
629             try:
630                 state[slot] = getattr(self, slot)
631             except AttributeError:  # pragma: optional cover
632                 pass
633         storage = self._impl_values._p_._storage
634         if not storage.serializable:
635             raise ConfigError(_('this storage is not serialisable, could be a '
636                               'none persistent storage'))  # pragma: optional cover
637         state['_storage'] = {'session_id': storage.session_id,
638                              'persistent': storage.persistent}
639         state['_impl_setting'] = _impl_getstate_setting()
640         return state
641
642     def __setstate__(self, state):
643         for key, value in state.items():
644             if key not in ['_storage', '_impl_setting']:
645                 setattr(self, key, value)
646         set_storage('config', **state['_impl_setting'])
647         self._impl_context = weakref.ref(self)
648         self._impl_settings.context = weakref.ref(self)
649         self._impl_values.context = weakref.ref(self)
650         storage = get_storage('config', test=self._impl_test, **state['_storage'])
651         self._impl_values._impl_setstate(storage)
652         self._impl_settings._impl_setstate(storage)
653         self._impl_meta = None
654
655     def _gen_fake_values(self, session):
656         fake_config = Config(self._impl_descr, persistent=False,
657                              force_values=get_storages_validation(),
658                              force_settings=self.cfgimpl_get_settings())
659         fake_config.cfgimpl_get_values()._p_.importation(self.cfgimpl_get_values()._p_.exportation(session, fake=True))
660         return fake_config
661
662     def duplicate(self):
663         config = Config(self._impl_descr)
664         session = self.cfgimpl_get_values()._p_.getsession()
665         config.cfgimpl_get_values()._p_.importation(self.cfgimpl_get_values()._p_.exportation(session))
666         config.cfgimpl_get_settings()._p_._properties = self.cfgimpl_get_settings()._p_.get_modified_properties()
667         config.cfgimpl_get_settings()._p_._permissives = self.cfgimpl_get_settings()._p_.get_modified_permissives()
668         return config
669
670
671 # ____________________________________________________________
672 class Config(_CommonConfig):
673     "main configuration management entry"
674     __slots__ = ('__weakref__', '_impl_test', '_impl_name')
675
676     def __init__(self, descr, session_id=None, persistent=False,
677                  name=undefined, force_values=None, force_settings=None):
678         """ Configuration option management master class
679
680         :param descr: describes the configuration schema
681         :type descr: an instance of ``option.OptionDescription``
682         :param context: the current root config
683         :type context: `Config`
684         :param session_id: session ID is import with persistent Config to
685         retrieve good session
686         :type session_id: `str`
687         :param persistent: if persistent, don't delete storage when leaving
688         :type persistent: `boolean`
689         """
690         if force_settings is not None and force_values is not None:
691             self._impl_settings = force_settings
692             self._impl_values = Values(self, force_values)
693         else:
694             settings, values = get_storages(self, session_id, persistent)
695             if name is undefined:
696                 name = 'config'
697                 if session_id is not None:
698                     name += session_id
699             if name is not None and not valid_name(name):  # pragma: optional cover
700                 raise ValueError(_("invalid name: {0} for config").format(name))
701             self._impl_settings = Settings(self, settings)
702             self._impl_values = Values(self, values)
703         super(Config, self).__init__(descr, weakref.ref(self))
704         self._impl_meta = None
705         #undocumented option used only in test script
706         self._impl_test = False
707         if force_settings is None or force_values is None:
708             self._impl_build_all_caches()
709         self._impl_name = name
710
711     def cfgimpl_reset_cache(self,
712                             only_expired=False,
713                             only=('values', 'settings')):
714         if 'values' in only:
715             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
716         if 'settings' in only:
717             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
718
719     def impl_getname(self):
720         return self._impl_name
721
722     def impl_getsessionid(self):
723         return self._impl_values._p_._storage.session_id
724
725
726 class GroupConfig(_CommonConfig):
727     __slots__ = ('__weakref__', '_impl_children', '_impl_name')
728
729     def __init__(self, children, session_id=None, persistent=False,
730                  _descr=None, name=undefined):
731         if not isinstance(children, list):
732             raise ValueError(_("groupconfig's children must be a list"))
733         names = []
734         for child in children:
735             if not isinstance(child, _CommonConfig):
736                 raise ValueError(_("groupconfig's children must be Config, MetaConfig or GroupConfig"))
737             name_ = child._impl_name
738             if name_ is None:
739                 raise ValueError(_('name must be set to config before creating groupconfig'))
740             names.append(name_)
741         if len(names) != len(set(names)):
742             for idx in xrange(1, len(names) + 1):
743                 name = names.pop(0)
744                 if name in names:
745                     raise ConflictError(_('config name must be uniq in '
746                                           'groupconfig for {0}').format(name))
747         self._impl_children = children
748         settings, values = get_storages(self, session_id, persistent)
749         self._impl_settings = Settings(self, settings)
750         self._impl_values = Values(self, values)
751         super(GroupConfig, self).__init__(_descr, weakref.ref(self))
752         self._impl_meta = None
753         #undocumented option used only in test script
754         self._impl_test = False
755         if name is undefined:
756             name = session_id
757         self._impl_name = name
758
759     def cfgimpl_get_children(self):
760         return self._impl_children
761
762     #def cfgimpl_get_context(self):
763     #    "a meta config is a config which has a setting, that is itself"
764     #    return self
765
766     def cfgimpl_reset_cache(self,
767                             only_expired=False,
768                             only=('values', 'settings')):
769         if 'values' in only:
770             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
771         if 'settings' in only:
772             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
773         for child in self._impl_children:
774             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
775
776     def set_value(self, path, value):
777         """Setattr not in current GroupConfig, but in each children
778         """
779         for child in self._impl_children:
780             if isinstance(child, MetaConfig):
781                 child.set_value(path, value, only_config=True)
782             elif isinstance(child, GroupConfig):
783                 child.set_value(path, value)
784             else:
785                 child.setattr(path, value, not_raises=True)
786
787     def find_firsts(self, byname=None, bypath=undefined, byoption=undefined,
788                     byvalue=undefined, raise_if_not_found=True, _sub=False,
789                     check_properties=True):
790         """Find first not in current GroupConfig, but in each children
791         """
792         ret = []
793
794         #if MetaConfig, all children have same OptionDescription in context
795         #so search only one time the option for all children
796         if bypath is undefined and byname is not None and \
797                 isinstance(self, MetaConfig):
798             bypath = self._find(bytype=None, byvalue=undefined, byname=byname,
799                                 first=True, type_='path',
800                                 check_properties=None,
801                                 raise_if_not_found=raise_if_not_found)
802             byname = None
803             byoption = self.cfgimpl_get_description(
804             ).impl_get_opt_by_path(bypath)
805
806         for child in self._impl_children:
807             if isinstance(child, GroupConfig):
808                 ret.extend(child.find_firsts(byname=byname, bypath=bypath,
809                                              byoption=byoption,
810                                              byvalue=byvalue,
811                                              check_properties=check_properties,
812                                              raise_if_not_found=False,
813                                              _sub=True))
814             elif child._find(None, byname, byvalue, first=True,
815                              type_='path', raise_if_not_found=False,
816                              check_properties=check_properties,
817                              only_path=bypath, only_option=byoption):
818                 ret.append(child)
819         if _sub:
820             return ret
821         else:
822             return GroupConfig(self._find_return_results(ret, raise_if_not_found))
823
824     def __repr__(self):
825         return object.__repr__(self)
826
827     def __str__(self):
828         ret = ''
829         for child in self._impl_children:
830             ret += '({0})\n'.format(child._impl_name)
831         ret += super(GroupConfig, self).__str__()
832         return ret
833
834     def getattr(self, name, force_permissive=False, validate=True,
835                 _setting_properties=undefined,
836                 returns_raise=False):
837         for child in self._impl_children:
838             if name == child._impl_name:
839                 return child
840         return super(GroupConfig, self).getattr(name, force_permissive,
841                                                 validate,
842                                                 _setting_properties=_setting_properties,
843                                                 returns_raise=returns_raise)
844
845
846 class MetaConfig(GroupConfig):
847     __slots__ = tuple()
848
849     def __init__(self, children, session_id=None, persistent=False,
850                  name=undefined):
851         descr = None
852         for child in children:
853             if not isinstance(child, _CommonConfig):
854                 raise TypeError(_("metaconfig's children "
855                                   "should be config, not {0}"
856                                   ).format(type(child)))
857             if child.cfgimpl_get_meta() is not None:
858                 raise ValueError(_("child has already a metaconfig's"))
859             if descr is None:
860                 descr = child.cfgimpl_get_description()
861             elif not descr is child.cfgimpl_get_description():
862                 raise ValueError(_('all config in metaconfig must '
863                                    'have the same optiondescription'))
864             child._impl_meta = weakref.ref(self)
865
866         super(MetaConfig, self).__init__(children, session_id, persistent,
867                                          descr, name)
868
869     def set_value(self, path, value, force_default=False,
870                   force_dont_change_value=False, force_default_if_same=False,
871                   only_config=False):
872         """only_config: could be set if you want modify value in all Config included in
873                         this MetaConfig
874         """
875         if only_config:
876             if force_default or force_default_if_same or force_dont_change_value:
877                 raise ValueError(_('force_default, force_default_if_same or '
878                                    'force_dont_change_value cannot be set with'
879                                    ' only_config'))
880             return super(MetaConfig, self).set_value(path, value)
881         if force_default or force_default_if_same or force_dont_change_value:
882             if force_default and force_dont_change_value:
883                 raise ValueError(_('force_default and force_dont_change_value'
884                                    ' cannot be set together'))
885             opt = self.cfgimpl_get_description().impl_get_opt_by_path(path)
886             for child in self._impl_children:
887                 if force_default_if_same or force_default:
888                     if force_default_if_same:
889                         if not child.cfgimpl_get_values()._contains(path):
890                             child_value = undefined
891                         else:
892                             child_value = child.getattr(path)
893                     if force_default or value == child_value:
894                         child.cfgimpl_get_values().reset(opt, path=path,
895                                                          validate=False)
896                         continue
897                 if force_dont_change_value:
898                     child_value = child.getattr(path)
899                     if value != child_value:
900                         setattr(child, path, child_value)
901
902         setattr(self, path, value)