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