docstrings and api
[tiramisu.git] / tiramisu / config.py
1 # -*- coding: utf-8 -*-
2 "pretty small and local configuration management tool"
3 # Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 #
19 # The original `Config` design model is unproudly borrowed from
20 # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
21 # the whole pypy projet is under MIT licence
22 # ____________________________________________________________
23 from tiramisu.error import PropertiesOptionError, ConfigError
24 from tiramisu.option import OptionDescription, Option, SymLinkOption, \
25     BaseInformation
26 from tiramisu.setting import groups, Setting
27 from tiramisu.value import Values
28 from tiramisu.i18n import _
29
30
31 class SubConfig(BaseInformation):
32     "sub configuration management entry"
33     __slots__ = ('_impl_context', '_impl_descr')
34
35     def __init__(self, descr, context):
36         """ Configuration option management master class
37
38         :param descr: describes the configuration schema
39         :type descr: an instance of ``option.OptionDescription``
40         :param context: the current root config
41         :type context: `Config`
42         """
43         # main option description
44         if not isinstance(descr, OptionDescription):
45             raise ValueError(_('descr must be an optiondescription, not {0}'
46                                ).format(type(descr)))
47         self._impl_descr = descr
48         # sub option descriptions
49         if not isinstance(context, SubConfig):
50             raise ValueError('context must be a SubConfig')
51         self._impl_context = context
52
53     def cfgimpl_reset_cache(self, only_expired=False, only=('values',
54                                                             'settings')):
55         self.cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
56
57     def cfgimpl_get_home_by_path(self, path, force_permissive=False,
58                                  force_properties=None):
59         """:returns: tuple (config, name)"""
60         path = path.split('.')
61         for step in path[:-1]:
62             self = self._getattr(step,
63                                  force_permissive=force_permissive,
64                                  force_properties=force_properties)
65         return self, path[-1]
66
67     def __hash__(self):
68         return hash(self.cfgimpl_get_description().impl_getkey(self))
69
70     def __eq__(self, other):
71         "Config's comparison"
72         if not isinstance(other, Config):
73             return False
74         return self.cfgimpl_get_description().impl_getkey(self) == \
75             other.cfgimpl_get_description().impl_getkey(other)
76
77     def __ne__(self, other):
78         "Config's comparison"
79         if not isinstance(other, Config):
80             return False
81         return not self == other
82
83     # ______________________________________________________________________
84     def __iter__(self):
85         """Pythonesque way of parsing group's ordered options.
86         iteration only on Options (not OptionDescriptions)"""
87         for child in self.cfgimpl_get_description().impl_getchildren():
88             if not isinstance(child, OptionDescription):
89                 try:
90                     yield child._name, getattr(self, child._name)
91                 except GeneratorExit:
92                     raise StopIteration
93                 except PropertiesOptionError:
94                     pass  # option with properties
95
96     def iter_all(self):
97         """A way of parsing options **and** groups.
98         iteration on Options and OptionDescriptions."""
99         for child in self.cfgimpl_get_description().impl_getchildren():
100             try:
101                 yield child._name, getattr(self, child._name)
102             except GeneratorExit:
103                 raise StopIteration
104             except PropertiesOptionError:
105                 pass  # option with properties
106
107     def iter_groups(self, group_type=None):
108         """iteration on groups objects only.
109         All groups are returned if `group_type` is `None`, otherwise the groups
110         can be filtered by categories (families, or whatever).
111
112         :param group_type: if defined, is an instance of `groups.GroupType`
113                            or `groups.MasterGroupType` that lives in
114                            `setting.groups`
115         """
116         if group_type is not None:
117             if not isinstance(group_type, groups.GroupType):
118                 raise TypeError(_("unknown group_type: {0}").format(group_type))
119         for child in self.cfgimpl_get_description().impl_getchildren():
120             if isinstance(child, OptionDescription):
121                 try:
122                     if group_type is None or (group_type is not None and
123                                               child.impl_get_group_type()
124                                               == group_type):
125                         yield child._name, getattr(self, child._name)
126                 except GeneratorExit:
127                     raise StopIteration
128                 except PropertiesOptionError:
129                     pass
130     # ______________________________________________________________________
131
132     def __str__(self):
133         "Config's string representation"
134         lines = []
135         for name, grp in self.iter_groups():
136             lines.append("[%s]" % name)
137         for name, value in self:
138             try:
139                 lines.append("%s = %s" % (name, value))
140             except PropertiesOptionError:
141                 pass
142         return '\n'.join(lines)
143
144     __repr__ = __str__
145
146     def cfgimpl_get_context(self):
147         return self._impl_context
148
149     def cfgimpl_get_description(self):
150         if self._impl_descr is None:
151             raise ConfigError(_('no optiondescription for this config (may be MetaConfig without meta)'))
152         else:
153             return self._impl_descr
154
155     def cfgimpl_get_settings(self):
156         return self.cfgimpl_get_context()._impl_settings
157
158     def cfgimpl_get_values(self):
159         return self.cfgimpl_get_context()._impl_values
160
161     # ____________________________________________________________
162     # attribute methods
163     def __setattr__(self, name, value):
164         "attribute notation mechanism for the setting of the value of an option"
165         if name.startswith('_impl_'):
166             #self.__dict__[name] = value
167             object.__setattr__(self, name, value)
168             return
169         self._setattr(name, value)
170
171     def _setattr(self, name, value, force_permissive=False):
172         if '.' in name:
173             homeconfig, name = self.cfgimpl_get_home_by_path(name)
174             return homeconfig.__setattr__(name, value)
175         child = getattr(self.cfgimpl_get_description(), name)
176         if not isinstance(child, SymLinkOption):
177             self.cfgimpl_get_values().setitem(child, value,
178                                               force_permissive=force_permissive)
179         else:
180             context = self.cfgimpl_get_context()
181             path = context.cfgimpl_get_description().impl_get_path_by_opt(child._opt)
182             context._setattr(path, value, force_permissive=force_permissive)
183
184     def __delattr__(self, name):
185         child = getattr(self.cfgimpl_get_description(), name)
186         del(self.cfgimpl_get_values()[child])
187
188     def __getattr__(self, name):
189         return self._getattr(name)
190
191     def _getattr(self, name, force_permissive=False, force_properties=None,
192                  validate=True):
193         """
194         attribute notation mechanism for accessing the value of an option
195         :param name: attribute name
196         :return: option's value if name is an option name, OptionDescription
197                  otherwise
198         """
199         # attribute access by passing a path,
200         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
201         if '.' in name:
202             homeconfig, name = self.cfgimpl_get_home_by_path(name,
203                                                              force_permissive=force_permissive,
204                                                              force_properties=force_properties)
205             return homeconfig._getattr(name, force_permissive=force_permissive,
206                                        force_properties=force_properties,
207                                        validate=validate)
208         # special attributes
209         if name.startswith('_impl_') or name.startswith('cfgimpl_') \
210                 or name.startswith('impl_'):
211             # if it were in __dict__ it would have been found already
212             return object.__getattribute__(self, name)
213         opt_or_descr = getattr(self.cfgimpl_get_description(), name)
214         # symlink options
215         if isinstance(opt_or_descr, SymLinkOption):
216             context = self.cfgimpl_get_context()
217             path = context.cfgimpl_get_description().impl_get_path_by_opt(opt_or_descr._opt)
218             return context._getattr(path, validate=validate,
219                                     force_properties=force_properties,
220                                     force_permissive=force_permissive)
221         elif isinstance(opt_or_descr, OptionDescription):
222             self.cfgimpl_get_settings().validate_properties(opt_or_descr,
223                                                             True, False,
224                                                             force_permissive=force_permissive,
225                                                             force_properties=force_properties)
226             return SubConfig(opt_or_descr, self.cfgimpl_get_context())
227         else:
228             return self.cfgimpl_get_values().getitem(opt_or_descr,
229                                                      validate=validate,
230                                                      force_properties=force_properties,
231                                                      force_permissive=force_permissive)
232
233     def find(self, bytype=None, byname=None, byvalue=None, type_='option'):
234         """
235             finds a list of options recursively in the config
236
237             :param bytype: Option class (BoolOption, StrOption, ...)
238             :param byname: filter by Option._name
239             :param byvalue: filter by the option's value
240             :returns: list of matching Option objects
241         """
242         return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
243                                                 first=False,
244                                                 type_=type_,
245                                                 _subpath=self.cfgimpl_get_path())
246
247     def find_first(self, bytype=None, byname=None, byvalue=None,
248                    type_='option'):
249         """
250             finds an option recursively in the config
251
252             :param bytype: Option class (BoolOption, StrOption, ...)
253             :param byname: filter by Option._name
254             :param byvalue: filter by the option's value
255             :returns: list of matching Option objects
256         """
257         return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
258                                                 first=True,
259                                                 type_=type_,
260                                                 _subpath=self.cfgimpl_get_path())
261
262     def _find(self, bytype, byname, byvalue, first, type_='option',
263               _subpath=None, check_properties=True):
264         """
265         convenience method for finding an option that lives only in the subtree
266
267         :param first: return only one option if True, a list otherwise
268         :return: find list or an exception if nothing has been found
269         """
270         def _filter_by_name():
271             try:
272                 if byname is None or path == byname or path.endswith('.' + byname):
273                     return True
274             except IndexError:
275                 pass
276             return False
277
278         def _filter_by_value():
279             if byvalue is None:
280                 return True
281             try:
282                 value = getattr(self, path)
283                 if value == byvalue:
284                     return True
285             except PropertiesOptionError:  # a property restricts the access of the value
286                 pass
287             return False
288
289         def _filter_by_type():
290             if bytype is None:
291                 return True
292             if isinstance(option, bytype):
293                 return True
294             return False
295
296         #def _filter_by_attrs():
297         #    if byattrs is None:
298         #        return True
299         #    for key, val in byattrs.items():
300         #        print "----", path, key
301         #        if path == key or path.endswith('.' + key):
302         #            if value == val:
303         #                return True
304         #            else:
305         #                return False
306         #    return False
307         if type_ not in ('option', 'path', 'context', 'value'):
308             raise ValueError(_('unknown type_ type {0} for _find').format(type_))
309         find_results = []
310         opts, paths = self.cfgimpl_get_description()._cache_paths
311         for index in range(0, len(paths)):
312             option = opts[index]
313             if isinstance(option, OptionDescription):
314                 continue
315             path = paths[index]
316             if _subpath is not None and not path.startswith(_subpath + '.'):
317                 continue
318             if not _filter_by_name():
319                 continue
320             if not _filter_by_value():
321                 continue
322             #remove option with propertyerror, ...
323             if check_properties:
324                 try:
325                     value = getattr(self, path)
326                 except PropertiesOptionError:
327                     # a property restricts the access of the value
328                     continue
329             if not _filter_by_type():
330                 continue
331             #if not _filter_by_attrs():
332             #    continue
333             if type_ == 'value':
334                 retval = value
335             elif type_ == 'path':
336                 retval = path
337             elif type_ == 'option':
338                 retval = option
339             elif type_ == 'context':
340                 retval = self.cfgimpl_get_context()
341             if first:
342                 return retval
343             else:
344                 find_results.append(retval)
345         if find_results == []:
346             #FIXME too slow
347             #raise AttributeError(_("no option found in config with these criteria"))
348             raise AttributeError("no option found in config with these criteria")
349         else:
350             return find_results
351
352     def make_dict(self, flatten=False, _currpath=None, withoption=None,
353                   withvalue=None):
354         """exports the whole config into a `dict`, for example: 
355         
356         >>> print cfg.make_dict()
357         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
358         
359         
360         
361         :param flatten: returns a dict(name=value) instead of a dict(path=value)
362                         ::
363
364                             >>> print cfg.make_dict(flatten=True)
365                             {'var5': None, 'var4': None, 'var6': None}
366        
367         :param withoption: returns the options that are present in the very same
368                            `OptionDescription` than the `withoption` itself::
369
370                                 >>> print cfg.make_dict(withoption='var1')
371                                 {'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 
372                                 'od2.var1': u'value', 'od1.var1': None, 
373                                 'od1.var3': None, 'od1.var2': None}
374
375         :param withvalue: returns the options that have the value `withvalue`
376                           ::
377
378                             >>> print c.make_dict(withoption='var1', withvalue=u'value')
379                             {'od2.var4': None, 'od2.var5': None, 'od2.var6': None, 
380                             'od2.var1': u'value'}
381
382         :returns: dict of Option's name (or path) and values
383         """
384         pathsvalues = []
385         if _currpath is None:
386             _currpath = []
387         if withoption is None and withvalue is not None:
388             raise ValueError(_("make_dict can't filtering with value without "
389                                "option"))
390         if withoption is not None:
391             mypath = self.cfgimpl_get_path()
392             for path in self.cfgimpl_get_context()._find(bytype=Option,
393                                                          byname=withoption,
394                                                          byvalue=withvalue,
395                                                          first=False,
396                                                          type_='path',
397                                                          _subpath=mypath):
398                 path = '.'.join(path.split('.')[:-1])
399                 opt = self.cfgimpl_get_context().cfgimpl_get_description().impl_get_opt_by_path(path)
400                 if mypath is not None:
401                     if mypath == path:
402                         withoption = None
403                         withvalue = None
404                         break
405                     else:
406                         tmypath = mypath + '.'
407                         if not path.startswith(tmypath):
408                             raise AttributeError(_('unexpected path {0}, '
409                                                    'should start with {1}'
410                                                    '').format(path, mypath))
411                         path = path[len(tmypath):]
412                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
413         #withoption can be set to None below !
414         if withoption is None:
415             for opt in self.cfgimpl_get_description().impl_getchildren():
416                 path = opt._name
417                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
418         if _currpath == []:
419             options = dict(pathsvalues)
420             return options
421         return pathsvalues
422
423     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten):
424         if isinstance(opt, OptionDescription):
425             try:
426                 pathsvalues += getattr(self, path).make_dict(flatten,
427                                                              _currpath + path.split('.'))
428             except PropertiesOptionError:
429                 pass  # this just a hidden or disabled option
430         else:
431             try:
432                 value = self._getattr(opt._name)
433                 if flatten:
434                     name = opt._name
435                 else:
436                     name = '.'.join(_currpath + [opt._name])
437                 pathsvalues.append((name, value))
438             except PropertiesOptionError:
439                 pass  # this just a hidden or disabled option
440
441     def cfgimpl_get_path(self):
442         descr = self.cfgimpl_get_description()
443         context_descr = self.cfgimpl_get_context().cfgimpl_get_description()
444         return context_descr.impl_get_path_by_opt(descr)
445
446
447 class CommonConfig(SubConfig):
448     "abstract base class for the Config and the MetaConfig"
449     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta')
450
451     def _impl_build_all_paths(self):
452         self.cfgimpl_get_description().impl_build_cache()
453
454     def read_only(self):
455         "read only is a global config's setting, see `settings.py`"
456         self.cfgimpl_get_settings().read_only()
457
458     def read_write(self):
459         "read write is a global config's setting, see `settings.py`"
460         self.cfgimpl_get_settings().read_write()
461
462     def getowner(self, path):
463         """convenience method to retrieve an option's owner
464         from the config itself
465         """
466         opt = self.cfgimpl_get_description().impl_get_opt_by_path(path)
467         return self.cfgimpl_get_values().getowner(opt)
468
469     def unwrap_from_path(self, path):
470         """convenience method to extract and Option() object from the Config()
471         and it is **fast**: finds the option directly in the appropriate
472         namespace
473
474         :returns: Option()
475         """
476         if '.' in path:
477             homeconfig, path = self.cfgimpl_get_home_by_path(path)
478             return getattr(homeconfig.cfgimpl_get_description(), path)
479         return getattr(self.cfgimpl_get_description(), path)
480
481     def cfgimpl_get_path(self):
482         return None
483
484     def cfgimpl_get_meta(self):
485         return self._impl_meta
486
487
488 # ____________________________________________________________
489 class Config(CommonConfig):
490     "main configuration management entry"
491     __slots__ = tuple()
492
493     def __init__(self, descr):
494         """ Configuration option management master class
495
496         :param descr: describes the configuration schema
497         :type descr: an instance of ``option.OptionDescription``
498         :param context: the current root config
499         :type context: `Config`
500         """
501         self._impl_settings = Setting(self)
502         self._impl_values = Values(self)
503         super(Config, self).__init__(descr, self)
504         self._impl_build_all_paths()
505         self._impl_meta = None
506         self._impl_informations = {}
507
508     def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
509         if 'values' in only:
510             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
511         if 'settings' in only:
512             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
513
514
515 class MetaConfig(CommonConfig):
516     __slots__ = ('_impl_children',)
517
518     def __init__(self, children, meta=True):
519         if not isinstance(children, list):
520             raise ValueError(_("metaconfig's children must be a list"))
521         self._impl_descr = None
522         if meta:
523             for child in children:
524                 if not isinstance(child, CommonConfig):
525                     raise ValueError(_("metaconfig's children must be Config, not {0}"
526                                        "".format(type(child))))
527                 if self._impl_descr is None:
528                     self._impl_descr = child.cfgimpl_get_description()
529                 elif not self._impl_descr is child.cfgimpl_get_description():
530                     raise ValueError(_('all config in MetaConfig must have same '
531                                        'optiondescription'))
532                 if child.cfgimpl_get_meta() is not None:
533                     raise ValueError(_("child has already a metaconfig's"))
534                 child._impl_meta = self
535
536         self._impl_children = children
537         self._impl_settings = Setting(self)
538         self._impl_values = Values(self)
539         self._impl_meta = None
540         self._impl_informations = {}
541
542     def cfgimpl_get_children(self):
543         return self._impl_children
544
545     def cfgimpl_get_context(self):
546         "a meta config is a config wich has a setting, that is itself"
547         return self
548
549     def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
550         if 'values' in only:
551             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
552         if 'settings' in only:
553             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
554         for child in self._impl_children:
555             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
556
557     def set_contexts(self, path, value):
558         for child in self._impl_children:
559             try:
560                 if not isinstance(child, MetaConfig):
561                     setattr(child, path, value)
562                 else:
563                     child.set_contexts(path, value)
564             except PropertiesOptionError:
565                 pass
566
567     def find_first_contexts(self, byname=None, bypath=None, byvalue=None, type_='context'):
568         ret = []
569         try:
570             if bypath is None and byname is not None and \
571                     self.cfgimpl_get_description() is not None:
572                 bypath = self._find(bytype=None, byvalue=None, byname=byname,
573                                     first=True, type_='path',
574                                     check_properties=False)
575         except ConfigError:
576             pass
577         for child in self._impl_children:
578             try:
579                 if not isinstance(child, MetaConfig):
580                     if bypath is not None:
581                         if byvalue is not None:
582                             if getattr(child, bypath) == byvalue:
583                                 ret.append(child)
584                         else:
585                             #not raise
586                             getattr(child, bypath)
587                             ret.append(child)
588                     else:
589                         ret.append(child.find_first(byname=byname,
590                                                     byvalue=byvalue,
591                                                     type_=type_))
592                 else:
593                     ret.extend(child.find_first_contexts(byname=byname,
594                                                          bypath=bypath,
595                                                          byvalue=byvalue,
596                                                          type_=type_))
597             except AttributeError:
598                 pass
599         return ret
600
601
602 def mandatory_warnings(config):
603     """convenience function to trace Options that are mandatory and
604     where no value has been set
605
606     :returns: generator of mandatory Option's path
607
608     """
609     #if value in cache, properties are not calculated
610     config.cfgimpl_reset_cache(only=('values',))
611     for path in config.cfgimpl_get_description().impl_getpaths(include_groups=True):
612         try:
613             config._getattr(path, force_properties=frozenset(('mandatory',)))
614         except PropertiesOptionError, err:
615             if err.proptype == ['mandatory']:
616                 yield path
617     config.cfgimpl_reset_cache(only=('values',))