931 lines
39 KiB
Python
931 lines
39 KiB
Python
# -*- coding: utf-8 -*-
|
|
# Copyright (C) 2014 Team tiramisu (see AUTHORS for all contributors)
|
|
#
|
|
# 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.
|
|
#
|
|
# 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.
|
|
#
|
|
# 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/>.
|
|
#
|
|
# 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
|
|
# ____________________________________________________________
|
|
import re
|
|
from copy import copy
|
|
from types import FunctionType
|
|
import warnings
|
|
|
|
from tiramisu.i18n import _
|
|
from tiramisu.setting import log, undefined
|
|
from tiramisu.autolib import carry_out_calculation
|
|
from tiramisu.error import ConfigError, ValueWarning
|
|
from tiramisu.storage import get_storages_option
|
|
|
|
|
|
StorageBase = get_storages_option('base')
|
|
|
|
|
|
class SubMulti(object):
|
|
pass
|
|
|
|
|
|
submulti = SubMulti()
|
|
|
|
|
|
name_regexp = re.compile(r'^\d+')
|
|
forbidden_names = ('iter_all', 'iter_group', 'find', 'find_first',
|
|
'make_dict', 'unwrap_from_path', 'read_only',
|
|
'read_write', 'getowner', 'set_contexts')
|
|
|
|
|
|
def valid_name(name):
|
|
"an option's name is a str and does not start with 'impl' or 'cfgimpl'"
|
|
if not isinstance(name, str):
|
|
return False
|
|
if re.match(name_regexp, name) is None and not name.startswith('_') \
|
|
and name not in forbidden_names \
|
|
and not name.startswith('impl_') \
|
|
and not name.startswith('cfgimpl_'):
|
|
return True
|
|
else:
|
|
return False
|
|
|
|
|
|
def validate_callback(callback, callback_params, type_):
|
|
if type(callback) != FunctionType:
|
|
raise ValueError(_('{0} must be a function').format(type_))
|
|
if callback_params is not None:
|
|
if not isinstance(callback_params, dict):
|
|
raise ValueError(_('{0}_params must be a dict').format(type_))
|
|
for key, callbacks in callback_params.items():
|
|
if key != '' and len(callbacks) != 1:
|
|
raise ValueError(_("{0}_params with key {1} mustn't have "
|
|
"length different to 1").format(type_,
|
|
key))
|
|
if not isinstance(callbacks, tuple):
|
|
raise ValueError(_('{0}_params must be tuple for key "{1}"'
|
|
).format(type_, key))
|
|
for callbk in callbacks:
|
|
if isinstance(callbk, tuple):
|
|
if len(callbk) == 1:
|
|
if callbk != (None,):
|
|
raise ValueError(_('{0}_params with length of '
|
|
'tuple as 1 must only have '
|
|
'None as first value'))
|
|
elif len(callbk) != 2:
|
|
raise ValueError(_('{0}_params must only have 1 or 2 '
|
|
'as length'))
|
|
else:
|
|
option, force_permissive = callbk
|
|
if type_ == 'validator' and not force_permissive:
|
|
raise ValueError(_('validator not support tuple'))
|
|
if not isinstance(option, Option) and not \
|
|
isinstance(option, SymLinkOption):
|
|
raise ValueError(_('{0}_params must have an option'
|
|
' not a {0} for first argument'
|
|
).format(type_, type(option)))
|
|
if force_permissive not in [True, False]:
|
|
raise ValueError(_('{0}_params must have a boolean'
|
|
' not a {0} for second argument'
|
|
).format(type_, type(
|
|
force_permissive)))
|
|
#____________________________________________________________
|
|
#
|
|
|
|
|
|
class Base(StorageBase):
|
|
__slots__ = tuple()
|
|
|
|
def __init__(self, name, doc, default=None, default_multi=None,
|
|
requires=None, multi=False, callback=None,
|
|
callback_params=None, validator=None, validator_params=None,
|
|
properties=None, warnings_only=False):
|
|
if not valid_name(name):
|
|
raise ValueError(_("invalid name: {0} for option").format(name))
|
|
self._name = name
|
|
self._readonly = False
|
|
self._informations = {}
|
|
self.impl_set_information('doc', doc)
|
|
if requires is not None:
|
|
self._calc_properties, self._requires = validate_requires_arg(
|
|
requires, self._name)
|
|
else:
|
|
self._calc_properties = frozenset()
|
|
self._requires = []
|
|
if not multi and default_multi is not None:
|
|
raise ValueError(_("a default_multi is set whereas multi is False"
|
|
" in option: {0}").format(name))
|
|
if default_multi is not None:
|
|
try:
|
|
self._validate(default_multi)
|
|
except ValueError as err:
|
|
raise ValueError(_("invalid default_multi value {0} "
|
|
"for option {1}: {2}").format(
|
|
str(default_multi), name, err))
|
|
self._multi = multi
|
|
if self._multi is not False:
|
|
if default is None:
|
|
default = []
|
|
self._default_multi = default_multi
|
|
if callback is not None and ((not multi and (default is not None or
|
|
default_multi is not None))
|
|
or (multi and (default != [] or
|
|
default_multi is not None))
|
|
):
|
|
raise ValueError(_("default value not allowed if option: {0} "
|
|
"is calculated").format(name))
|
|
if properties is None:
|
|
properties = tuple()
|
|
if not isinstance(properties, tuple):
|
|
raise TypeError(_('invalid properties type {0} for {1},'
|
|
' must be a tuple').format(
|
|
type(properties),
|
|
self._name))
|
|
if validator is not None:
|
|
validate_callback(validator, validator_params, 'validator')
|
|
self._validator = validator
|
|
if validator_params is not None:
|
|
self._validator_params = validator_params
|
|
if callback is None and callback_params is not None:
|
|
raise ValueError(_("params defined for a callback function but "
|
|
"no callback defined"
|
|
" yet for option {0}").format(name))
|
|
if callback is not None:
|
|
validate_callback(callback, callback_params, 'callback')
|
|
self._callback = callback
|
|
if callback_params is not None:
|
|
self._callback_params = callback_params
|
|
if self._calc_properties != frozenset([]) and properties is not tuple():
|
|
set_forbidden_properties = self._calc_properties & set(properties)
|
|
if set_forbidden_properties != frozenset():
|
|
raise ValueError('conflict: properties already set in '
|
|
'requirement {0}'.format(
|
|
list(set_forbidden_properties)))
|
|
if multi and default is None:
|
|
self._default = []
|
|
else:
|
|
self._default = default
|
|
self._properties = properties
|
|
self._warnings_only = warnings_only
|
|
ret = super(Base, self).__init__()
|
|
self.impl_validate(self._default)
|
|
return ret
|
|
|
|
|
|
class BaseOption(Base):
|
|
"""This abstract base class stands for attribute access
|
|
in options that have to be set only once, it is of course done in the
|
|
__setattr__ method
|
|
"""
|
|
__slots__ = tuple()
|
|
|
|
# information
|
|
def impl_set_information(self, key, value):
|
|
"""updates the information's attribute
|
|
(which is a dictionary)
|
|
|
|
:param key: information's key (ex: "help", "doc"
|
|
:param value: information's value (ex: "the help string")
|
|
"""
|
|
self._informations[key] = value
|
|
|
|
def impl_get_information(self, key, default=undefined):
|
|
"""retrieves one information's item
|
|
|
|
:param key: the item string (ex: "help")
|
|
"""
|
|
if key in self._informations:
|
|
return self._informations[key]
|
|
elif default is not undefined:
|
|
return default
|
|
else:
|
|
raise ValueError(_("information's item not found: {0}").format(
|
|
key))
|
|
|
|
# ____________________________________________________________
|
|
# serialize object
|
|
def _impl_convert_requires(self, descr, load=False):
|
|
"""export of the requires during the serialization process
|
|
|
|
:type descr: :class:`tiramisu.option.OptionDescription`
|
|
:param load: `True` if we are at the init of the option description
|
|
:type load: bool
|
|
"""
|
|
if not load and self._requires is None:
|
|
self._state_requires = None
|
|
elif load and self._state_requires is None:
|
|
self._requires = None
|
|
del(self._state_requires)
|
|
else:
|
|
if load:
|
|
_requires = self._state_requires
|
|
else:
|
|
_requires = self._requires
|
|
new_value = []
|
|
for requires in _requires:
|
|
new_requires = []
|
|
for require in requires:
|
|
if load:
|
|
new_require = [descr.impl_get_opt_by_path(require[0])]
|
|
else:
|
|
new_require = [descr.impl_get_path_by_opt(require[0])]
|
|
new_require.extend(require[1:])
|
|
new_requires.append(tuple(new_require))
|
|
new_value.append(tuple(new_requires))
|
|
if load:
|
|
del(self._state_requires)
|
|
self._requires = new_value
|
|
else:
|
|
self._state_requires = new_value
|
|
|
|
# serialize
|
|
def _impl_getstate(self, descr):
|
|
"""the under the hood stuff that need to be done
|
|
before the serialization.
|
|
|
|
:param descr: the parent :class:`tiramisu.option.OptionDescription`
|
|
"""
|
|
self._stated = True
|
|
for func in dir(self):
|
|
if func.startswith('_impl_convert_'):
|
|
getattr(self, func)(descr)
|
|
self._state_readonly = self._readonly
|
|
|
|
def __getstate__(self, stated=True):
|
|
"""special method to enable the serialization with pickle
|
|
Usualy, a `__getstate__` method does'nt need any parameter,
|
|
but somme under the hood stuff need to be done before this action
|
|
|
|
:parameter stated: if stated is `True`, the serialization protocol
|
|
can be performed, not ready yet otherwise
|
|
:parameter type: bool
|
|
"""
|
|
try:
|
|
self._stated
|
|
except AttributeError:
|
|
raise SystemError(_('cannot serialize Option, '
|
|
'only in OptionDescription'))
|
|
slots = set()
|
|
for subclass in self.__class__.__mro__:
|
|
if subclass is not object:
|
|
slots.update(subclass.__slots__)
|
|
slots -= frozenset(['_cache_paths', '_cache_consistencies',
|
|
'__weakref__'])
|
|
states = {}
|
|
for slot in slots:
|
|
# remove variable if save variable converted
|
|
# in _state_xxxx variable
|
|
if '_state' + slot not in slots:
|
|
try:
|
|
if slot.startswith('_state'):
|
|
states[slot] = getattr(self, slot)
|
|
# remove _state_xxx variable
|
|
self.__delattr__(slot)
|
|
else:
|
|
states[slot] = getattr(self, slot)
|
|
except AttributeError:
|
|
pass
|
|
if not stated:
|
|
del(states['_stated'])
|
|
return states
|
|
|
|
# unserialize
|
|
def _impl_setstate(self, descr):
|
|
"""the under the hood stuff that need to be done
|
|
before the serialization.
|
|
|
|
:type descr: :class:`tiramisu.option.OptionDescription`
|
|
"""
|
|
for func in dir(self):
|
|
if func.startswith('_impl_convert_'):
|
|
getattr(self, func)(descr, load=True)
|
|
try:
|
|
self._readonly = self._state_readonly
|
|
del(self._state_readonly)
|
|
del(self._stated)
|
|
except AttributeError:
|
|
pass
|
|
|
|
def __setstate__(self, state):
|
|
"""special method that enables us to serialize (pickle)
|
|
|
|
Usualy, a `__setstate__` method does'nt need any parameter,
|
|
but somme under the hood stuff need to be done before this action
|
|
|
|
:parameter state: a dict is passed to the loads, it is the attributes
|
|
of the options object
|
|
:type state: dict
|
|
"""
|
|
for key, value in state.items():
|
|
setattr(self, key, value)
|
|
|
|
def __setattr__(self, name, value):
|
|
"""set once and only once some attributes in the option,
|
|
like `_name`. `_name` cannot be changed one the option and
|
|
pushed in the :class:`tiramisu.option.OptionDescription`.
|
|
|
|
if the attribute `_readonly` is set to `True`, the option is
|
|
"frozen" (which has noting to do with the high level "freeze"
|
|
propertie or "read_only" property)
|
|
"""
|
|
if name not in ('_option', '_is_build_cache') \
|
|
and not isinstance(value, tuple) and \
|
|
not name.startswith('_state'):
|
|
is_readonly = False
|
|
# never change _name
|
|
if name == '_name':
|
|
try:
|
|
if self._name is not None:
|
|
#so _name is already set
|
|
is_readonly = True
|
|
except (KeyError, AttributeError):
|
|
pass
|
|
elif name != '_readonly':
|
|
is_readonly = self.impl_is_readonly()
|
|
if is_readonly:
|
|
raise AttributeError(_("'{0}' ({1}) object attribute '{2}' is"
|
|
" read-only").format(
|
|
self.__class__.__name__,
|
|
self._name,
|
|
name))
|
|
super(BaseOption, self).__setattr__(name, value)
|
|
|
|
def impl_is_readonly(self):
|
|
try:
|
|
if self._readonly is True:
|
|
return True
|
|
except AttributeError:
|
|
pass
|
|
return False
|
|
|
|
def impl_getname(self):
|
|
return self._name
|
|
|
|
|
|
class OnlyOption(BaseOption):
|
|
__slots__ = tuple()
|
|
|
|
|
|
class Option(OnlyOption):
|
|
"""
|
|
Abstract base class for configuration option's.
|
|
|
|
Reminder: an Option object is **not** a container for the value.
|
|
"""
|
|
# __slots__ = ('_multi', '_validator', '_default_multi', '_default',
|
|
# '_state_callback', '_callback',
|
|
# '_consistencies', '_warnings_only', '_master_slaves',
|
|
# '_state_consistencies', '__weakref__')
|
|
__slots__ = tuple()
|
|
_empty = ''
|
|
|
|
def __init__(self, name, doc, default=None, default_multi=None,
|
|
requires=None, multi=False, callback=None,
|
|
callback_params=None, validator=None, validator_params=None,
|
|
properties=None, warnings_only=False):
|
|
"""
|
|
:param name: the option's name
|
|
:param doc: the option's description
|
|
:param default: specifies the default value of the option,
|
|
for a multi : ['bla', 'bla', 'bla']
|
|
:param default_multi: 'bla' (used in case of a reset to default only at
|
|
a given index)
|
|
:param requires: is a list of names of options located anywhere
|
|
in the configuration.
|
|
:param multi: if true, the option's value is a list
|
|
:param callback: the name of a function. If set, the function's output
|
|
is responsible of the option's value
|
|
:param callback_params: the callback's parameter
|
|
:param validator: the name of a function which stands for a custom
|
|
validation of the value
|
|
:param validator_params: the validator's parameters
|
|
:param properties: tuple of default properties
|
|
:param warnings_only: _validator and _consistencies don't raise if True
|
|
Values()._warning contain message
|
|
|
|
"""
|
|
super(Option, self).__init__(name, doc, default, default_multi,
|
|
requires, multi, callback,
|
|
callback_params, validator,
|
|
validator_params, properties,
|
|
warnings_only)
|
|
|
|
def impl_getrequires(self):
|
|
return self._requires
|
|
|
|
def _launch_consistency(self, func, option, value, context, index,
|
|
submulti_index, all_cons_opts, warnings_only):
|
|
"""Launch consistency now
|
|
|
|
:param func: function name, this name should start with _cons_
|
|
:type func: `str`
|
|
:param option: option that value is changing
|
|
:type option: `tiramisu.option.Option`
|
|
:param value: new value of this option
|
|
:param context: Config's context, if None, check default value instead
|
|
:type context: `tiramisu.config.Config`
|
|
:param index: only for multi option, consistency should be launch for
|
|
specified index
|
|
:type index: `int`
|
|
:param all_cons_opts: all options concerne by this consistency
|
|
:type all_cons_opts: `list` of `tiramisu.option.Option`
|
|
:param warnings_only: specific raise error for warning
|
|
:type warnings_only: `boolean`
|
|
"""
|
|
if context is not None:
|
|
descr = context.cfgimpl_get_description()
|
|
|
|
all_cons_vals = []
|
|
for opt in all_cons_opts:
|
|
#get value
|
|
if option == opt:
|
|
opt_value = value
|
|
else:
|
|
#if context, calculate value, otherwise get default value
|
|
if context is not None:
|
|
opt_value = context.getattr(
|
|
descr.impl_get_path_by_opt(opt), validate=False,
|
|
force_permissive=True)
|
|
else:
|
|
opt_value = opt.impl_getdefault()
|
|
|
|
#append value
|
|
if not self.impl_is_multi() or option == opt:
|
|
all_cons_vals.append(opt_value)
|
|
elif self.impl_is_submulti():
|
|
try:
|
|
all_cons_vals.append(opt_value[index][submulti_index])
|
|
except IndexError:
|
|
#value is not already set, could be higher index
|
|
#so return if no value
|
|
return
|
|
else:
|
|
try:
|
|
all_cons_vals.append(opt_value[index])
|
|
except IndexError:
|
|
#value is not already set, could be higher index
|
|
#so return if no value
|
|
return
|
|
getattr(self, func)(all_cons_opts, all_cons_vals, warnings_only)
|
|
|
|
def impl_validate(self, value, context=None, validate=True,
|
|
force_index=None, force_submulti_index=None):
|
|
"""
|
|
:param value: the option's value
|
|
:param context: Config's context
|
|
:type context: :class:`tiramisu.config.Config`
|
|
:param validate: if true enables ``self._validator`` validation
|
|
:type validate: boolean
|
|
:param force_index: if multi, value has to be a list
|
|
not if force_index is not None
|
|
:type force_index: integer
|
|
:param force_submulti_index: if submulti, value has to be a list
|
|
not if force_submulti_index is not None
|
|
:type force_submulti_index: integer
|
|
"""
|
|
if not validate:
|
|
return
|
|
|
|
def val_validator(val):
|
|
if self._validator is not None:
|
|
if self._validator_params is not None:
|
|
validator_params = {}
|
|
for val_param, values in self._validator_params.items():
|
|
validator_params[val_param] = values
|
|
#inject value in calculation
|
|
if '' in validator_params:
|
|
lst = list(validator_params[''])
|
|
lst.insert(0, val)
|
|
validator_params[''] = tuple(lst)
|
|
else:
|
|
validator_params[''] = (val,)
|
|
else:
|
|
validator_params = {'': (val,)}
|
|
# Raise ValueError if not valid
|
|
carry_out_calculation(self, config=context,
|
|
callback=self._validator,
|
|
callback_params=validator_params)
|
|
|
|
def do_validation(_value, _index, submulti_index):
|
|
if _value is None:
|
|
return
|
|
# option validation
|
|
try:
|
|
self._validate(_value, context)
|
|
except ValueError as err:
|
|
log.debug('do_validation: value: {0}, index: {1}, '
|
|
'submulti_index: {2}'.format(_value, _index,
|
|
submulti_index),
|
|
exc_info=True)
|
|
raise ValueError(_('invalid value for option {0}: {1}'
|
|
'').format(self.impl_getname(), err))
|
|
error = None
|
|
warning = None
|
|
try:
|
|
# valid with self._validator
|
|
val_validator(_value)
|
|
# if not context launch consistency validation
|
|
if context is not None:
|
|
descr._valid_consistency(self, _value, context, _index,
|
|
submulti_index)
|
|
self._second_level_validation(_value, self._warnings_only)
|
|
except ValueError as error:
|
|
log.debug(_('do_validation for {0}: error in value').format(
|
|
self.impl_getname()), exc_info=True)
|
|
if self._warnings_only:
|
|
warning = error
|
|
error = None
|
|
except ValueWarning as warning:
|
|
log.debug(_('do_validation for {0}: warning in value').format(
|
|
self.impl_getname()), exc_info=True)
|
|
pass
|
|
if error is None and warning is None:
|
|
try:
|
|
# if context launch consistency validation
|
|
if context is not None:
|
|
descr._valid_consistency(self, _value, context, _index,
|
|
submulti_index)
|
|
except ValueError as error:
|
|
log.debug(_('do_validation for {0}: error in consistency').format(
|
|
self.impl_getname()), exc_info=True)
|
|
pass
|
|
except ValueWarning as warning:
|
|
log.debug(_('do_validation for {0}: warning in consistency').format(
|
|
self.impl_getname()), exc_info=True)
|
|
pass
|
|
if warning:
|
|
msg = _("warning on the value of the option {0}: {1}").format(
|
|
self.impl_getname(), warning)
|
|
warnings.warn_explicit(ValueWarning(msg, self),
|
|
ValueWarning,
|
|
self.__class__.__name__, 0)
|
|
elif error:
|
|
raise ValueError(_("invalid value for option {0}: {1}").format(
|
|
self._name, error))
|
|
|
|
# generic calculation
|
|
if context is not None:
|
|
descr = context.cfgimpl_get_description()
|
|
|
|
if not self.impl_is_multi():
|
|
do_validation(value, None, None)
|
|
elif force_index is not None:
|
|
if self.impl_is_submulti() and force_submulti_index is None:
|
|
if not isinstance(value, list):
|
|
raise ValueError(_("invalid value {0} for option {1} which"
|
|
" must be a list").format(
|
|
value, self.impl_getname()))
|
|
for idx, val in enumerate(value):
|
|
do_validation(val, force_index, idx)
|
|
else:
|
|
do_validation(value, force_index, force_submulti_index)
|
|
else:
|
|
if not isinstance(value, list):
|
|
raise ValueError(_("invalid value {0} for option {1} which "
|
|
"must be a list").format(value,
|
|
self.impl_getname()))
|
|
for idx, val in enumerate(value):
|
|
if self.impl_is_submulti() and force_submulti_index is None:
|
|
if not isinstance(val, list):
|
|
raise ValueError(_("invalid value {0} for option {1} "
|
|
"which must be a list of list"
|
|
"").format(value,
|
|
self.impl_getname()))
|
|
for slave_idx, slave_val in enumerate(val):
|
|
do_validation(slave_val, idx, slave_idx)
|
|
else:
|
|
do_validation(val, idx, force_submulti_index)
|
|
|
|
def impl_getdefault(self):
|
|
"accessing the default value"
|
|
if isinstance(self._default, list):
|
|
return copy(self._default)
|
|
return self._default
|
|
|
|
def impl_getdefault_multi(self):
|
|
"accessing the default value for a multi"
|
|
return self._default_multi
|
|
|
|
def impl_is_master_slaves(self, type_='both'):
|
|
"""FIXME
|
|
"""
|
|
try:
|
|
self._master_slaves
|
|
if type_ in ('both', 'master') and \
|
|
self._master_slaves.is_master(self):
|
|
return True
|
|
if type_ in ('both', 'slave') and \
|
|
not self._master_slaves.is_master(self):
|
|
return True
|
|
except:
|
|
pass
|
|
return False
|
|
|
|
def impl_get_master_slaves(self):
|
|
return self._master_slaves
|
|
|
|
def impl_is_empty_by_default(self):
|
|
"no default value has been set yet"
|
|
if ((not self.impl_is_multi() and self._default is None) or
|
|
(self.impl_is_multi() and (self._default == []
|
|
or None in self._default))):
|
|
return True
|
|
return False
|
|
|
|
def impl_getdoc(self):
|
|
"accesses the Option's doc"
|
|
return self.impl_get_information('doc')
|
|
|
|
def impl_has_callback(self):
|
|
"to know if a callback has been defined or not"
|
|
if self._callback is None:
|
|
return False
|
|
else:
|
|
return True
|
|
|
|
def impl_get_callback(self):
|
|
return self._callback, self._callback_params
|
|
|
|
#def impl_getkey(self, value):
|
|
# return value
|
|
|
|
def impl_is_multi(self):
|
|
return self._multi is True or self._multi is submulti
|
|
|
|
def impl_is_submulti(self):
|
|
return self._multi is submulti
|
|
|
|
def impl_add_consistency(self, func, *other_opts, **params):
|
|
"""Add consistency means that value will be validate with other_opts
|
|
option's values.
|
|
|
|
:param func: function's name
|
|
:type func: `str`
|
|
:param other_opts: options used to validate value
|
|
:type other_opts: `list` of `tiramisu.option.Option`
|
|
:param params: extra params (only warnings_only are allowed)
|
|
"""
|
|
if self.impl_is_readonly():
|
|
raise AttributeError(_("'{0}' ({1}) cannont add consistency, option is"
|
|
" read-only").format(
|
|
self.__class__.__name__,
|
|
self._name))
|
|
warnings_only = params.get('warnings_only', False)
|
|
for opt in other_opts:
|
|
if not isinstance(opt, Option):
|
|
raise ConfigError(_('consistency must be set with an option'))
|
|
if self is opt:
|
|
raise ConfigError(_('cannot add consistency with itself'))
|
|
if self.impl_is_multi() != opt.impl_is_multi():
|
|
raise ConfigError(_('every options in consistency must be '
|
|
'multi or none'))
|
|
func = '_cons_{0}'.format(func)
|
|
all_cons_opts = tuple([self] + list(other_opts))
|
|
value = self.impl_getdefault()
|
|
if value is not None:
|
|
if self.impl_is_multi():
|
|
for idx, val in enumerate(value):
|
|
if not self.impl_is_submulti():
|
|
self._launch_consistency(func, self, val, None, idx,
|
|
None, all_cons_opts,
|
|
warnings_only)
|
|
else:
|
|
for slave_idx, val in enumerate(value):
|
|
self._launch_consistency(func, self, val, None,
|
|
idx, slave_idx,
|
|
all_cons_opts,
|
|
warnings_only)
|
|
else:
|
|
self._launch_consistency(func, self, value, None, None,
|
|
None, all_cons_opts, warnings_only)
|
|
self._add_consistency(func, all_cons_opts, params)
|
|
self.impl_validate(self.impl_getdefault())
|
|
|
|
def _cons_not_equal(self, opts, vals, warnings_only):
|
|
for idx_inf, val_inf in enumerate(vals):
|
|
for idx_sup, val_sup in enumerate(vals[idx_inf + 1:]):
|
|
if val_inf == val_sup is not None:
|
|
if warnings_only:
|
|
msg = _("same value for {0} and {1}, should be different")
|
|
else:
|
|
msg = _("same value for {0} and {1}, must be different")
|
|
raise ValueError(msg.format(opts[idx_inf].impl_getname(),
|
|
opts[idx_inf + idx_sup + 1].impl_getname()))
|
|
|
|
def _impl_convert_callbacks(self, descr, load=False):
|
|
if not load and self._callback is None:
|
|
self._state_callback = None
|
|
self._state_callback_params = None
|
|
elif load and self._state_callback is None:
|
|
self._callback = None
|
|
self._callback_params = None
|
|
del(self._state_callback)
|
|
del(self._state_callback_params)
|
|
else:
|
|
if load:
|
|
callback = self._state_callback
|
|
callback_params = self._state_callback_params
|
|
else:
|
|
callback = self._callback
|
|
callback_params = self._callback_params
|
|
self._state_callback_params = None
|
|
if callback_params is not None:
|
|
cllbck_prms = {}
|
|
for key, values in callback_params.items():
|
|
vls = []
|
|
for value in values:
|
|
if isinstance(value, tuple):
|
|
if load:
|
|
value = (descr.impl_get_opt_by_path(value[0]),
|
|
value[1])
|
|
else:
|
|
value = (descr.impl_get_path_by_opt(value[0]),
|
|
value[1])
|
|
vls.append(value)
|
|
cllbck_prms[key] = tuple(vls)
|
|
else:
|
|
cllbck_prms = None
|
|
|
|
if load:
|
|
del(self._state_callback)
|
|
del(self._state_callback_params)
|
|
self._callback = callback
|
|
self._callback_params = cllbck_prms
|
|
else:
|
|
self._state_callback = callback
|
|
self._state_callback_params = cllbck_prms
|
|
|
|
# serialize/unserialize
|
|
def _impl_convert_consistencies(self, descr, load=False):
|
|
"""during serialization process, many things have to be done.
|
|
one of them is the localisation of the options.
|
|
The paths are set once for all.
|
|
|
|
:type descr: :class:`tiramisu.option.OptionDescription`
|
|
:param load: `True` if we are at the init of the option description
|
|
:type load: bool
|
|
"""
|
|
if not load and self._consistencies is None:
|
|
self._state_consistencies = None
|
|
elif load and self._state_consistencies is None:
|
|
self._consistencies = None
|
|
del(self._state_consistencies)
|
|
else:
|
|
if load:
|
|
consistencies = self._state_consistencies
|
|
else:
|
|
consistencies = self._consistencies
|
|
new_value = []
|
|
for consistency in consistencies:
|
|
values = []
|
|
for obj in consistency[1]:
|
|
if load:
|
|
values.append(descr.impl_get_opt_by_path(obj))
|
|
else:
|
|
values.append(descr.impl_get_path_by_opt(obj))
|
|
new_value.append((consistency[0], tuple(values), consistency[2]))
|
|
if load:
|
|
del(self._state_consistencies)
|
|
self._consistencies = new_value
|
|
else:
|
|
self._state_consistencies = new_value
|
|
|
|
def _second_level_validation(self, value, warnings_only):
|
|
pass
|
|
|
|
|
|
def validate_requires_arg(requires, name):
|
|
"""check malformed requirements
|
|
and tranform dict to internal tuple
|
|
|
|
:param requires: have a look at the
|
|
:meth:`tiramisu.setting.Settings.apply_requires` method to
|
|
know more about
|
|
the description of the requires dictionary
|
|
"""
|
|
if requires is None:
|
|
return None, None
|
|
ret_requires = {}
|
|
config_action = {}
|
|
|
|
# start parsing all requires given by user (has dict)
|
|
# transforme it to a tuple
|
|
for require in requires:
|
|
if not type(require) == dict:
|
|
raise ValueError(_("malformed requirements type for option:"
|
|
" {0}, must be a dict").format(name))
|
|
valid_keys = ('option', 'expected', 'action', 'inverse', 'transitive',
|
|
'same_action')
|
|
unknown_keys = frozenset(require.keys()) - frozenset(valid_keys)
|
|
if unknown_keys != frozenset():
|
|
raise ValueError('malformed requirements for option: {0}'
|
|
' unknown keys {1}, must only '
|
|
'{2}'.format(name,
|
|
unknown_keys,
|
|
valid_keys))
|
|
# prepare all attributes
|
|
try:
|
|
option = require['option']
|
|
expected = require['expected']
|
|
action = require['action']
|
|
except KeyError:
|
|
raise ValueError(_("malformed requirements for option: {0}"
|
|
" require must have option, expected and"
|
|
" action keys").format(name))
|
|
if action == 'force_store_value':
|
|
raise ValueError(_("malformed requirements for option: {0}"
|
|
" action cannot be force_store_value"
|
|
).format(name))
|
|
inverse = require.get('inverse', False)
|
|
if inverse not in [True, False]:
|
|
raise ValueError(_('malformed requirements for option: {0}'
|
|
' inverse must be boolean'))
|
|
transitive = require.get('transitive', True)
|
|
if transitive not in [True, False]:
|
|
raise ValueError(_('malformed requirements for option: {0}'
|
|
' transitive must be boolean'))
|
|
same_action = require.get('same_action', True)
|
|
if same_action not in [True, False]:
|
|
raise ValueError(_('malformed requirements for option: {0}'
|
|
' same_action must be boolean'))
|
|
|
|
if not isinstance(option, Option):
|
|
raise ValueError(_('malformed requirements '
|
|
'must be an option in option {0}').format(name))
|
|
if option.impl_is_multi():
|
|
raise ValueError(_('malformed requirements option {0} '
|
|
'must not be a multi for {1}').format(
|
|
option.impl_getname(), name))
|
|
if expected is not None:
|
|
try:
|
|
option._validate(expected)
|
|
except ValueError as err:
|
|
raise ValueError(_('malformed requirements second argument '
|
|
'must be valid for option {0}'
|
|
': {1}').format(name, err))
|
|
if action in config_action:
|
|
if inverse != config_action[action]:
|
|
raise ValueError(_("inconsistency in action types"
|
|
" for option: {0}"
|
|
" action: {1}").format(name, action))
|
|
else:
|
|
config_action[action] = inverse
|
|
if action not in ret_requires:
|
|
ret_requires[action] = {}
|
|
if option not in ret_requires[action]:
|
|
ret_requires[action][option] = (option, [expected], action,
|
|
inverse, transitive, same_action)
|
|
else:
|
|
ret_requires[action][option][1].append(expected)
|
|
# transform dict to tuple
|
|
ret = []
|
|
for opt_requires in ret_requires.values():
|
|
ret_action = []
|
|
for require in opt_requires.values():
|
|
ret_action.append((require[0], tuple(require[1]), require[2],
|
|
require[3], require[4], require[5]))
|
|
ret.append(tuple(ret_action))
|
|
return frozenset(config_action.keys()), tuple(ret)
|
|
|
|
|
|
class SymLinkOption(OnlyOption):
|
|
#FIXME : et avec sqlalchemy ca marche vraiment ?
|
|
__slots__ = ('_opt', '_state_opt')
|
|
#not return _opt consistencies
|
|
#_consistencies = None
|
|
|
|
def __init__(self, name, opt):
|
|
self._name = name
|
|
if not isinstance(opt, Option):
|
|
raise ValueError(_('malformed symlinkoption '
|
|
'must be an option '
|
|
'for symlink {0}').format(name))
|
|
self._opt = opt
|
|
self._readonly = True
|
|
return super(Base, self).__init__()
|
|
|
|
def __getattr__(self, name):
|
|
if name in ('_opt', '_opt_type', '_readonly', 'impl_getname'):
|
|
return object.__getattr__(self, name)
|
|
else:
|
|
return getattr(self._opt, name)
|
|
|
|
def _impl_getstate(self, descr):
|
|
super(SymLinkOption, self)._impl_getstate(descr)
|
|
self._state_opt = descr.impl_get_path_by_opt(self._opt)
|
|
|
|
def _impl_setstate(self, descr):
|
|
self._opt = descr.impl_get_opt_by_path(self._state_opt)
|
|
del(self._state_opt)
|
|
super(SymLinkOption, self)._impl_setstate(descr)
|
|
|
|
def impl_get_information(self, key, default=undefined):
|
|
return self._opt.impl_get_information(key, default)
|