tiramisu/tiramisu/setting.py

392 lines
14 KiB
Python
Raw Normal View History

2012-11-19 10:45:03 +01:00
# -*- coding: utf-8 -*-
"sets the options of the configuration objects Config object itself"
2013-03-01 13:10:52 +01:00
# Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
2012-11-19 10:45:03 +01:00
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# 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
# ____________________________________________________________
from time import time
2013-04-14 12:01:32 +02:00
from tiramisu.error import RequirementRecursionError, PropertiesOptionError
from tiramisu.i18n import _
2013-04-03 12:20:26 +02:00
expires_time = 5
2012-12-06 18:14:57 +01:00
class _const:
"""convenient class that emulates a module
2012-12-10 09:53:13 +01:00
and builds constants (that is, unique names)"""
2013-04-03 12:20:26 +02:00
class ConstError(TypeError):
pass
2012-12-06 18:14:57 +01:00
def __setattr__(self, name, value):
2013-04-03 12:20:26 +02:00
if name in self.__dict__:
2013-04-14 12:01:32 +02:00
raise self.ConstError, _("Can't rebind group ({})").format(name)
2012-12-06 18:14:57 +01:00
self.__dict__[name] = value
def __delattr__(self, name):
2013-04-03 12:20:26 +02:00
if name in self.__dict__:
2013-04-14 12:01:32 +02:00
raise self.ConstError, _("Can't unbind group ({})").format(name)
raise ValueError(name)
2013-04-03 12:20:26 +02:00
2012-12-10 09:53:13 +01:00
# ____________________________________________________________
class GroupModule(_const):
"emulates a module to manage unique group (OptionDescription) names"
2012-12-10 14:38:25 +01:00
class GroupType(str):
2012-12-06 18:14:57 +01:00
"""allowed normal group (OptionDescription) names
*normal* means : groups that are not master
"""
pass
2013-04-03 12:20:26 +02:00
2012-12-10 14:38:25 +01:00
class DefaultGroupType(GroupType):
2012-12-10 14:10:05 +01:00
"""groups that are default (typically 'default')"""
pass
2012-12-10 14:38:25 +01:00
class MasterGroupType(GroupType):
2012-12-06 18:14:57 +01:00
"""allowed normal group (OptionDescription) names
*master* means : groups that have the 'master' attribute set
"""
pass
2012-12-10 09:53:13 +01:00
# setting.groups (emulates a module)
groups = GroupModule()
2012-12-06 18:14:57 +01:00
2013-04-03 12:20:26 +02:00
2012-12-10 09:53:13 +01:00
def populate_groups():
"populates the available groups in the appropriate namespaces"
groups.master = groups.MasterGroupType('master')
groups.default = groups.DefaultGroupType('default')
groups.family = groups.GroupType('family')
2012-12-10 09:53:13 +01:00
# names are in the module now
2012-12-06 18:14:57 +01:00
populate_groups()
2013-04-03 12:20:26 +02:00
2012-12-06 18:14:57 +01:00
# ____________________________________________________________
2012-12-10 14:10:05 +01:00
class OwnerModule(_const):
"""emulates a module to manage unique owner names.
owners are living in `Config._cfgimpl_value_owners`
"""
class Owner(str):
"""allowed owner names
"""
pass
2013-04-03 12:20:26 +02:00
2012-12-10 14:10:05 +01:00
class DefaultOwner(Owner):
"""groups that are default (typically 'default')"""
pass
# setting.owners (emulates a module)
owners = OwnerModule()
2013-04-03 12:20:26 +02:00
2012-12-10 14:10:05 +01:00
def populate_owners():
"""populates the available owners in the appropriate namespaces
- 'user' is the generic is the generic owner.
- 'default' is the config owner after init time
"""
setattr(owners, 'default', owners.DefaultOwner('default'))
2013-04-03 12:20:26 +02:00
setattr(owners, 'user', owners.Owner('user'))
2012-12-10 14:38:25 +01:00
def add_owner(name):
"""
:param name: the name of the new owner
"""
setattr(owners, name, owners.Owner(name))
setattr(owners, 'add_owner', add_owner)
2012-12-10 14:10:05 +01:00
# names are in the module now
populate_owners()
2013-02-21 17:07:00 +01:00
2013-04-03 12:20:26 +02:00
2013-02-21 17:07:00 +01:00
class MultiTypeModule(_const):
class MultiType(str):
pass
2013-04-03 12:20:26 +02:00
2013-02-21 17:07:00 +01:00
class DefaultMultiType(MultiType):
pass
2013-04-03 12:20:26 +02:00
2013-02-21 17:07:00 +01:00
class MasterMultiType(MultiType):
pass
2013-04-03 12:20:26 +02:00
2013-02-21 17:07:00 +01:00
class SlaveMultiType(MultiType):
pass
multitypes = MultiTypeModule()
2013-04-03 12:20:26 +02:00
2013-02-21 17:07:00 +01:00
def populate_multitypes():
setattr(multitypes, 'default', multitypes.DefaultMultiType('default'))
setattr(multitypes, 'master', multitypes.MasterMultiType('master'))
setattr(multitypes, 'slave', multitypes.SlaveMultiType('slave'))
populate_multitypes()
2013-04-03 12:20:26 +02:00
class Property(object):
__slots__ = ('_setting', '_properties', '_opt')
def __init__(self, setting, prop, opt=None):
self._opt = opt
self._setting = setting
self._properties = prop
def append(self, propname):
if not propname in self._properties:
self._properties.append(propname)
self._setting._set_properties(self._properties, self._opt)
self._setting.context.cfgimpl_reset_cache()
def remove(self, propname):
if propname in self._properties:
self._properties.remove(propname)
self._setting._set_properties(self._properties, self._opt)
self._setting.context.cfgimpl_reset_cache()
def __contains__(self, propname):
return propname in self._properties
2012-12-10 14:10:05 +01:00
#____________________________________________________________
2013-04-03 12:20:26 +02:00
class Setting(object):
2012-11-19 10:45:03 +01:00
"``Config()``'s configuration options"
__slots__ = ('context', '_properties', '_permissives', '_owner', '_cache')
2013-04-03 12:20:26 +02:00
def __init__(self, context):
2013-04-03 12:20:26 +02:00
# properties attribute: the name of a property enables this property
# key is None for global properties
self._properties = {None: ['expire']}
2013-04-03 12:20:26 +02:00
# permissive properties
self._permissives = {}
2013-04-03 12:20:26 +02:00
# generic owner
self._owner = owners.user
self.context = context
self._cache = {}
2013-04-03 12:20:26 +02:00
2012-12-11 11:18:53 +01:00
#____________________________________________________________
2012-11-19 10:45:03 +01:00
# properties methods
def __contains__(self, propname):
return propname in self._get_properties()
def __getitem__(self, opt):
return Property(self, self._get_properties(opt), opt)
2013-03-14 11:31:44 +01:00
def __setitem__(self, opt, value):
raise ValueError('you must only append/remove properties')
def _get_properties(self, opt=None, is_apply_req=True):
if opt is not None and opt in self._cache:
exp = time()
props, created = self._cache[opt]
if exp < created:
return props
2013-04-03 12:20:26 +02:00
if opt is None:
default = []
else:
if is_apply_req:
apply_requires(opt, self.context)
2013-04-03 12:20:26 +02:00
default = list(opt._properties)
props = self._properties.get(opt, default)
if opt is not None:
self._set_cache(opt, props)
return props
2013-03-14 11:31:44 +01:00
def append(self, propname):
2012-11-19 10:45:03 +01:00
"puts property propname in the Config's properties attribute"
Property(self, self._get_properties()).append(propname)
2012-11-19 10:45:03 +01:00
def remove(self, propname):
2012-11-19 10:45:03 +01:00
"deletes property propname in the Config's properties attribute"
Property(self, self._get_properties()).remove(propname)
2013-04-03 12:20:26 +02:00
def _set_properties(self, properties, opt=None):
2013-04-03 12:20:26 +02:00
"""save properties for specified opt
(never save properties if same has option properties)
"""
if opt is None:
self._properties[opt] = properties
2013-04-03 12:20:26 +02:00
else:
if opt._properties == properties:
if opt in self._properties:
del(self._properties[opt])
2013-04-03 12:20:26 +02:00
else:
self._properties[opt] = properties
def _validate_frozen(self, opt, value, is_write):
if not is_write:
return False
if 'permissive' in self and 'frozen' in self._get_permissive():
return False
if 'everything_frozen' in self or (
'frozen' in self and 'frozen' in self[opt]):
return True
return False
2013-04-03 12:20:26 +02:00
def _validate_mandatory(self, opt, value, force_properties):
if 'permissive' in self and 'mandatory' in self._get_permissive():
return False
check_mandatory = 'mandatory' in self
2013-04-18 23:06:14 +02:00
if force_properties is not None:
check_mandatory = ('mandatory' in force_properties or
check_mandatory)
if check_mandatory and 'mandatory' in self[opt] and \
2013-04-18 23:06:14 +02:00
self.context.cfgimpl_get_values()._is_empty(opt, value):
return True
return False
def _calc_properties(self, opt_or_descr, force_permissive, force_properties):
properties = set(self._get_properties(opt_or_descr))
2013-04-18 23:06:14 +02:00
#remove this properties, those properties are validate in after
properties = properties - set(['mandatory', 'frozen'])
set_properties = set(self._get_properties())
2013-04-18 23:06:14 +02:00
if force_properties is not None:
set_properties.update(set(force_properties))
2013-04-18 23:06:14 +02:00
properties = properties & set_properties
if force_permissive is True or 'permissive' in self:
properties = properties - set(self._get_permissive())
properties = properties - set(self._get_permissive(opt_or_descr))
2013-04-18 23:06:14 +02:00
return list(properties)
2012-12-11 11:18:53 +01:00
#____________________________________________________________
def validate_properties(self, opt_or_descr, is_descr, is_write,
value=None, force_permissive=False,
force_properties=None):
properties = self._calc_properties(opt_or_descr, force_permissive,
force_properties)
raise_text = _("trying to access"
" to an option named: {0} with properties"
" {1}")
if not is_descr:
if self._validate_mandatory(opt_or_descr, value, force_properties):
properties.append('mandatory')
if self._validate_frozen(opt_or_descr, value, is_write):
properties.append('frozen')
raise_text = _('cannot change the value to {0} for '
'option {1} this option is frozen')
if properties != []:
raise PropertiesOptionError(raise_text.format(opt_or_descr._name,
str(properties)),
properties)
def _get_permissive(self, opt=None):
return self._permissives.get(opt, [])
2013-03-14 11:31:44 +01:00
def set_permissive(self, permissive, opt=None):
if not isinstance(permissive, tuple):
raise TypeError(_('permissive must be a tuple'))
self._permissives[opt] = permissive
2013-04-03 12:20:26 +02:00
2013-02-06 14:59:24 +01:00
#____________________________________________________________
2013-04-03 12:20:26 +02:00
def setowner(self, owner):
":param owner: sets the default value for owner at the Config level"
if not isinstance(owner, owners.Owner):
2013-04-14 12:01:32 +02:00
raise TypeError(_("invalid generic owner {0}").format(str(owner)))
self._owner = owner
2012-11-19 10:45:03 +01:00
2013-04-03 12:20:26 +02:00
def getowner(self):
return self._owner
2013-02-06 14:59:24 +01:00
#____________________________________________________________
2012-11-19 10:45:03 +01:00
def read_only(self):
"convenience method to freeze, hidde and disable"
self.append('everything_frozen')
self.append('frozen') # can be usefull...
self.remove('hidden')
self.append('disabled')
self.append('mandatory')
self.append('validator')
self.remove('permissive')
2012-11-19 10:45:03 +01:00
def read_write(self):
"convenience method to freeze, hidde and disable"
self.remove('everything_frozen')
self.append('frozen') # can be usefull...
self.append('hidden')
self.append('disabled')
self.remove('mandatory')
self.append('validator')
self.remove('permissive')
def _set_cache(self, opt, props):
if 'expire' in self:
self._cache[opt] = (props, time() + expires_time)
pass
def reset_cache(self, only_expired):
if only_expired:
exp = time()
keys = self._cache.keys()
for key in keys:
props, created = self._cache[key]
if exp > created:
del(self._cache[key])
else:
self._cache.clear()
def apply_requires(opt, config):
"carries out the jit (just in time requirements between options"
def build_actions(requires):
"action are hide, show, enable, disable..."
trigger_actions = {}
for require in requires:
action = require[2]
trigger_actions.setdefault(action, []).append(require)
return trigger_actions
#for symlink
if hasattr(opt, '_requires') and opt._requires is not None:
# filters the callbacks
settings = config.cfgimpl_get_settings()
setting = Property(settings, settings._get_properties(opt, False), opt)
trigger_actions = build_actions(opt._requires)
optpath = config.cfgimpl_get_context().cfgimpl_get_description().get_path_by_opt(opt)
for requires in trigger_actions.values():
matches = False
for require in requires:
if len(require) == 3:
path, expected, action = require
inverse = False
elif len(require) == 4:
path, expected, action, inverse = require
if path == optpath or path.startswith(optpath + '.'):
2013-04-14 12:01:32 +02:00
raise RequirementRecursionError(_("malformed requirements "
"imbrication detected for option: '{0}' "
2013-04-14 12:01:32 +02:00
"with requirement on: '{1}'").format(optpath, path))
try:
value = config.cfgimpl_get_context()._getattr(path, force_permissive=True)
except PropertiesOptionError, err:
properties = err.proptype
raise PropertiesOptionError(_("option '{0}' has requirement's property error: "
"{1} {2}").format(opt._name, path, properties))
except AttributeError:
2013-04-14 12:01:32 +02:00
raise AttributeError(_("required option not found: "
"{0}").format(path))
if value == expected:
if inverse:
setting.remove(action)
else:
setting.append(action)
matches = True
# no requirement has been triggered, then just reverse the action
if not matches:
if inverse:
setting.append(action)
else:
setting.remove(action)