tiramisu/tiramisu/config.py

872 lines
39 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2013-02-21 17:07:00 +01:00
# Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
#
2013-09-22 22:33:09 +02:00
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
2013-09-22 22:33:09 +02:00
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
2013-09-22 22:33:09 +02:00
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
2012-10-05 16:00:07 +02:00
# The original `Config` design model is unproudly borrowed from
# the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence
# ____________________________________________________________
2013-09-23 22:55:54 +02:00
"options handler global entry point"
import weakref
2015-04-18 22:53:45 +02:00
from .error import PropertiesOptionError, ConfigError, ConflictError
from .option import OptionDescription, Option, SymLinkOption, \
2014-06-19 23:22:39 +02:00
DynSymLinkOption
from .option.baseoption import valid_name
from .setting import groups, Settings, default_encoding, undefined
from .storage import get_storages, get_storage, set_storage, \
2015-04-18 22:53:45 +02:00
_impl_getstate_setting, get_storages_validation
from .value import Values, Multi
from .i18n import _
2013-02-22 11:09:17 +01:00
class SubConfig(object):
2013-09-23 22:55:54 +02:00
"""Sub configuration management entry.
Tree if OptionDescription's responsability. SubConfig are generated
on-demand. A Config is also a SubConfig.
Root Config is call context below
"""
__slots__ = ('_impl_context', '_impl_descr', '_impl_path')
2013-04-03 12:20:26 +02:00
def __init__(self, descr, context, subpath=None):
2012-10-05 16:00:07 +02:00
""" Configuration option management master class
2013-02-19 11:24:17 +01:00
2012-10-05 16:00:07 +02:00
:param descr: describes the configuration schema
:type descr: an instance of ``option.OptionDescription``
2013-02-07 16:20:21 +01:00
:param context: the current root config
:type context: `Config`
:type subpath: `str` with the path name
2012-10-05 16:00:07 +02:00
"""
# main option description
2014-06-19 23:22:39 +02:00
error = False
try:
if descr is not None and not descr.impl_is_optiondescription(): # pragma: optional cover
error = True
except AttributeError:
error = True
if error:
raise TypeError(_('descr must be an optiondescription, not {0}'
).format(type(descr)))
self._impl_descr = descr
# sub option descriptions
2014-06-19 23:22:39 +02:00
if not isinstance(context, weakref.ReferenceType): # pragma: optional cover
raise ValueError('context must be a Weakref')
self._impl_context = context
self._impl_path = subpath
2013-05-02 11:34:57 +02:00
def cfgimpl_reset_cache(self, only_expired=False, only=('values',
'settings')):
2013-09-23 22:55:54 +02:00
"remove cache (in context)"
2014-06-19 23:22:39 +02:00
self._cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only) # pragma: optional cover
2013-02-07 16:20:21 +01:00
def cfgimpl_get_home_by_path(self, path, force_permissive=False):
2012-10-05 16:00:07 +02:00
""":returns: tuple (config, name)"""
path = path.split('.')
for step in path[:-1]:
self = self.getattr(step,
force_permissive=force_permissive)
return self, path[-1]
#def __hash__(self):
#FIXME
# return hash(self.cfgimpl_get_description().impl_getkey(self))
#def __eq__(self, other):
#FIXME
# "Config's comparison"
# if not isinstance(other, Config):
# return False
# return self.cfgimpl_get_description().impl_getkey(self) == \
# other.cfgimpl_get_description().impl_getkey(other)
#def __ne__(self, other):
#FIXME
# "Config's comparison"
# if not isinstance(other, Config):
# return True
# return not self == other
2013-02-25 16:24:30 +01:00
2012-10-05 16:00:07 +02:00
# ______________________________________________________________________
def __iter__(self, force_permissive=False):
2012-11-20 17:14:58 +01:00
"""Pythonesque way of parsing group's ordered options.
iteration only on Options (not OptionDescriptions)"""
2014-06-19 23:22:39 +02:00
for child in self.cfgimpl_get_description()._impl_getchildren(
context=self._cfgimpl_get_context()):
if not child.impl_is_optiondescription():
try:
2014-06-19 23:22:39 +02:00
name = child.impl_getname()
yield name, self.getattr(name,
force_permissive=force_permissive)
2014-06-19 23:22:39 +02:00
except GeneratorExit: # pragma: optional cover
2013-03-25 14:21:30 +01:00
raise StopIteration
2014-06-19 23:22:39 +02:00
except PropertiesOptionError: # pragma: optional cover
2013-02-25 16:24:30 +01:00
pass # option with properties
def iter_all(self, force_permissive=False):
2013-03-07 11:02:18 +01:00
"""A way of parsing options **and** groups.
iteration on Options and OptionDescriptions."""
for child in self.cfgimpl_get_description().impl_getchildren():
2013-03-07 11:02:18 +01:00
try:
yield child.impl_getname(), self.getattr(child.impl_getname(),
2014-06-19 23:22:39 +02:00
force_permissive=force_permissive)
except GeneratorExit: # pragma: optional cover
2013-03-25 14:21:30 +01:00
raise StopIteration
2014-06-19 23:22:39 +02:00
except PropertiesOptionError: # pragma: optional cover
2013-03-07 11:02:18 +01:00
pass # option with properties
def iter_groups(self, group_type=None, force_permissive=False):
2012-11-20 17:14:58 +01:00
"""iteration on groups objects only.
All groups are returned if `group_type` is `None`, otherwise the groups
can be filtered by categories (families, or whatever).
2013-02-21 17:07:00 +01:00
2012-12-10 14:38:25 +01:00
:param group_type: if defined, is an instance of `groups.GroupType`
or `groups.MasterGroupType` that lives in
2013-02-07 16:20:21 +01:00
`setting.groups`
2012-11-20 17:14:58 +01:00
"""
if group_type is not None and not isinstance(group_type,
2014-06-19 23:22:39 +02:00
groups.GroupType): # pragma: optional cover
raise TypeError(_("unknown group_type: {0}").format(group_type))
2014-06-19 23:22:39 +02:00
for child in self.cfgimpl_get_description()._impl_getchildren(
context=self._cfgimpl_get_context()):
if child.impl_is_optiondescription():
2012-11-06 15:19:36 +01:00
try:
if group_type is None or (group_type is not None and
child.impl_get_group_type()
2013-05-02 11:34:57 +02:00
== group_type):
2014-06-19 23:22:39 +02:00
name = child.impl_getname()
yield name, self.getattr(name, force_permissive=force_permissive)
except GeneratorExit: # pragma: optional cover
2013-03-25 14:21:30 +01:00
raise StopIteration
2014-06-19 23:22:39 +02:00
except PropertiesOptionError: # pragma: optional cover
2012-12-06 18:14:57 +01:00
pass
2012-10-05 16:00:07 +02:00
# ______________________________________________________________________
2013-04-03 12:20:26 +02:00
2012-11-28 10:14:16 +01:00
def __str__(self):
2012-10-05 16:00:07 +02:00
"Config's string representation"
lines = []
2012-11-28 10:14:16 +01:00
for name, grp in self.iter_groups():
lines.append("[{0}]".format(name))
2012-11-28 10:14:16 +01:00
for name, value in self:
try:
lines.append("{0} = {1}".format(name, value))
2014-06-19 23:22:39 +02:00
except UnicodeEncodeError: # pragma: optional cover
lines.append("{0} = {1}".format(name,
value.encode(default_encoding)))
return '\n'.join(lines)
2012-11-28 10:14:16 +01:00
__repr__ = __str__
def _cfgimpl_get_context(self):
"""context could be None, we need to test it
context is None only if all reference to `Config` object is deleted
(for example we delete a `Config` and we manipulate a reference to
old `SubConfig`, `Values`, `Multi` or `Settings`)
"""
context = self._impl_context()
2014-06-19 23:22:39 +02:00
if context is None: # pragma: optional cover
raise ConfigError(_('the context does not exist anymore'))
return context
2013-05-02 11:34:57 +02:00
def cfgimpl_get_description(self):
2014-06-19 23:22:39 +02:00
if self._impl_descr is None: # pragma: optional cover
2013-08-20 12:08:02 +02:00
raise ConfigError(_('no option description found for this config'
2013-09-30 16:22:08 +02:00
' (may be GroupConfig)'))
2013-05-02 11:34:57 +02:00
else:
return self._impl_descr
2013-05-02 11:34:57 +02:00
def cfgimpl_get_settings(self):
return self._cfgimpl_get_context()._impl_settings
2013-05-02 11:34:57 +02:00
def cfgimpl_get_values(self):
return self._cfgimpl_get_context()._impl_values
2013-05-02 11:34:57 +02:00
# ____________________________________________________________
# attribute methods
def __setattr__(self, name, value):
"attribute notation mechanism for the setting of the value of an option"
self._setattr(name, value)
def _setattr(self, name, value, force_permissive=False):
2014-06-19 23:22:39 +02:00
if name.startswith('_impl_'):
object.__setattr__(self, name, value)
return
if '.' in name: # pragma: optional cover
2013-05-02 11:34:57 +02:00
homeconfig, name = self.cfgimpl_get_home_by_path(name)
2014-06-19 23:22:39 +02:00
return homeconfig._setattr(name, value, force_permissive)
context = self._cfgimpl_get_context()
child = self.cfgimpl_get_description().__getattr__(name,
context=context)
2013-09-26 22:35:12 +02:00
if isinstance(child, OptionDescription):
2014-06-19 23:22:39 +02:00
raise TypeError(_("can't assign to an OptionDescription")) # pragma: optional cover
elif isinstance(child, SymLinkOption) and \
not isinstance(child, DynSymLinkOption): # pragma: no dynoptiondescription cover
2013-08-21 18:34:32 +02:00
path = context.cfgimpl_get_description().impl_get_path_by_opt(
2014-11-10 09:13:44 +01:00
child._impl_getopt())
2013-05-02 11:34:57 +02:00
context._setattr(path, value, force_permissive=force_permissive)
2014-06-19 23:22:39 +02:00
else:
subpath = self._get_subpath(name)
self.cfgimpl_get_values().setitem(child, value, subpath,
force_permissive=force_permissive)
2013-05-02 11:34:57 +02:00
def __delattr__(self, name):
2014-06-19 23:22:39 +02:00
context = self._cfgimpl_get_context()
child = self.cfgimpl_get_description().__getattr__(name, context)
self.cfgimpl_get_values().__delitem__(child)
2013-05-02 11:34:57 +02:00
def __getattr__(self, name):
return self.getattr(name)
2013-05-02 11:34:57 +02:00
2014-06-19 23:22:39 +02:00
def _getattr(self, name, force_permissive=False, validate=True): # pragma: optional cover
"""use getattr instead of _getattr
"""
return self.getattr(name, force_permissive, validate)
2014-06-19 23:22:39 +02:00
def _get_subpath(self, name):
if self._impl_path is None:
subpath = name
else:
subpath = self._impl_path + '.' + name
return subpath
2015-10-29 09:03:13 +01:00
def getattr(self, name, force_permissive=False, validate=True,
_setting_properties=undefined, index=None):
2013-05-02 11:34:57 +02:00
"""
attribute notation mechanism for accessing the value of an option
:param name: attribute name
:return: option's value if name is an option name, OptionDescription
otherwise
"""
# attribute access by passing a path,
# for instance getattr(self, "creole.general.family.adresse_ip_eth0")
if '.' in name:
2013-08-21 18:34:32 +02:00
homeconfig, name = self.cfgimpl_get_home_by_path(
name, force_permissive=force_permissive)
return homeconfig.getattr(name, force_permissive=force_permissive,
2015-10-29 09:03:13 +01:00
validate=validate,
_setting_properties=_setting_properties,
index=index)
2014-06-19 23:22:39 +02:00
context = self._cfgimpl_get_context()
2015-05-03 09:56:03 +02:00
option = self.cfgimpl_get_description().__getattr__(name,
context=context)
2014-06-19 23:22:39 +02:00
subpath = self._get_subpath(name)
2015-05-03 09:56:03 +02:00
if isinstance(option, DynSymLinkOption):
return self.cfgimpl_get_values()._get_cached_value(
2015-05-03 09:56:03 +02:00
option, path=subpath,
2014-06-19 23:22:39 +02:00
validate=validate,
2015-10-29 09:03:13 +01:00
force_permissive=force_permissive,
setting_properties=_setting_properties, index=index)
2015-05-03 09:56:03 +02:00
elif isinstance(option, SymLinkOption): # pragma: no dynoptiondescription cover
2013-08-21 18:34:32 +02:00
path = context.cfgimpl_get_description().impl_get_path_by_opt(
2015-05-03 09:56:03 +02:00
option._impl_getopt())
return context.getattr(path, validate=validate,
2015-10-29 09:03:13 +01:00
force_permissive=force_permissive,
_setting_properties=_setting_properties,
index=index)
2015-05-03 09:56:03 +02:00
elif option.impl_is_optiondescription():
2013-08-21 18:34:32 +02:00
self.cfgimpl_get_settings().validate_properties(
2015-05-03 09:56:03 +02:00
option, True, False, path=subpath,
2015-10-29 09:03:13 +01:00
force_permissive=force_permissive,
setting_properties=_setting_properties)
2015-05-03 09:56:03 +02:00
return SubConfig(option, self._impl_context, subpath)
2013-05-02 11:34:57 +02:00
else:
return self.cfgimpl_get_values()._get_cached_value(
2015-05-03 09:56:03 +02:00
option, path=subpath,
2013-08-21 18:34:32 +02:00
validate=validate,
2015-10-29 09:03:13 +01:00
force_permissive=force_permissive,
setting_properties=_setting_properties,
index=index)
2013-04-03 12:20:26 +02:00
def find(self, bytype=None, byname=None, byvalue=undefined, type_='option',
check_properties=True, force_permissive=False):
2013-04-04 11:24:00 +02:00
"""
finds a list of options recursively in the config
:param bytype: Option class (BoolOption, StrOption, ...)
:param byname: filter by Option.impl_getname()
2013-04-04 11:24:00 +02:00
:param byvalue: filter by the option's value
:returns: list of matching Option objects
"""
return self._cfgimpl_get_context()._find(bytype, byname, byvalue,
first=False,
type_=type_,
2014-06-19 23:22:39 +02:00
_subpath=self.cfgimpl_get_path(False),
check_properties=check_properties,
force_permissive=force_permissive)
2013-04-03 12:20:26 +02:00
def find_first(self, bytype=None, byname=None, byvalue=undefined,
type_='option', display_error=True, check_properties=True,
force_permissive=False):
2013-04-04 11:24:00 +02:00
"""
finds an option recursively in the config
:param bytype: Option class (BoolOption, StrOption, ...)
:param byname: filter by Option.impl_getname()
2013-04-04 11:24:00 +02:00
:param byvalue: filter by the option's value
:returns: list of matching Option objects
"""
return self._cfgimpl_get_context()._find(
2013-08-21 18:34:32 +02:00
bytype, byname, byvalue, first=True, type_=type_,
2014-06-19 23:22:39 +02:00
_subpath=self.cfgimpl_get_path(False), display_error=display_error,
check_properties=check_properties,
force_permissive=force_permissive)
2013-04-04 11:24:00 +02:00
2013-05-02 11:34:57 +02:00
def _find(self, bytype, byname, byvalue, first, type_='option',
_subpath=None, check_properties=True, display_error=True,
force_permissive=False, only_path=undefined,
2015-12-14 23:37:15 +01:00
only_option=undefined, setting_properties=undefined):
2013-05-02 11:34:57 +02:00
"""
convenience method for finding an option that lives only in the subtree
:param first: return only one option if True, a list otherwise
:return: find list or an exception if nothing has been found
"""
2014-11-10 09:13:44 +01:00
2013-05-02 11:34:57 +02:00
def _filter_by_value():
if byvalue is undefined:
2013-05-02 11:34:57 +02:00
return True
try:
2015-12-14 23:37:15 +01:00
value = self.getattr(path, force_permissive=force_permissive,
_setting_properties=setting_properties)
if isinstance(value, Multi):
return byvalue in value
else:
return value == byvalue
2014-06-19 23:22:39 +02:00
# a property is a restriction upon the access of the value
except PropertiesOptionError: # pragma: optional cover
return False
2013-05-02 11:34:57 +02:00
2014-06-19 23:22:39 +02:00
if type_ not in ('option', 'path', 'value'): # pragma: optional cover
2013-08-20 12:08:02 +02:00
raise ValueError(_('unknown type_ type {0}'
'for _find').format(type_))
2013-05-02 11:34:57 +02:00
find_results = []
2014-02-01 16:26:23 +01:00
# if value and/or check_properties are set, need all avalaible option
# If first one has no good value or not good property check second one
# and so on
only_first = first is True and byvalue is None and \
check_properties is None
if only_path is not undefined:
options = [(only_path, only_option)]
else:
options = self.cfgimpl_get_description().impl_get_options_paths(
bytype, byname, _subpath, only_first,
self._cfgimpl_get_context())
2014-02-01 16:26:23 +01:00
for path, option in options:
2013-05-02 11:34:57 +02:00
if not _filter_by_value():
continue
#remove option with propertyerror, ...
if byvalue is undefined and check_properties:
2013-05-02 11:34:57 +02:00
try:
value = self.getattr(path,
2015-12-14 23:37:15 +01:00
force_permissive=force_permissive,
_setting_properties=setting_properties)
2014-06-19 23:22:39 +02:00
except PropertiesOptionError: # pragma: optional cover
2013-05-02 11:34:57 +02:00
# a property restricts the access of the value
continue
if type_ == 'value':
retval = value
elif type_ == 'path':
retval = path
elif type_ == 'option':
retval = option
if first:
return retval
else:
find_results.append(retval)
return self._find_return_results(find_results, display_error)
def _find_return_results(self, find_results, display_error):
2014-06-19 23:22:39 +02:00
if find_results == []: # pragma: optional cover
2013-07-17 23:02:50 +02:00
if display_error:
2013-08-20 12:08:02 +02:00
raise AttributeError(_("no option found in config"
" with these criteria"))
2013-07-17 23:02:50 +02:00
else:
# translation is slow
2013-07-17 23:02:50 +02:00
raise AttributeError()
2013-05-02 11:34:57 +02:00
else:
return find_results
def make_dict(self, flatten=False, _currpath=None, withoption=None,
2015-12-14 23:37:15 +01:00
withvalue=undefined, force_permissive=False,
setting_properties=undefined):
"""exports the whole config into a `dict`, for example:
2013-05-23 17:51:50 +02:00
>>> print cfg.make_dict()
{'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
2013-05-23 17:51:50 +02:00
:param flatten: returns a dict(name=value) instead of a dict(path=value)
::
>>> print cfg.make_dict(flatten=True)
{'var5': None, 'var4': None, 'var6': None}
2013-05-23 17:51:50 +02:00
:param withoption: returns the options that are present in the very same
`OptionDescription` than the `withoption` itself::
>>> print cfg.make_dict(withoption='var1')
2013-08-20 12:08:02 +02:00
{'od2.var4': None, 'od2.var5': None,
'od2.var6': None,
'od2.var1': u'value',
'od1.var1': None,
'od1.var3': None,
'od1.var2': None}
2013-05-23 17:51:50 +02:00
:param withvalue: returns the options that have the value `withvalue`
::
2013-08-20 12:08:02 +02:00
>>> print c.make_dict(withoption='var1',
withvalue=u'value')
{'od2.var4': None,
'od2.var5': None,
'od2.var6': None,
2013-05-23 17:51:50 +02:00
'od2.var1': u'value'}
2013-05-23 14:55:52 +02:00
:returns: dict of Option's name (or path) and values
"""
2013-04-04 11:24:00 +02:00
pathsvalues = []
if _currpath is None:
_currpath = []
2014-06-19 23:22:39 +02:00
if withoption is None and withvalue is not undefined: # pragma: optional cover
2013-05-02 11:34:57 +02:00
raise ValueError(_("make_dict can't filtering with value without "
"option"))
2015-12-14 23:37:15 +01:00
if setting_properties is undefined:
setting_properties = self.cfgimpl_get_settings()._getproperties(
read_write=False)
2013-04-04 11:24:00 +02:00
if withoption is not None:
2014-06-19 23:22:39 +02:00
context = self._cfgimpl_get_context()
for path in context._find(bytype=None, byname=withoption,
byvalue=withvalue, first=False,
type_='path', _subpath=self.cfgimpl_get_path(False),
2015-12-14 23:37:15 +01:00
force_permissive=force_permissive,
setting_properties=setting_properties):
2013-04-04 11:24:00 +02:00
path = '.'.join(path.split('.')[:-1])
2014-06-19 23:22:39 +02:00
opt = context.unwrap_from_path(path, force_permissive=True)
mypath = self.cfgimpl_get_path()
2013-04-04 11:24:00 +02:00
if mypath is not None:
if mypath == path:
withoption = None
withvalue = undefined
2013-04-04 11:24:00 +02:00
break
else:
tmypath = mypath + '.'
2014-06-19 23:22:39 +02:00
if not path.startswith(tmypath): # pragma: optional cover
2013-04-14 12:01:32 +02:00
raise AttributeError(_('unexpected path {0}, '
2013-05-02 11:34:57 +02:00
'should start with {1}'
'').format(path, mypath))
2013-04-04 11:24:00 +02:00
path = path[len(tmypath):]
self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
2015-12-14 23:37:15 +01:00
force_permissive=force_permissive,
setting_properties=setting_properties)
2013-04-04 11:24:00 +02:00
#withoption can be set to None below !
if withoption is None:
for opt in self.cfgimpl_get_description().impl_getchildren():
path = opt.impl_getname()
self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
2015-12-14 23:37:15 +01:00
force_permissive=force_permissive,
setting_properties=setting_properties)
2013-04-04 11:24:00 +02:00
if _currpath == []:
options = dict(pathsvalues)
return options
return pathsvalues
def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten,
2015-12-14 23:37:15 +01:00
setting_properties, force_permissive=False):
2014-03-12 14:57:36 +01:00
try:
2014-06-19 23:22:39 +02:00
if opt.impl_is_optiondescription():
pathsvalues += self.getattr(path,
2015-12-14 23:37:15 +01:00
force_permissive=force_permissive,
_setting_properties=setting_properties).make_dict(
flatten,
_currpath + path.split('.'),
2015-12-14 23:37:15 +01:00
force_permissive=force_permissive,
setting_properties=setting_properties)
2014-02-04 21:14:30 +01:00
else:
value = self.getattr(opt.impl_getname(),
2015-12-14 23:37:15 +01:00
force_permissive=force_permissive,
_setting_properties=setting_properties)
2013-04-04 11:24:00 +02:00
if flatten:
name = opt.impl_getname()
2013-04-04 11:24:00 +02:00
else:
name = '.'.join(_currpath + [opt.impl_getname()])
2013-04-04 11:24:00 +02:00
pathsvalues.append((name, value))
2014-06-19 23:22:39 +02:00
except PropertiesOptionError: # pragma: optional cover
2014-03-12 14:57:36 +01:00
pass
2013-04-03 12:20:26 +02:00
2014-06-19 23:22:39 +02:00
def cfgimpl_get_path(self, dyn=True):
2013-05-02 11:34:57 +02:00
descr = self.cfgimpl_get_description()
2014-06-19 23:22:39 +02:00
if not dyn and descr.impl_is_dynoptiondescription():
context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
2014-11-10 09:13:44 +01:00
return context_descr.impl_get_path_by_opt(descr._impl_getopt())
2014-06-19 23:22:39 +02:00
return self._impl_path
2013-04-03 12:20:26 +02:00
2013-09-30 16:22:08 +02:00
class _CommonConfig(SubConfig):
"abstract base class for the Config, GroupConfig and the MetaConfig"
__slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
2013-04-03 12:20:26 +02:00
2014-01-25 10:15:25 +01:00
def _impl_build_all_caches(self):
2015-05-03 09:56:03 +02:00
descr = self.cfgimpl_get_description()
if not descr.impl_already_build_caches():
2015-12-22 22:06:14 +01:00
descr.impl_build_cache()
2015-05-03 09:56:03 +02:00
descr.impl_build_cache_option()
def read_only(self):
2013-05-14 17:40:42 +02:00
"read only is a global config's setting, see `settings.py`"
self.cfgimpl_get_settings().read_only()
def read_write(self):
2013-05-14 17:40:42 +02:00
"read write is a global config's setting, see `settings.py`"
self.cfgimpl_get_settings().read_write()
2015-11-19 22:25:00 +01:00
def getowner(self, opt, index=None, force_permissive=False):
2013-05-14 17:40:42 +02:00
"""convenience method to retrieve an option's owner
from the config itself
"""
2014-11-10 09:13:44 +01:00
if not isinstance(opt, Option) and \
not isinstance(opt, SymLinkOption) and \
not isinstance(opt, DynSymLinkOption): # pragma: optional cover
2013-08-24 22:32:54 +02:00
raise TypeError(_('opt in getowner must be an option not {0}'
'').format(type(opt)))
2015-11-19 22:25:00 +01:00
return self.cfgimpl_get_values().getowner(opt, index=index,
force_permissive=force_permissive)
2013-04-03 12:20:26 +02:00
def unwrap_from_path(self, path, force_permissive=False):
2013-04-03 12:20:26 +02:00
"""convenience method to extract and Option() object from the Config()
and it is **fast**: finds the option directly in the appropriate
namespace
:returns: Option()
"""
2014-06-19 23:22:39 +02:00
context = self._cfgimpl_get_context()
2013-04-03 12:20:26 +02:00
if '.' in path:
2013-08-20 12:08:02 +02:00
homeconfig, path = self.cfgimpl_get_home_by_path(
2013-08-21 18:34:32 +02:00
path, force_permissive=force_permissive)
2014-06-19 23:22:39 +02:00
return homeconfig.cfgimpl_get_description().__getattr__(path, context=context)
return self.cfgimpl_get_description().__getattr__(path, context=context)
2013-04-03 12:20:26 +02:00
2014-06-19 23:22:39 +02:00
def cfgimpl_get_path(self, dyn=True):
2013-04-04 11:24:00 +02:00
return None
2013-04-03 12:20:26 +02:00
2013-05-02 11:34:57 +02:00
def cfgimpl_get_meta(self):
2013-09-30 16:22:08 +02:00
if self._impl_meta is not None:
return self._impl_meta()
# information
def impl_set_information(self, key, value):
"""updates the information's attribute
:param key: information's key (ex: "help", "doc"
:param value: information's value (ex: "the help string")
"""
self._impl_values.set_information(key, value)
def impl_get_information(self, key, default=undefined):
"""retrieves one information's item
:param key: the item string (ex: "help")
"""
return self._impl_values.get_information(key, default)
2013-09-30 16:22:08 +02:00
# ----- state
2013-09-22 20:57:52 +02:00
def __getstate__(self):
if self._impl_meta is not None:
2014-06-19 23:22:39 +02:00
raise ConfigError(_('cannot serialize Config with MetaConfig')) # pragma: optional cover
2013-09-22 20:57:52 +02:00
slots = set()
for subclass in self.__class__.__mro__:
if subclass is not object:
slots.update(subclass.__slots__)
2013-10-15 18:23:36 +02:00
slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
2013-09-22 20:57:52 +02:00
state = {}
for slot in slots:
try:
state[slot] = getattr(self, slot)
2014-06-19 23:22:39 +02:00
except AttributeError: # pragma: optional cover
2013-09-22 20:57:52 +02:00
pass
storage = self._impl_values._p_._storage
if not storage.serializable:
2014-02-02 22:47:46 +01:00
raise ConfigError(_('this storage is not serialisable, could be a '
2014-06-19 23:22:39 +02:00
'none persistent storage')) # pragma: optional cover
2013-09-22 20:57:52 +02:00
state['_storage'] = {'session_id': storage.session_id,
'persistent': storage.persistent}
state['_impl_setting'] = _impl_getstate_setting()
return state
def __setstate__(self, state):
for key, value in state.items():
if key not in ['_storage', '_impl_setting']:
setattr(self, key, value)
2014-04-12 22:47:52 +02:00
set_storage('config', **state['_impl_setting'])
2013-09-22 20:57:52 +02:00
self._impl_context = weakref.ref(self)
self._impl_settings.context = weakref.ref(self)
self._impl_values.context = weakref.ref(self)
2014-04-12 22:47:52 +02:00
storage = get_storage('config', test=self._impl_test, **state['_storage'])
2013-09-22 20:57:52 +02:00
self._impl_values._impl_setstate(storage)
self._impl_settings._impl_setstate(storage)
2013-10-15 18:23:36 +02:00
self._impl_meta = None
2012-10-12 11:35:07 +02:00
2015-04-18 22:53:45 +02:00
def _gen_fake_values(self):
fake_config = Config(self._impl_descr, persistent=False,
force_values=get_storages_validation(),
2015-05-03 09:56:03 +02:00
force_settings=self.cfgimpl_get_settings())
2015-11-19 22:25:00 +01:00
fake_config.cfgimpl_get_values()._p_._values = self.cfgimpl_get_values()._p_._values
2015-04-18 22:53:45 +02:00
return fake_config
2015-07-24 17:54:10 +02:00
def duplicate(self):
config = Config(self._impl_descr)
2015-11-19 22:25:00 +01:00
config.cfgimpl_get_values()._p_._values = self.cfgimpl_get_values()._p_._values
2015-07-24 17:54:10 +02:00
config.cfgimpl_get_settings()._p_._properties = self.cfgimpl_get_settings()._p_.get_modified_properties()
config.cfgimpl_get_settings()._p_._permissives = self.cfgimpl_get_settings()._p_.get_modified_permissives()
return config
2013-09-30 16:22:08 +02:00
# ____________________________________________________________
class Config(_CommonConfig):
"main configuration management entry"
__slots__ = ('__weakref__', '_impl_test', '_impl_name')
2013-09-30 16:22:08 +02:00
def __init__(self, descr, session_id=None, persistent=False,
name=undefined, force_values=None, force_settings=None):
2013-09-30 16:22:08 +02:00
""" Configuration option management master class
:param descr: describes the configuration schema
:type descr: an instance of ``option.OptionDescription``
:param context: the current root config
:type context: `Config`
:param session_id: session ID is import with persistent Config to
retrieve good session
:type session_id: `str`
:param persistent: if persistent, don't delete storage when leaving
:type persistent: `boolean`
"""
if force_settings is not None and force_values is not None:
2015-05-03 09:56:03 +02:00
self._impl_settings = force_settings
self._impl_values = Values(self, force_values)
else:
settings, values = get_storages(self, session_id, persistent)
if name is undefined:
name = 'config'
if session_id is not None:
name += session_id
if name is not None and not valid_name(name): # pragma: optional cover
raise ValueError(_("invalid name: {0} for config").format(name))
self._impl_settings = Settings(self, settings)
self._impl_values = Values(self, values)
2015-05-03 09:56:03 +02:00
super(Config, self).__init__(descr, weakref.ref(self))
self._impl_build_all_caches()
2015-05-03 09:56:03 +02:00
self._impl_meta = None
#undocumented option used only in test script
self._impl_test = False
self._impl_name = name
2013-09-30 16:22:08 +02:00
2013-08-20 12:08:02 +02:00
def cfgimpl_reset_cache(self,
only_expired=False,
only=('values', 'settings')):
2013-05-02 11:34:57 +02:00
if 'values' in only:
self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
if 'settings' in only:
self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
2013-02-22 11:09:17 +01:00
def impl_getname(self):
return self._impl_name
2013-09-30 16:22:08 +02:00
class GroupConfig(_CommonConfig):
__slots__ = ('__weakref__', '_impl_children', '_impl_name')
2012-10-12 11:35:07 +02:00
2013-09-30 16:22:08 +02:00
def __init__(self, children, session_id=None, persistent=False,
_descr=None, name=undefined):
2013-09-17 09:02:10 +02:00
if not isinstance(children, list):
raise ValueError(_("groupconfig's children must be a list"))
names = []
for child in children:
if not isinstance(child, _CommonConfig):
raise ValueError(_("groupconfig's children must be Config, MetaConfig or GroupConfig"))
name_ = child._impl_name
if name_ is None:
raise ValueError(_('name must be set to config before creating groupconfig'))
names.append(name_)
if len(names) != len(set(names)):
for idx in xrange(1, len(names) + 1):
name = names.pop(0)
if name in names:
raise ConflictError(_('config name must be uniq in '
'groupconfig for {0}').format(name))
2013-09-17 09:02:10 +02:00
self._impl_children = children
settings, values = get_storages(self, session_id, persistent)
self._impl_settings = Settings(self, settings)
self._impl_values = Values(self, values)
2013-09-30 16:22:08 +02:00
super(GroupConfig, self).__init__(_descr, weakref.ref(self))
2013-09-17 09:02:10 +02:00
self._impl_meta = None
2013-09-30 16:22:08 +02:00
#undocumented option used only in test script
self._impl_test = False
if name is undefined:
name = session_id
self._impl_name = name
2013-09-17 09:02:10 +02:00
def cfgimpl_get_children(self):
return self._impl_children
2013-09-30 16:22:08 +02:00
#def cfgimpl_get_context(self):
# "a meta config is a config which has a setting, that is itself"
# return self
2013-08-20 12:08:02 +02:00
def cfgimpl_reset_cache(self,
only_expired=False,
only=('values', 'settings')):
2013-05-02 11:34:57 +02:00
if 'values' in only:
self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
if 'settings' in only:
self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
2013-09-17 09:02:10 +02:00
for child in self._impl_children:
child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
2013-02-22 11:09:17 +01:00
def set_value(self, path, value):
2013-09-30 16:22:08 +02:00
"""Setattr not in current GroupConfig, but in each children
"""
2013-09-17 09:02:10 +02:00
for child in self._impl_children:
try:
if isinstance(child, MetaConfig):
child.set_value(path, value, only_config=True)
elif isinstance(child, GroupConfig):
child.set_value(path, value)
2013-09-17 09:02:10 +02:00
else:
setattr(child, path, value)
2013-09-17 09:02:10 +02:00
except PropertiesOptionError:
pass
def find_firsts(self, byname=None, bypath=undefined, byoption=undefined,
byvalue=undefined, display_error=True, _sub=False,
check_properties=True):
2013-09-30 16:22:08 +02:00
"""Find first not in current GroupConfig, but in each children
"""
2013-09-17 09:02:10 +02:00
ret = []
#if MetaConfig, all children have same OptionDescription in context
#so search only one time the option for all children
if bypath is undefined and byname is not None and \
isinstance(self, MetaConfig):
bypath = self._find(bytype=None, byvalue=undefined, byname=byname,
first=True, type_='path',
check_properties=None,
display_error=display_error)
byname = None
byoption = self.cfgimpl_get_description(
).impl_get_opt_by_path(bypath)
2013-09-17 09:02:10 +02:00
for child in self._impl_children:
try:
if isinstance(child, GroupConfig):
ret.extend(child.find_firsts(byname=byname, bypath=bypath,
byoption=byoption,
2013-09-30 16:22:08 +02:00
byvalue=byvalue,
check_properties=check_properties,
display_error=False,
_sub=True))
else:
child._find(None, byname, byvalue, first=True,
type_='path', display_error=False,
check_properties=check_properties,
only_path=bypath, only_option=byoption)
ret.append(child)
2013-09-17 09:02:10 +02:00
except AttributeError:
pass
if _sub:
return ret
else:
return GroupConfig(self._find_return_results(ret, display_error))
2013-05-02 11:34:57 +02:00
2014-11-10 23:15:08 +01:00
def __repr__(self):
return object.__repr__(self)
def __str__(self):
ret = ''
for child in self._impl_children:
ret += '({0})\n'.format(child._impl_name)
try:
ret += super(GroupConfig, self).__str__()
except ConfigError:
pass
return ret
2015-12-14 23:37:15 +01:00
def getattr(self, name, force_permissive=False, validate=True,
_setting_properties=undefined):
for child in self._impl_children:
if name == child._impl_name:
return child
return super(GroupConfig, self).getattr(name, force_permissive,
2015-12-14 23:37:15 +01:00
validate,
_setting_properties=_setting_properties)
2014-11-10 23:15:08 +01:00
2013-09-30 16:22:08 +02:00
class MetaConfig(GroupConfig):
__slots__ = tuple()
def __init__(self, children, session_id=None, persistent=False,
name=undefined):
2013-09-30 16:22:08 +02:00
descr = None
for child in children:
if not isinstance(child, _CommonConfig):
raise TypeError(_("metaconfig's children "
"should be config, not {0}"
).format(type(child)))
if child.cfgimpl_get_meta() is not None:
raise ValueError(_("child has already a metaconfig's"))
if descr is None:
descr = child.cfgimpl_get_description()
elif not descr is child.cfgimpl_get_description():
raise ValueError(_('all config in metaconfig must '
'have the same optiondescription'))
child._impl_meta = weakref.ref(self)
super(MetaConfig, self).__init__(children, session_id, persistent,
descr, name)
def set_value(self, path, value, force_default=False,
force_dont_change_value=False, force_default_if_same=False,
only_config=False):
"""only_config: could be set if you want modify value in all Config included in
this MetaConfig
"""
if only_config:
if force_default or force_default_if_same or force_dont_change_value:
raise ValueError(_('force_default, force_default_if_same or '
'force_dont_change_value cannot be set with'
' only_config'))
return super(MetaConfig, self).set_value(path, value)
if force_default or force_default_if_same or force_dont_change_value:
if force_default and force_dont_change_value:
raise ValueError(_('force_default and force_dont_change_value'
' cannot be set together'))
opt = self.cfgimpl_get_description().impl_get_opt_by_path(path)
for child in self._impl_children:
if force_default_if_same or force_default:
if force_default_if_same:
if not child.cfgimpl_get_values()._contains(path):
child_value = undefined
else:
child_value = child.getattr(path)
if force_default or value == child_value:
child.cfgimpl_get_values().reset(opt, path=path,
validate=False)
continue
if force_dont_change_value:
child_value = child.getattr(path)
if value != child_value:
setattr(child, path, child_value)
setattr(self, path, value)