tiramisu/tiramisu/autolib.py

283 lines
11 KiB
Python
Raw Normal View History

2017-07-08 15:59:56 +02:00
# Copyright (C) 2012-2017 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-09-18 09:48:41 +02:00
# The original `Config` design model is unproudly borrowed from
# the rough gus of pypy: pypy: http://codespeak.net/svn/pypy/dist/pypy/config/
# the whole pypy projet is under MIT licence
# ____________________________________________________________
"enables us to carry out a calculation and return an option's value"
2017-11-28 22:42:30 +01:00
from .error import PropertiesOptionError, ConfigError, SlaveError, display_list
from .i18n import _
from .setting import undefined
2017-12-07 22:20:19 +01:00
from .option.symlinkoption import DynSymLinkOption
2017-07-16 10:57:43 +02:00
from .storage import get_default_values_storages, get_default_settings_storages
# ____________________________________________________________
2013-04-03 12:20:26 +02:00
2017-11-28 22:42:30 +01:00
def carry_out_calculation(option,
context,
callback,
callback_params,
2017-12-13 22:15:34 +01:00
setting_properties,
2017-11-28 22:42:30 +01:00
index=undefined,
validate=True,
is_validator=False):
2013-08-21 14:52:48 +02:00
"""a function that carries out a calculation for an option's value
2013-04-03 12:20:26 +02:00
2014-01-30 22:55:15 +01:00
:param option: the option
2015-04-18 22:53:45 +02:00
:param context: the context config in order to have
2013-08-21 14:52:48 +02:00
the whole options available
:param callback: the name of the callback function
:type callback: str
:param callback_params: the callback's parameters
(only keyword parameters are allowed)
:type callback_params: dict
:param index: if an option is multi, only calculates the nth value
:type index: int
:param is_validator: to know if carry_out_calculation is used to validate a value
The callback_params is a dict. Key is used to build args (if key is '')
and kwargs (otherwise). Values are tuple of:
- values
- tuple with option and boolean's force_permissive (True when don't raise
if PropertiesOptionError)
Values could have multiple values only when key is ''.
* if no callback_params:
=> calculate(<function func at 0x2092320>, [], {})
* if callback_params={'': ('yes',)}
=> calculate(<function func at 0x2092320>, ['yes'], {})
* if callback_params={'value': ('yes',)}
=> calculate(<function func at 0x165b320>, [], {'value': 'yes'})
* if callback_params={'': ('yes', 'no')}
=> calculate('yes', 'no')
* if callback_params={'value': ('yes', 'no')}
=> ValueError()
* if callback_params={'': (['yes', 'no'],)}
=> calculate(<function func at 0x176b320>, ['yes', 'no'], {})
* if callback_params={'value': ('yes', 'no')}
=> raises ValueError()
* if callback_params={'': ((opt1, False),)}
- a simple option:
opt1 == 11
=> calculate(<function func at 0x1cea320>, [11], {})
- a multi option and not master/slave:
opt1 == [1, 2, 3]
=> calculate(<function func at 0x223c320>, [[1, 2, 3]], {})
- option is master or slave of opt1:
opt1 == [1, 2, 3]
=> calculate(<function func at 0x223c320>, [1], {})
=> calculate(<function func at 0x223c320>, [2], {})
=> calculate(<function func at 0x223c320>, [3], {})
- opt is a master or slave but not related to option:
opt1 == [1, 2, 3]
=> calculate(<function func at 0x11b0320>, [[1, 2, 3]], {})
* if callback_params={'value': ((opt1, False),)}
- a simple option:
opt1 == 11
=> calculate(<function func at 0x17ff320>, [], {'value': 11})
- a multi option:
opt1 == [1, 2, 3]
=> calculate(<function func at 0x1262320>, [], {'value': [1, 2, 3]})
* if callback_params={'': ((opt1, False), (opt2, False))}
- two single options
opt1 = 11
opt2 = 12
=> calculate(<function func at 0x217a320>, [11, 12], {})
- a multi option with a simple option
opt1 == [1, 2, 3]
opt2 == 12
=> calculate(<function func at 0x2153320>, [[1, 2, 3], 12], {})
- a multi option with an other multi option but with same length
opt1 == [1, 2, 3]
opt2 == [11, 12, 13]
=> calculate(<function func at 0x1981320>, [[1, 2, 3], [11, 12, 13]], {})
- a multi option with an other multi option but with different length
opt1 == [1, 2, 3]
opt2 == [11, 12]
=> calculate(<function func at 0x2384320>, [[1, 2, 3], [11, 12]], {})
- a multi option without value with a simple option
opt1 == []
opt2 == 11
=> calculate(<function func at 0xb65320>, [[], 12], {})
* if callback_params={'value': ((opt1, False), (opt2, False))}
=> raises ValueError()
If index is not undefined, return a value, otherwise return:
* a list if one parameters have multi option
* a value otherwise
If calculate return list, this list is extend to return value.
2013-08-21 14:52:48 +02:00
"""
tcparams = {}
# if callback_params has a callback, launch several time calculate()
2014-06-19 23:22:39 +02:00
master_slave = False
has_option = False
# multi's option should have same value for all option
if option._is_subdyn():
tcparams['suffix'] = [(option.impl_getsuffix(), False)]
2014-01-27 23:28:22 +01:00
for key, callbacks in callback_params.items():
for callbk in callbacks:
if isinstance(callbk, tuple):
2015-04-18 22:53:45 +02:00
if context is undefined:
return undefined
2014-07-06 15:31:57 +02:00
if callbk[0] is None: # pragma: optional cover
#Not an option, set full context
2017-07-16 10:57:43 +02:00
tcparams.setdefault(key, []).append((context.duplicate(
force_values=get_default_values_storages(),
force_settings=get_default_settings_storages()), False))
elif callbk[0] == 'index':
tcparams.setdefault(key, []).append((index, False))
else:
# callbk is something link (opt, True|False)
opt, force_permissive = callbk
2014-06-19 23:22:39 +02:00
if opt._is_subdyn():
2017-12-02 22:53:57 +01:00
opt = DynSymLinkOption(opt,
option._rootpath,
option.impl_getsuffix())
path = opt.impl_getpath(context)
2014-06-19 23:22:39 +02:00
else:
2015-04-18 22:53:45 +02:00
path = context.cfgimpl_get_description(
2014-06-19 23:22:39 +02:00
).impl_get_path_by_opt(opt)
2017-01-26 21:01:54 +01:00
# don't validate if option is option that we tried to validate
if opt == option:
valid = False
else:
valid = validate
# get value
2017-11-28 22:42:30 +01:00
try:
value = context.getattr(path,
force_permissive=True,
validate=valid,
setting_properties=setting_properties)
except PropertiesOptionError as err:
if force_permissive:
continue
raise ConfigError(_('unable to carry out a calculation for "{}"'
', {}').format(option.impl_get_display_name(), err))
2016-01-03 21:18:52 +01:00
# convert to list, not modifie this multi
if value.__class__.__name__ == 'Multi':
has_option = True
2016-01-03 21:18:52 +01:00
value = list(value)
if opt != option and opt.impl_is_master_slaves() and \
opt.impl_get_master_slaves().in_same_group(option):
2014-06-19 23:22:39 +02:00
master_slave = True
is_multi = True
else:
is_multi = False
tcparams.setdefault(key, []).append((value, is_multi))
2012-10-17 11:14:17 +02:00
else:
# callbk is a value and not a multi
2014-01-27 23:28:22 +01:00
tcparams.setdefault(key, []).append((callbk, False))
# if one value is a multi, launch several time calculate
# if index is set, return a value
# if no index, return a list
2014-06-19 23:22:39 +02:00
if master_slave:
ret = []
args = []
kwargs = {}
for key, couples in tcparams.items():
for couple in couples:
value, ismulti = couple
if ismulti:
val = value[index]
else:
val = value
if key == '':
args.append(val)
else:
kwargs[key] = val
return calculate(option, callback, is_validator, args, kwargs)
else:
# no value is multi
# return a single value
args = []
kwargs = {}
2012-10-17 11:14:17 +02:00
for key, couples in tcparams.items():
for couple in couples:
# couple[1] (ismulti) is always False
2012-10-17 11:14:17 +02:00
if key == '':
args.append(couple[0])
2012-10-17 11:14:17 +02:00
else:
kwargs[key] = couple[0]
ret = calculate(option, callback, is_validator, args, kwargs)
2015-12-26 10:57:20 +01:00
if not option.impl_is_optiondescription() and callback_params != {} and isinstance(ret, list) and \
option.impl_is_master_slaves('slave'):
if not has_option and index not in [None, undefined]:
if index < len(ret):
ret = ret[index]
else:
ret = None
else:
raise SlaveError(_("callback cannot return a list for a "
"slave option ({0})").format(option.impl_getname()))
return ret
2012-09-18 09:48:41 +02:00
2013-04-03 12:20:26 +02:00
def calculate(option, callback, is_validator, args, kwargs):
2013-05-23 14:55:52 +02:00
"""wrapper that launches the 'callback'
2013-05-10 16:02:27 +02:00
:param callback: callback function
:param args: in the callback's arity, the unnamed parameters
:param kwargs: in the callback's arity, the named parameters
2013-05-23 14:55:52 +02:00
2013-05-10 16:02:27 +02:00
"""
2016-10-14 22:20:14 +02:00
try:
return callback(*args, **kwargs)
2016-10-14 22:20:14 +02:00
except ValueError as err:
if is_validator:
2017-11-28 22:42:30 +01:00
raise err
error = err
except Exception as err:
error = err
if len(args) != 0 or len(kwargs) != 0:
msg = _('unexpected error "{0}" in function "{1}" with arguments "{3}" and "{4}" '
'for option "{2}"').format(str(error),
2017-07-09 09:49:03 +02:00
callback.__name__,
option.impl_get_display_name(),
args,
kwargs)
else:
msg = _('unexpected error "{0}" in function "{1}" for option "{2}"'
'').format(str(error),
2017-07-09 09:49:03 +02:00
callback.__name__,
option.impl_get_display_name())
raise ConfigError(msg)