This commit is contained in:
2017-07-21 18:03:34 +02:00
parent be43c95ec0
commit ddaadb0701
19 changed files with 297 additions and 154 deletions

View File

@ -35,7 +35,7 @@ from .value import Values, Multi
from .i18n import _
if sys.version_info[0] >= 3: # pragma: optional cover
if sys.version_info[0] >= 3: # pragma: no cover
xrange = range
@ -482,7 +482,7 @@ class SubConfig(object):
# 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 \
only_first = first is True and byvalue is undefined and \
check_properties is None
if only_path is not undefined:
options = [(only_path, only_option)]
@ -752,7 +752,7 @@ class _CommonConfig(SubConfig):
self._impl_context = weakref.ref(self)
self._impl_settings.context = weakref.ref(self)
self._impl_values.context = weakref.ref(self)
storage = get_storage('config', test=self._impl_test, **state['_storage'])
storage = get_storage(test=self._impl_test, **state['_storage'])
self._impl_values._impl_setstate(storage)
self._impl_settings._impl_setstate(storage)
self._impl_meta = None
@ -836,8 +836,6 @@ class GroupConfig(_CommonConfig):
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):
@ -923,16 +921,16 @@ class GroupConfig(_CommonConfig):
else:
return GroupConfig(self._find_return_results(ret, raise_if_not_found))
def __repr__(self):
return object.__repr__(self)
def __str__(self):
ret = ''
for child in self._impl_children:
ret += '({0})\n'.format(child._impl_name)
ret += super(GroupConfig, self).__str__()
if self._impl_descr is not None:
ret += super(GroupConfig, self).__str__()
return ret
__repr__ = __str__
def getattr(self, name, force_permissive=False, validate=True,
_setting_properties=undefined, _self_properties=undefined, index=None,
returns_raise=False):
@ -951,14 +949,14 @@ class MetaConfig(GroupConfig):
__slots__ = tuple()
def __init__(self, children, session_id=None, persistent=False,
optiondescription=None):
optiondescription=None, _force_store_values=True):
descr = None
if optiondescription is not None:
new_children = []
for child_session_id in children:
#FIXME _force_store_values doit etre a true si inexistant !
new_children.append(Config(optiondescription, persistent=True,
session_id=child_session_id, _force_store_values=False))
new_children.append(Config(optiondescription, persistent=persistent,
session_id=child_session_id, _force_store_values=_force_store_values))
children = new_children
for child in children:
if not isinstance(child, _CommonConfig):
@ -1004,12 +1002,10 @@ class MetaConfig(GroupConfig):
else:
child_value = child.getattr(path)
if force_default or value == child_value:
childret = child.cfgimpl_get_values().reset(opt, path=path,
validate=False,
_setting_properties=setting_properties,
_commit=False)
if childret is not None:
ret.append(childret)
child.cfgimpl_get_values().reset(opt, path=path,
validate=False,
_setting_properties=setting_properties,
_commit=False)
continue
if force_dont_change_value:
child_value = child.getattr(path, _setting_properties=setting_properties,
@ -1018,7 +1014,7 @@ class MetaConfig(GroupConfig):
ret.append(child_value)
elif value != child_value:
childret = child.setattr(path, child_value, _commit=False, not_raises=True)
if childret is not None:
if childret is not None: # pragma: no cover
ret.append(childret)
setret = self.setattr(path, value, _commit=_commit, not_raises=True)
@ -1038,6 +1034,13 @@ class MetaConfig(GroupConfig):
validate=False,
_setting_properties=setting_properties)
def new_config(self, session_id=None, persistent=False):
return Config(self._impl_descr, session_id=session_id,
persistent=persistent)
def new_config(self, session_id, persistent=False):
config = Config(self._impl_descr, session_id=session_id,
persistent=persistent)
if config._impl_name in [child._impl_name for child in self._impl_children]: # pragma: no cover
raise ConflictError(_('config name must be uniq in '
'groupconfig for {0}').format(config._impl_name))
config._impl_meta = weakref.ref(self)
self._impl_children.append(config)
return config

View File

@ -554,7 +554,7 @@ class Option(OnlyOption):
return opt_value
else:
opt_value = None
else:
else: # pragma: no cover
return opt_value
elif index is None:
opt_value = opt.impl_getdefault()
@ -719,7 +719,7 @@ class Option(OnlyOption):
' must be a list').format(
value, self.impl_get_display_name()))
for idx, val in enumerate(value):
if isinstance(val, list):
if isinstance(val, list): # pragma: no cover
return ValueError(_('invalid value "{}" for "{}" '
'which must not be a list').format(val,
self.impl_get_display_name()))

View File

@ -36,7 +36,7 @@ StorageOptionDescription = get_storages_option('optiondescription')
name_regexp = re.compile(r'^[a-zA-Z\d\-_]*$')
import sys
if sys.version_info[0] >= 3: # pragma: optional cover
if sys.version_info[0] >= 3: # pragma: no cover
xrange = range
del(sys)
@ -141,18 +141,18 @@ class OptionDescription(BaseOption, StorageOptionDescription):
if func not in allowed_const_list and is_multi:
is_masterslaves = option.impl_is_master_slaves()
if not is_masterslaves:
raise ValueError(_('malformed consistency option "{0}" '
raise ConfigError(_('malformed consistency option "{0}" '
'must be a master/slaves').format(
option.impl_getname()))
masterslaves = option.impl_get_master_slaves()
for opt in all_cons_opts:
if func not in allowed_const_list and is_multi:
if not opt.impl_is_master_slaves():
raise ValueError(_('malformed consistency option "{0}" '
raise ConfigError(_('malformed consistency option "{0}" '
'must not be a multi for "{1}"').format(
option.impl_getname(), opt.impl_getname()))
elif masterslaves != opt.impl_get_master_slaves():
raise ValueError(_('malformed consistency option "{0}" '
raise ConfigError(_('malformed consistency option "{0}" '
'must be in same master/slaves for "{1}"').format(
option.impl_getname(), opt.impl_getname()))
_consistencies.setdefault(opt,
@ -318,8 +318,6 @@ class OptionDescription(BaseOption, StorageOptionDescription):
values = carry_out_calculation(self, context=context,
callback=callback,
callback_params=callback_params)
if isinstance(values, Exception):
raise values
if len(values) > len(set(values)):
raise ConfigError(_('DynOptionDescription callback return not unique value'))
for val in values:
@ -327,16 +325,14 @@ class OptionDescription(BaseOption, StorageOptionDescription):
raise ValueError(_("invalid suffix: {0} for option").format(val))
return values
def _impl_search_dynchild(self, name=undefined, context=undefined):
def _impl_search_dynchild(self, name, context):
ret = []
for child in self._impl_st_getchildren(context, only_dyn=True):
cname = child.impl_getname()
if name is undefined or name.startswith(cname):
if name.startswith(cname):
path = cname
for value in child._impl_get_suffixes(context):
if name is undefined:
ret.append(SynDynOptionDescription(child, cname + value, path + value, value))
elif name == cname + value:
if name == cname + value:
return SynDynOptionDescription(child, name, path + value, value)
return ret
@ -388,9 +384,6 @@ class DynOptionDescription(OptionDescription):
if isinstance(child, SymLinkOption):
raise ConfigError(_('cannot set symlinkoption in a '
'dynoptiondescription'))
if isinstance(child, SymLinkOption):
raise ConfigError(_('cannot set symlinkoption in a '
'dynoptiondescription'))
child._impl_setsubdyn(self)
self.impl_set_callback(callback, callback_params)

View File

@ -732,7 +732,7 @@ class Settings(object):
# transitive action, force expected
value = expected[0]
inverse = False
else:
else: # pragma: no cover
raise value
else:
orig_value = value

View File

@ -49,7 +49,7 @@ class StorageType(object):
mod = None
def set(self, name): # pragma: optional cover
if self.storage_type is not None:
if self.storage_type is not None: # pragma: no cover
if self.storage_type == name:
return
raise ConfigError(_('storage_type is already set, cannot rebind it'))
@ -65,7 +65,7 @@ class StorageType(object):
modulepath = '{0}.storage.{1}'.format(MODULE_PATH, self.storage_type)
try:
mod = __import__(modulepath)
except ImportError:
except ImportError: # pragma: no cover
raise SystemError(_('cannot import the storage {0}').format(
self.default_storage))
for token in modulepath.split(".")[1:]:
@ -81,7 +81,7 @@ default_validation = StorageType()
default_validation.set(DEFAULT_STORAGE)
def set_storage(type_, name, **kwargs): # pragma: optional cover
def set_storage(type_, name): # pragma: optional cover
"""Change storage's configuration
:params name: is the storage name. If storage is already set, cannot
@ -89,19 +89,8 @@ def set_storage(type_, name, **kwargs): # pragma: optional cover
Other attributes are differents according to the selected storage's name
"""
if type_ == 'option':
storage_option_type.set(name)
setting = storage_option_type.get().setting
else:
storage_type.set(name)
setting = storage_type.get().setting
for option, value in kwargs.items():
try:
getattr(setting, option)
setattr(setting, option, value)
except AttributeError:
raise ValueError(_('option {0} not already exists in storage {1}'
'').format(option, name))
storage_type.set(name)
setting = storage_type.get().setting
def _impl_getstate_setting():
@ -113,16 +102,10 @@ def _impl_getstate_setting():
return state
def get_storage(type_, session_id, persistent, test): # pragma: optional cover
def get_storage(session_id, persistent, test): # pragma: optional cover
"""all used when __setstate__ a Config
"""
#FIXME ca sert ???
if type_ == 'option':
return storage_option_type.get().Storage(session_id, persistent, test)
elif type_ == 'config':
return storage_type.get().Storage(session_id, persistent, test)
else:
return default_validation.get().Storage(session_id, persistent, test)
return storage_type.get().Storage(session_id, persistent, test)
def get_storages(context, session_id, persistent):

View File

@ -402,12 +402,6 @@ class StorageOptionDescription(StorageBase):
__slots__ = ('_children', '_cache_paths', '_cache_consistencies',
'_group_type', '_state_group_type', '_cache_force_store_values')
def __init__(self, name, multi, warnings_only, doc, extra):
super(StorageOptionDescription, self).__init__(name, multi,
warnings_only, doc,
None, undefined,
undefined, undefined)
def _add_children(self, child_names, children):
_setattr = object.__setattr__
_setattr(self, '_children', (tuple(child_names), tuple(children)))
@ -550,7 +544,7 @@ class StorageOptionDescription(StorageBase):
if _filter(path, option) is False:
continue
if only_first:
return find_results[0]
return find_results
return find_results
def _impl_st_getchildren(self, context, only_dyn=False):

View File

@ -36,9 +36,6 @@ class Properties(Cache):
def getproperties(self, path, default_properties):
return self._properties.get(path, set(default_properties))
def hasproperties(self, path):
return path in self._properties
def reset_all_properties(self):
self._properties.clear()

View File

@ -15,7 +15,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ____________________________________________________________
from ...i18n import _
from ...error import ConfigError
from ...error import ConfigError, ConflictError
from ..util import SerializeObject
@ -45,7 +45,7 @@ class Storage(object):
def __init__(self, session_id, persistent, test=False):
if not test and session_id in _list_sessions: # pragma: optional cover
raise ValueError(_('session already used'))
raise ConflictError(_('session already used'))
if persistent: # pragma: optional cover
raise ValueError(_('a dictionary cannot be persistent'))
self.session_id = session_id

View File

@ -85,12 +85,6 @@ class Values(Cache):
self._setvalue_info(3, idx, owner, values, index, vidx)
self._values = tuple(values)
def getvalue(self, path, session, index=None):
"""get value for a path
return: only value, not the owner
"""
return self._getvalue(path, 2, index)
def hasvalue(self, path, index=None):
"""if path has a value
return: boolean

View File

@ -49,12 +49,6 @@ class Properties(Sqlite3DB):
else:
return set(self._sqlite_decode(value[0]))
def hasproperties(self, path):
path = self._sqlite_encode_path(path)
return self._storage.select("SELECT properties FROM property WHERE "
"path = ? AND session_id = ? LIMIT 1", (path, self._session_id)
) is not None
def reset_all_properties(self):
self._storage.execute("DELETE FROM property WHERE session_id = ?", (self._session_id,))

View File

@ -72,16 +72,6 @@ class Values(Sqlite3DB):
self._session_id),
commit=commit)
def getvalue(self, path, session, index=None):
"""get value for an option
return: only value, not the owner
"""
path = self._sqlite_encode_path(path)
values = self._sqlite_select(path, index)
if values is None:
return values
return self._sqlite_decode(values[0])
def hasvalue(self, path, index=None):
"""if opt has a value
return: boolean

View File

@ -73,21 +73,13 @@ class Values(object):
raise value
else:
if isinstance(value, Multi):
if index is not None:
value = value[index]
if isinstance(value, SubMulti):
if submulti_index is not undefined:
value = value[submulti_index]
else:
value = list(value)
else:
new_value = []
for val in value:
if isinstance(val, SubMulti):
val = list(val)
new_value.append(val)
value = new_value
del new_value
new_value = []
for val in value:
if isinstance(val, SubMulti):
val = list(val)
new_value.append(val)
value = new_value
del new_value
return value
# if value has callback and is not set
if opt.impl_has_callback():
@ -230,12 +222,6 @@ class Values(object):
"enables us to use the pythonic dictionary-like access to values"
return self._get_cached_value(opt)
def getitem(self, opt, validate=True, force_permissive=False):
"""
"""
return self._get_cached_value(opt, validate=validate,
force_permissive=force_permissive)
def _get_cached_value(self, opt, path=None, validate=True,
force_permissive=False, trusted_cached_properties=True,
validate_properties=True,
@ -411,8 +397,6 @@ class Values(object):
# user didn't change value, so not write
# valid opt
context = self._getcontext()
if _setting_properties is undefined:
_setting_properties = context.cfgimpl_get_settings()._getproperties(read_write=False)
if 'validator' in _setting_properties:
session = context.cfgimpl_get_values()._p_.getsession()
if opt._has_consistencies():
@ -476,12 +460,8 @@ class Values(object):
if valid_masterslave and opt.impl_is_master_slaves():
if session is None:
session = self._p_.getsession()
if index is not None:
len_value = index
setitem = False
else:
len_value = len(value)
setitem = True
len_value = len(value)
setitem = True
val = opt.impl_get_master_slaves().validate(self, opt, len_value, path, session, setitem=setitem)
if isinstance(val, Exception):
return val
@ -502,8 +482,6 @@ class Values(object):
context = self._getcontext()
setting = context.cfgimpl_get_settings()
self_properties = setting._getproperties(opt, path, read_write=False)
if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
return False
if self._p_.getowner(path, owners.default, session, only_default=True) is not owners.default:
return False
if context.cfgimpl_get_meta() is not None:
@ -834,8 +812,6 @@ class Multi(list):
session = context.cfgimpl_get_values()._p_.getsession()
fake_context = context._gen_fake_values(session)
fake_multi = Multi(list(self), weakref.ref(fake_context), self.opt, self.path)
if isinstance(fake_multi, Exception):
raise fake_multi
fake_multi.append(value, validate=False, force=True,
setitem=setitem)
self._validate(value, fake_context, index, True)