__str__ method could return unicode object, force to decode in str
[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, default_encoding
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("[{0}]".format(name))
137         for name, value in self:
138             value = value.encode(default_encoding)
139             try:
140                 lines.append("{0} = {1}".format(name, value))
141             except PropertiesOptionError:
142                 pass
143         return '\n'.join(lines)
144
145     __repr__ = __str__
146
147     def cfgimpl_get_context(self):
148         return self._impl_context
149
150     def cfgimpl_get_description(self):
151         if self._impl_descr is None:
152             raise ConfigError(_('no optiondescription for this config (may be MetaConfig without meta)'))
153         else:
154             return self._impl_descr
155
156     def cfgimpl_get_settings(self):
157         return self.cfgimpl_get_context()._impl_settings
158
159     def cfgimpl_get_values(self):
160         return self.cfgimpl_get_context()._impl_values
161
162     # ____________________________________________________________
163     # attribute methods
164     def __setattr__(self, name, value):
165         "attribute notation mechanism for the setting of the value of an option"
166         if name.startswith('_impl_'):
167             #self.__dict__[name] = value
168             object.__setattr__(self, name, value)
169             return
170         self._setattr(name, value)
171
172     def _setattr(self, name, value, force_permissive=False):
173         if '.' in name:
174             homeconfig, name = self.cfgimpl_get_home_by_path(name)
175             return homeconfig.__setattr__(name, value)
176         child = getattr(self.cfgimpl_get_description(), name)
177         if not isinstance(child, SymLinkOption):
178             self.cfgimpl_get_values().setitem(child, value,
179                                               force_permissive=force_permissive)
180         else:
181             context = self.cfgimpl_get_context()
182             path = context.cfgimpl_get_description().impl_get_path_by_opt(child._opt)
183             context._setattr(path, value, force_permissive=force_permissive)
184
185     def __delattr__(self, name):
186         child = getattr(self.cfgimpl_get_description(), name)
187         del(self.cfgimpl_get_values()[child])
188
189     def __getattr__(self, name):
190         return self._getattr(name)
191
192     def _getattr(self, name, force_permissive=False, force_properties=None,
193                  validate=True):
194         """
195         attribute notation mechanism for accessing the value of an option
196         :param name: attribute name
197         :return: option's value if name is an option name, OptionDescription
198                  otherwise
199         """
200         # attribute access by passing a path,
201         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
202         if '.' in name:
203             homeconfig, name = self.cfgimpl_get_home_by_path(name,
204                                                              force_permissive=force_permissive,
205                                                              force_properties=force_properties)
206             return homeconfig._getattr(name, force_permissive=force_permissive,
207                                        force_properties=force_properties,
208                                        validate=validate)
209         # special attributes
210         if name.startswith('_impl_') or name.startswith('cfgimpl_') \
211                 or name.startswith('impl_'):
212             # if it were in __dict__ it would have been found already
213             return object.__getattribute__(self, name)
214         opt_or_descr = getattr(self.cfgimpl_get_description(), name)
215         # symlink options
216         if isinstance(opt_or_descr, SymLinkOption):
217             context = self.cfgimpl_get_context()
218             path = context.cfgimpl_get_description().impl_get_path_by_opt(opt_or_descr._opt)
219             return context._getattr(path, validate=validate,
220                                     force_properties=force_properties,
221                                     force_permissive=force_permissive)
222         elif isinstance(opt_or_descr, OptionDescription):
223             self.cfgimpl_get_settings().validate_properties(opt_or_descr,
224                                                             True, False,
225                                                             force_permissive=force_permissive,
226                                                             force_properties=force_properties)
227             return SubConfig(opt_or_descr, self.cfgimpl_get_context())
228         else:
229             return self.cfgimpl_get_values().getitem(opt_or_descr,
230                                                      validate=validate,
231                                                      force_properties=force_properties,
232                                                      force_permissive=force_permissive)
233
234     def find(self, bytype=None, byname=None, byvalue=None, type_='option'):
235         """
236             finds a list of options recursively in the config
237
238             :param bytype: Option class (BoolOption, StrOption, ...)
239             :param byname: filter by Option._name
240             :param byvalue: filter by the option's value
241             :returns: list of matching Option objects
242         """
243         return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
244                                                 first=False,
245                                                 type_=type_,
246                                                 _subpath=self.cfgimpl_get_path())
247
248     def find_first(self, bytype=None, byname=None, byvalue=None,
249                    type_='option'):
250         """
251             finds an option recursively in the config
252
253             :param bytype: Option class (BoolOption, StrOption, ...)
254             :param byname: filter by Option._name
255             :param byvalue: filter by the option's value
256             :returns: list of matching Option objects
257         """
258         return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
259                                                 first=True,
260                                                 type_=type_,
261                                                 _subpath=self.cfgimpl_get_path())
262
263     def _find(self, bytype, byname, byvalue, first, type_='option',
264               _subpath=None, check_properties=True):
265         """
266         convenience method for finding an option that lives only in the subtree
267
268         :param first: return only one option if True, a list otherwise
269         :return: find list or an exception if nothing has been found
270         """
271         def _filter_by_name():
272             try:
273                 if byname is None or path == byname or path.endswith('.' + byname):
274                     return True
275             except IndexError:
276                 pass
277             return False
278
279         def _filter_by_value():
280             if byvalue is None:
281                 return True
282             try:
283                 value = getattr(self, path)
284                 if value == byvalue:
285                     return True
286             except PropertiesOptionError:  # a property restricts the access of the value
287                 pass
288             return False
289
290         def _filter_by_type():
291             if bytype is None:
292                 return True
293             if isinstance(option, bytype):
294                 return True
295             return False
296
297         #def _filter_by_attrs():
298         #    if byattrs is None:
299         #        return True
300         #    for key, val in byattrs.items():
301         #        print "----", path, key
302         #        if path == key or path.endswith('.' + key):
303         #            if value == val:
304         #                return True
305         #            else:
306         #                return False
307         #    return False
308         if type_ not in ('option', 'path', 'context', 'value'):
309             raise ValueError(_('unknown type_ type {0} for _find').format(type_))
310         find_results = []
311         opts, paths = self.cfgimpl_get_description()._cache_paths
312         for index in range(0, len(paths)):
313             option = opts[index]
314             if isinstance(option, OptionDescription):
315                 continue
316             path = paths[index]
317             if _subpath is not None and not path.startswith(_subpath + '.'):
318                 continue
319             if not _filter_by_name():
320                 continue
321             if not _filter_by_value():
322                 continue
323             #remove option with propertyerror, ...
324             if check_properties:
325                 try:
326                     value = getattr(self, path)
327                 except PropertiesOptionError:
328                     # a property restricts the access of the value
329                     continue
330             if not _filter_by_type():
331                 continue
332             #if not _filter_by_attrs():
333             #    continue
334             if type_ == 'value':
335                 retval = value
336             elif type_ == 'path':
337                 retval = path
338             elif type_ == 'option':
339                 retval = option
340             elif type_ == 'context':
341                 retval = self.cfgimpl_get_context()
342             if first:
343                 return retval
344             else:
345                 find_results.append(retval)
346         if find_results == []:
347             #FIXME too slow
348             #raise AttributeError(_("no option found in config with these criteria"))
349             raise AttributeError("no option found in config with these criteria")
350         else:
351             return find_results
352
353     def make_dict(self, flatten=False, _currpath=None, withoption=None,
354                   withvalue=None):
355         """exports the whole config into a `dict`, for example:
356
357         >>> print cfg.make_dict()
358         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
359
360
361
362         :param flatten: returns a dict(name=value) instead of a dict(path=value)
363                         ::
364
365                             >>> print cfg.make_dict(flatten=True)
366                             {'var5': None, 'var4': None, 'var6': None}
367
368         :param withoption: returns the options that are present in the very same
369                            `OptionDescription` than the `withoption` itself::
370
371                                 >>> print cfg.make_dict(withoption='var1')
372                                 {'od2.var4': None, 'od2.var5': None, 'od2.var6': None,
373                                 'od2.var1': u'value', 'od1.var1': None,
374                                 'od1.var3': None, 'od1.var2': None}
375
376         :param withvalue: returns the options that have the value `withvalue`
377                           ::
378
379                             >>> print c.make_dict(withoption='var1', withvalue=u'value')
380                             {'od2.var4': None, 'od2.var5': None, 'od2.var6': None,
381                             'od2.var1': u'value'}
382
383         :returns: dict of Option's name (or path) and values
384         """
385         pathsvalues = []
386         if _currpath is None:
387             _currpath = []
388         if withoption is None and withvalue is not None:
389             raise ValueError(_("make_dict can't filtering with value without "
390                                "option"))
391         if withoption is not None:
392             mypath = self.cfgimpl_get_path()
393             for path in self.cfgimpl_get_context()._find(bytype=Option,
394                                                          byname=withoption,
395                                                          byvalue=withvalue,
396                                                          first=False,
397                                                          type_='path',
398                                                          _subpath=mypath):
399                 path = '.'.join(path.split('.')[:-1])
400                 opt = self.cfgimpl_get_context().cfgimpl_get_description().impl_get_opt_by_path(path)
401                 if mypath is not None:
402                     if mypath == path:
403                         withoption = None
404                         withvalue = None
405                         break
406                     else:
407                         tmypath = mypath + '.'
408                         if not path.startswith(tmypath):
409                             raise AttributeError(_('unexpected path {0}, '
410                                                    'should start with {1}'
411                                                    '').format(path, mypath))
412                         path = path[len(tmypath):]
413                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
414         #withoption can be set to None below !
415         if withoption is None:
416             for opt in self.cfgimpl_get_description().impl_getchildren():
417                 path = opt._name
418                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
419         if _currpath == []:
420             options = dict(pathsvalues)
421             return options
422         return pathsvalues
423
424     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten):
425         if isinstance(opt, OptionDescription):
426             try:
427                 pathsvalues += getattr(self, path).make_dict(flatten,
428                                                              _currpath + path.split('.'))
429             except PropertiesOptionError:
430                 pass  # this just a hidden or disabled option
431         else:
432             try:
433                 value = self._getattr(opt._name)
434                 if flatten:
435                     name = opt._name
436                 else:
437                     name = '.'.join(_currpath + [opt._name])
438                 pathsvalues.append((name, value))
439             except PropertiesOptionError:
440                 pass  # this just a hidden or disabled option
441
442     def cfgimpl_get_path(self):
443         descr = self.cfgimpl_get_description()
444         context_descr = self.cfgimpl_get_context().cfgimpl_get_description()
445         return context_descr.impl_get_path_by_opt(descr)
446
447
448 class CommonConfig(SubConfig):
449     "abstract base class for the Config and the MetaConfig"
450     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta')
451
452     def _impl_build_all_paths(self):
453         self.cfgimpl_get_description().impl_build_cache()
454
455     def read_only(self):
456         "read only is a global config's setting, see `settings.py`"
457         self.cfgimpl_get_settings().read_only()
458
459     def read_write(self):
460         "read write is a global config's setting, see `settings.py`"
461         self.cfgimpl_get_settings().read_write()
462
463     def getowner(self, path):
464         """convenience method to retrieve an option's owner
465         from the config itself
466         """
467         opt = self.cfgimpl_get_description().impl_get_opt_by_path(path)
468         return self.cfgimpl_get_values().getowner(opt)
469
470     def unwrap_from_path(self, path, force_permissive=False):
471         """convenience method to extract and Option() object from the Config()
472         and it is **fast**: finds the option directly in the appropriate
473         namespace
474
475         :returns: Option()
476         """
477         if '.' in path:
478             homeconfig, path = self.cfgimpl_get_home_by_path(path,
479                                                              force_permissive=force_permissive)
480             return getattr(homeconfig.cfgimpl_get_description(), path)
481         return getattr(self.cfgimpl_get_description(), path)
482
483     def cfgimpl_get_path(self):
484         return None
485
486     def cfgimpl_get_meta(self):
487         return self._impl_meta
488
489
490 # ____________________________________________________________
491 class Config(CommonConfig):
492     "main configuration management entry"
493     __slots__ = tuple()
494
495     def __init__(self, descr):
496         """ Configuration option management master class
497
498         :param descr: describes the configuration schema
499         :type descr: an instance of ``option.OptionDescription``
500         :param context: the current root config
501         :type context: `Config`
502         """
503         self._impl_settings = Setting(self)
504         self._impl_values = Values(self)
505         super(Config, self).__init__(descr, self)
506         self._impl_build_all_paths()
507         self._impl_meta = None
508         self._impl_informations = {}
509
510     def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
511         if 'values' in only:
512             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
513         if 'settings' in only:
514             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
515
516
517 class MetaConfig(CommonConfig):
518     __slots__ = ('_impl_children',)
519
520     def __init__(self, children, meta=True):
521         if not isinstance(children, list):
522             raise ValueError(_("metaconfig's children must be a list"))
523         self._impl_descr = None
524         if meta:
525             for child in children:
526                 if not isinstance(child, CommonConfig):
527                     raise ValueError(_("metaconfig's children must be Config, not {0}"
528                                        "".format(type(child))))
529                 if self._impl_descr is None:
530                     self._impl_descr = child.cfgimpl_get_description()
531                 elif not self._impl_descr is child.cfgimpl_get_description():
532                     raise ValueError(_('all config in MetaConfig must have same '
533                                        'optiondescription'))
534                 if child.cfgimpl_get_meta() is not None:
535                     raise ValueError(_("child has already a metaconfig's"))
536                 child._impl_meta = self
537
538         self._impl_children = children
539         self._impl_settings = Setting(self)
540         self._impl_values = Values(self)
541         self._impl_meta = None
542         self._impl_informations = {}
543
544     def cfgimpl_get_children(self):
545         return self._impl_children
546
547     def cfgimpl_get_context(self):
548         "a meta config is a config wich has a setting, that is itself"
549         return self
550
551     def cfgimpl_reset_cache(self, only_expired=False, only=('values', 'settings')):
552         if 'values' in only:
553             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
554         if 'settings' in only:
555             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
556         for child in self._impl_children:
557             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
558
559     def set_contexts(self, path, value):
560         for child in self._impl_children:
561             try:
562                 if not isinstance(child, MetaConfig):
563                     setattr(child, path, value)
564                 else:
565                     child.set_contexts(path, value)
566             except PropertiesOptionError:
567                 pass
568
569     def find_first_contexts(self, byname=None, bypath=None, byvalue=None, type_='context'):
570         ret = []
571         try:
572             if bypath is None and byname is not None and \
573                     self.cfgimpl_get_description() is not None:
574                 bypath = self._find(bytype=None, byvalue=None, byname=byname,
575                                     first=True, type_='path',
576                                     check_properties=False)
577         except ConfigError:
578             pass
579         for child in self._impl_children:
580             try:
581                 if not isinstance(child, MetaConfig):
582                     if bypath is not None:
583                         if byvalue is not None:
584                             if getattr(child, bypath) == byvalue:
585                                 ret.append(child)
586                         else:
587                             #not raise
588                             getattr(child, bypath)
589                             ret.append(child)
590                     else:
591                         ret.append(child.find_first(byname=byname,
592                                                     byvalue=byvalue,
593                                                     type_=type_))
594                 else:
595                     ret.extend(child.find_first_contexts(byname=byname,
596                                                          bypath=bypath,
597                                                          byvalue=byvalue,
598                                                          type_=type_))
599             except AttributeError:
600                 pass
601         return ret
602
603
604 def mandatory_warnings(config):
605     """convenience function to trace Options that are mandatory and
606     where no value has been set
607
608     :returns: generator of mandatory Option's path
609
610     """
611     #if value in cache, properties are not calculated
612     config.cfgimpl_reset_cache(only=('values',))
613     for path in config.cfgimpl_get_description().impl_getpaths(include_groups=True):
614         try:
615             config._getattr(path, force_properties=frozenset(('mandatory',)))
616         except PropertiesOptionError, err:
617             if err.proptype == ['mandatory']:
618                 yield path
619     config.cfgimpl_reset_cache(only=('values',))