first version of new api

This commit is contained in:
2017-10-22 09:48:08 +02:00
parent 8e91f94379
commit 22a4aa81dc
12 changed files with 1250 additions and 35 deletions

View File

@ -12,3 +12,15 @@
#
# 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/>.
from .config import Config
from .option import *
from .error import APIError
from .api import getapi
from .option import __all__ as all_options
allfuncs = ['Config', 'getapi', 'APIError']
allfuncs.extend(all_options)
del(all_options)
__all__ = tuple(allfuncs)
del(allfuncs)

342
tiramisu/api.py Normal file
View File

@ -0,0 +1,342 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2017 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/>.
# ____________________________________________________________
from inspect import ismethod, getdoc
from .error import APIError
from .i18n import _
from .setting import owners, undefined
def getter(func):
def wrapper(self, path, *args, **kwargs):
opt = self._get_obj_by_path(path)
if opt.impl_is_master_slaves('slave'):
get = self._slave_get
else:
get = self._simple_get
return get(path, *args, **kwargs)
return wrapper
def setter(func):
def wrapper(self, path, *args, **kwargs):
opt = self._get_obj_by_path(path)
if opt.impl_is_master_slaves('slave'):
return self._slave_set(path, *args, **kwargs)
elif opt.impl_is_master_slaves('master'):
return self._master_set(path, *args, **kwargs)
else:
return self._simple_set(path, *args, **kwargs)
return wrapper
def resetter(func):
def wrapper(self, path, *args, **kwargs):
opt = self._get_obj_by_path(path)
if opt.impl_is_master_slaves('slave'):
reset = self._slave_reset
else:
reset = self._simple_reset
return reset(path, *args, **kwargs)
return wrapper
class CommonTiramisu(object):
icon = '\u2937'
tmpl_help = u' {} {}: {}'
def _get_obj_by_path(self, path, index=None):
return self.config.unwrap_from_path(path,
force_permissive=self.force_permissive,
index=index)
def __getattr__(self, name):
if name == 'help':
return self._help()
else:
if not hasattr(CommonTiramisu, name):
raise APIError(_('unknown method {}').format(name))
else:
super(CommonTiramisu).__getattribute__(name)
def _help(self):
txt = []
for func_name in dir(self):
if not func_name.startswith('_'):
func = getattr(self, func_name)
if ismethod(func):
txt.append(self.tmpl_help.format(self.icon, func_name, getdoc(func)))
return '\n'.join(txt)
class TiramisuAPIOption(CommonTiramisu):
"""get information from an option"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
if config:
self.values = self.config.cfgimpl_get_values()
def ismulti(self, path):
"""test if option could have multi value"""
opt = self._get_obj_by_path(path)
return opt.impl_is_multi()
def ismasterslaves(self, path):
"""test if option is a master or a slave"""
opt = self._get_obj_by_path(path)
return opt.impl_is_master_slaves()
def ismaster(self, path):
"""test if option is a master"""
opt = self._get_obj_by_path(path)
return opt.impl_is_master_slaves('master')
def isslave(self, path):
"""test if option is a slave"""
opt = self._get_obj_by_path(path)
return opt.impl_is_master_slaves('slave')
class TiramisuAPIOwner(CommonTiramisu):
"""manager option's owner"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
if config:
self.values = self.config.cfgimpl_get_values()
@getter
def get(self):
"""get owner for a specified option"""
pass
def _simple_get(self, path):
##FIXME should not be here, just for check property
#self.config.getattr(path,
# force_permissive=self.force_permissive)
# FIXME doublons aussi
opt = self._get_obj_by_path(path)
return self.values.getowner(opt,
force_permissive=self.force_permissive)
def _slave_get(self, path, index):
##FIXME should not be here, just for check property
#self.config.getattr(path,
# index=index,
# force_permissive=self.force_permissive)
# FIXME doublons aussi
opt = self._get_obj_by_path(path,
index=index)
return self.values.getowner(opt,
index=index,
force_permissive=self.force_permissive)
def isdefault(self, path):
"""is option has defaut value"""
#FIXME isdefault for slave should have index!
opt = self._get_obj_by_path(path)
#FIXME should not be here, just for check property
self.config.getattr(path,
force_permissive=self.force_permissive)
return self.values.is_default_owner(opt,
force_permissive=self.force_permissive)
@setter
def set(self):
"""get owner for a specified option"""
pass
def _simple_set(self, path, owner):
#FIXME doublons, opt est deja dans le setter
opt = self._get_obj_by_path(path)
try:
obj_owner = getattr(owners, owner)
except AttributeError:
owners.addowner(owner)
obj_owner = getattr(owners, owner)
self.values.setowner(opt,
obj_owner,
force_permissive=self.force_permissive)
def _master_set(self, path, owner):
return self._simple_set(path, owner)
def _slave_set(self, path, index, owner):
#FIXME doublons, opt est deja dans le setter
opt = self._get_obj_by_path(path, index)
try:
obj_owner = getattr(owners, owner)
except AttributeError:
owners.addowner(owner)
obj_owner = getattr(owners, owner)
self.values.setowner(opt,
obj_owner,
index,
force_permissive=self.force_permissive)
class TiramisuAPIProperty(CommonTiramisu):
"""manager option's property"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
if config:
self.settings = config.cfgimpl_get_settings()
@getter
def get(self, path):
"""get property for a specified option"""
def _simple_get(self, path):
opt = self._get_obj_by_path(path)
return self.settings.getproperties(opt, path, obj=False)
def _slave_get(self, path, index):
opt = self._get_obj_by_path(path)
return self.settings.getproperties(opt, path, index=index, obj=False)
def set(self, path, properties):
"""set properties for a specified option"""
opt = self._get_obj_by_path(path)
self.settings.setproperties(set(properties),
opt,
path)
def reset(self, path):
"""reset all personalised properties
"""
self._get_obj_by_path(path)
self.settings.reset(_path=path)
class TiramisuAPIValue(CommonTiramisu):
"""manager option's value"""
def __init__(self, config, force_permissive):
self.config = config
self.force_permissive = force_permissive
def append(self, path, value=undefined):
opt = self._get_obj_by_path(path)
if not opt.impl_is_master_slaves('master'):
raise APIError('append is only allowed for a master')
multi = self.config.getattr(path,
force_permissive=self.force_permissive)
multi.append(value, force_permissive=self.force_permissive)
@getter
def get(self):
"""get value for a specified option"""
pass
def _simple_get(self, path):
return self.config.getattr(path,
force_permissive=self.force_permissive)
def _slave_get(self, path, index):
return self.config.getattr(path,
index=index,
force_permissive=self.force_permissive)
@setter
def set(self):
"""set a value for a specified option"""
pass
def _simple_set(self, path, value):
self.config.setattr(path,
value,
force_permissive=self.force_permissive)
def _master_set(self, path, index, value):
multi = self.config.getattr(path,
force_permissive=self.force_permissive)
multi[index] = value
def _slave_set(self, path, index, value):
self.config.setattr(path,
value,
index=index,
force_permissive=self.force_permissive)
@resetter
def reset(self, path):
"""reset value for a value"""
pass
def _simple_reset(self, path):
opt = self._get_obj_by_path(path)
self.config.cfgimpl_get_values().reset(opt,
path=path,
force_permissive=self.force_permissive)
def _slave_reset(self, path, index):
#self._get_obj_by_path(path)
multi = self.config.getattr(path,
force_permissive=self.force_permissive)
del(multi[index])
class TiramisuAPI(object):
icon = '\u2937'
tmpl_help = ' {} {}: {}'
def __init__(self, config, force_permissive=False):
self.config = config
self.force_permissive = force_permissive
#FIXME ?
self.config.read_write()
self.config.cfgimpl_get_settings().setpermissive(('hidden',))
#/FIXME ?
self.registers = {}
self.prefix = self.__class__.__name__
for module_name in globals().keys():
if module_name != self.prefix and module_name.startswith(self.prefix):
module = globals()[module_name]
func_name = module_name[11:].lower()
self.registers[func_name] = module
def __getattr__(self, subfunc):
if subfunc in self.registers:
return self.registers[subfunc](self.config,
self.force_permissive)
elif subfunc == 'permissive':
return TiramisuAPI(self.config, force_permissive=True)
elif subfunc == 'help':
return self._help()
else:
raise APIError(_('please specify a valid sub function'))
def _help(self):
txt = ['[permissive]']
for module_name, module in self.registers.items():
module_doc = getdoc(module)
txt.append(self.tmpl_help.format(self.icon, module_name, module_doc))
txt.append(module(None, None).help)
return '\n'.join(txt)
def getapi(config):
"""instanciate TiramisuAPI
:param config: Config object
:type descr: an instance of ``config.Config``
"""
return TiramisuAPI(config)

View File

@ -382,7 +382,7 @@ class SubConfig(object):
def getattr(self, name, force_permissive=False, validate=True,
_setting_properties=undefined, _self_properties=undefined, index=None,
returns_raise=False):
returns_raise=False, returns_option=False):
"""
attribute notation mechanism for accessing the value of an option
:param name: attribute name
@ -457,7 +457,10 @@ class SubConfig(object):
index=index)
if not returns_raise and isinstance(cfg, Exception):
raise cfg
return cfg
if returns_option is True:
return option
else:
return cfg
def find(self, bytype=None, byname=None, byvalue=undefined, type_='option',
check_properties=True, force_permissive=False):
@ -724,7 +727,7 @@ class _CommonConfig(SubConfig):
return self.cfgimpl_get_values().getowner(opt, index=index,
force_permissive=force_permissive)
def unwrap_from_path(self, path, force_permissive=False):
def unwrap_from_path(self, path, force_permissive=False, index=None):
"""convenience method to extract and Option() object from the Config()
and it is **fast**: finds the option directly in the appropriate
namespace
@ -733,10 +736,9 @@ class _CommonConfig(SubConfig):
"""
context = self._cfgimpl_get_context()
if '.' in path:
homeconfig, path = self.cfgimpl_get_home_by_path(
path, force_permissive=force_permissive)
return homeconfig.cfgimpl_get_description().__getattr__(path, context=context)
return self.cfgimpl_get_description().__getattr__(path, context=context)
self, path = self.cfgimpl_get_home_by_path(path,
force_permissive=force_permissive)
return self.getattr(path, force_permissive=force_permissive, index=index, returns_option=True)
def cfgimpl_get_path(self, dyn=True):
return None

View File

@ -161,3 +161,7 @@ class ValueWarning(UserWarning): # pragma: optional cover
def __init__(self, msg, opt):
self.opt = opt
super(ValueWarning, self).__init__(msg)
class APIError(Exception):
pass

View File

@ -58,7 +58,7 @@ class Option(OnlyOption):
'_choice_values_params',
)
_empty = ''
def __init__(self, name, doc, default=None, default_multi=None,
def __init__(self, name, doc, default=undefined, default_multi=None,
requires=None, multi=False, unique=undefined, callback=None,
callback_params=None, validator=None, validator_params=None,
properties=None, warnings_only=False, extra=None,
@ -68,6 +68,11 @@ class Option(OnlyOption):
if not multi and default_multi is not None:
raise ValueError(_("default_multi is set whereas multi is False"
" in option: {0}").format(name))
if default is undefined:
if multi is False:
default = None
else:
default = []
if multi is True:
is_multi = True
_multi = 0

View File

@ -644,10 +644,10 @@ class MasterSlaves(OptionDescription):
c_opt = opt
return c_opt in self._children[1]
def reset(self, opt, values, setting_properties, _commit=True):
def reset(self, opt, values, setting_properties, _commit=True, force_permissive=False):
for slave in self.getslaves(opt):
values.reset(slave, validate=False, _setting_properties=setting_properties,
_commit=_commit)
_commit=_commit, force_permissive=force_permissive)
def pop(self, opt, values, index):
for slave in self.getslaves(opt):

View File

@ -270,7 +270,7 @@ class Property(object):
raise ConfigError(_('cannot add those properties: {0}').format(propname))
self._properties.add(propname)
if save:
self._setting._setproperties(self._properties, self._opt, self._path, force=True)
self._setting.setproperties(self._properties, self._opt, self._path, force=True)
def remove(self, propname):
"""Removes a property named propname
@ -280,7 +280,7 @@ class Property(object):
"""
if propname in self._properties:
self._properties.remove(propname)
self._setting._setproperties(self._properties, self._opt, self._path)
self._setting.setproperties(self._properties, self._opt, self._path)
def extend(self, propnames):
"""Extends properties to the existing properties
@ -290,7 +290,7 @@ class Property(object):
"""
for propname in propnames:
self._append(propname, save=False)
self._setting._setproperties(self._properties, self._opt, self._path)
self._setting.setproperties(self._properties, self._opt, self._path)
def reset(self):
"""resets the properties (does not **clear** the properties,
@ -353,11 +353,14 @@ class Settings(object):
path = opt.impl_getpath(self._getcontext())
return self.getproperties(opt, path)
def getproperties(self, opt, path, setting_properties=undefined):
return Property(self,
self._getproperties(opt, path,
setting_properties=setting_properties),
opt, path)
def getproperties(self, opt, path, setting_properties=undefined, index=None, obj=True):
"""get properties for a specified option
"""
properties = self._getproperties(opt, path, index=index,
setting_properties=setting_properties)
if obj:
return Property(self, properties, opt, path)
return properties
def __setitem__(self, opt, value): # pragma: optional cover
raise ValueError(_('you should only append/remove properties'))
@ -435,20 +438,25 @@ class Settings(object):
props = self._p_.getproperties(None, default_properties)
if propname not in props:
props.add(propname)
self._setproperties(props, None, None)
self.setproperties(props, None, None)
def remove(self, propname):
"deletes property propname in the Config's properties attribute"
props = self._p_.getproperties(None, default_properties)
if propname in props:
props.remove(propname)
self._setproperties(props, None, None)
self.setproperties(props, None, None)
def extend(self, propnames):
for propname in propnames:
self.append(propname)
def _setproperties(self, properties, opt, path, force=False):
"""just for compatibility
"""
self.setproperties(properties, opt, path, force)
def setproperties(self, properties, opt, path, force=False):
"""save properties for specified path
(never save properties if same has option properties)
"""
@ -617,7 +625,7 @@ class Settings(object):
props = props | append
modified = True
if modified:
self._setproperties(props, None, None)
self.setproperties(props, None, None)
def read_only(self):
"convenience method to freeze, hide and disable"

View File

@ -160,7 +160,8 @@ class Values(object):
"""overrides the builtins `del()` instructions"""
self.reset(opt)
def reset(self, opt, path=None, validate=True, _setting_properties=None, _commit=True):
def reset(self, opt, path=None, validate=True, _setting_properties=None, _commit=True,
force_permissive=False):
context = self._getcontext()
setting = context.cfgimpl_get_settings()
if path is None:
@ -177,11 +178,13 @@ class Values(object):
fake_value.reset(opt, path, validate=False)
ret = fake_value._get_cached_value(opt, path,
setting_properties=_setting_properties,
check_frozen=True)
check_frozen=True,
force_permissive=force_permissive)
if isinstance(ret, Exception):
raise ret
if opt.impl_is_master_slaves('master'):
opt.impl_get_master_slaves().reset(opt, self, _setting_properties, _commit=_commit)
opt.impl_get_master_slaves().reset(opt, self, _setting_properties, _commit=_commit,
force_permissive=force_permissive)
if hasvalue:
if 'force_store_value' in setting._getproperties(opt=opt,
path=path,
@ -462,16 +465,20 @@ class Values(object):
if valid_masterslave and opt.impl_is_master_slaves():
if session is None:
session = self._p_.getsession()
setitem = True
if opt.impl_is_master_slaves('master'):
masterlen = len(value)
slavelen = None
elif index is not None:
masterlen = None
slavelen = index
setitem = False
else:
masterlen = None
slavelen = len(value)
setitem = True
opt.impl_get_master_slaves().impl_validate(self._getcontext(), force_permissive,
setting_properties, masterlen=masterlen,
slavelen=slavelen, opt=opt, setitem=True)
slavelen=slavelen, opt=opt, setitem=setitem)
#val = opt.impl_get_master_slaves().impl_validate(self, opt, len_value, path, session, setitem=setitem)
#if isinstance(val, Exception):
# return val
@ -533,7 +540,7 @@ class Values(object):
if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
return owners.default
if validate_properties:
value = self._get_cached_value(opt, path, True, force_permissive, None, True,
value = self._get_cached_value(opt, path=path, force_permissive=force_permissive,
self_properties=self_properties, session=session,
index=index)
if isinstance(value, Exception):
@ -557,7 +564,7 @@ class Values(object):
only_default=only_default, index=index)
return owner
def setowner(self, opt, owner, index=None):
def setowner(self, opt, owner, index=None, force_permissive=False):
"""
sets a owner to an option
@ -569,16 +576,17 @@ class Values(object):
path = opt.impl_getpath(self._getcontext())
session = self._p_.getsession()
if not self._p_.hasvalue(path, session):
raise ConfigError(_('no value for {0} cannot change owner to {1}'
'').format(path, owner))
props = self._getcontext().cfgimpl_get_settings().validate_properties(opt,
False,
True,
path,
index=index)
index=index,
force_permissive=force_permissive)
if props:
raise props
if not self._p_.hasvalue(path, session):
raise ConfigError(_('no value for {0} cannot change owner to {1}'
'').format(path, owner))
self._p_.setowner(path, owner, session, index=index)
def is_default_owner(self, opt, path=None, validate_properties=True,
@ -900,7 +908,7 @@ class Multi(list):
:param index: remove item a index
:type index: int
:param force: force pop item (withoud check master/slave)
:param force: force pop item (without check master/slave)
:type force: boolean
:returns: item at index
"""