many improvements
This commit is contained in:
@ -4,27 +4,39 @@ import warnings
|
||||
import re
|
||||
|
||||
|
||||
from .error import APIError, ValueWarning, ValueOptionError, ValueErrorWarning, PropertiesOptionError
|
||||
from .error import APIError, ConfigError, ValueWarning, ValueOptionError, ValueErrorWarning, PropertiesOptionError, display_list
|
||||
from .setting import undefined
|
||||
from .i18n import _
|
||||
|
||||
|
||||
TIRAMISU_JSON_VERSION = '1.0'
|
||||
DEBUG = False
|
||||
|
||||
|
||||
TYPE = {'boolean': bool,
|
||||
'integer': int,
|
||||
'string': str,
|
||||
'password': str,
|
||||
'domain': str}
|
||||
'filename': str,
|
||||
'email': str,
|
||||
'url': str,
|
||||
'ip': str,
|
||||
'network': str,
|
||||
'netmask': str,
|
||||
'broadcast_address': str,
|
||||
'port': str,
|
||||
'domainname': str,
|
||||
'date': str}
|
||||
|
||||
|
||||
class Option:
|
||||
# fake Option (IntOption, StrOption, ...)
|
||||
# only usefull for warnings
|
||||
def __init__(self,
|
||||
path):
|
||||
path,
|
||||
display_name):
|
||||
self.path = path
|
||||
self.display_name = display_name
|
||||
|
||||
def __call__(self):
|
||||
# suppose to be a weakref
|
||||
@ -33,6 +45,9 @@ class Option:
|
||||
def impl_getpath(self):
|
||||
return self.path
|
||||
|
||||
def impl_get_display_name(self):
|
||||
return self.display_name
|
||||
|
||||
|
||||
class TiramisuOptionOption:
|
||||
# config.option(path).option
|
||||
@ -40,16 +55,18 @@ class TiramisuOptionOption:
|
||||
config: 'Config',
|
||||
path: str,
|
||||
schema: Dict,
|
||||
model: Dict,
|
||||
form: Dict) -> None:
|
||||
self.config = config
|
||||
self._path = path
|
||||
self.schema = schema
|
||||
self.model = model
|
||||
self.form = form
|
||||
|
||||
def doc(self):
|
||||
return self.schema['title']
|
||||
if self.issymlinkoption():
|
||||
schema = self.config.get_schema(self.schema['opt_path'])
|
||||
else:
|
||||
schema = self.schema
|
||||
return schema['title']
|
||||
|
||||
def path(self):
|
||||
return self._path
|
||||
@ -95,14 +112,14 @@ class TiramisuOptionOption:
|
||||
return self.schema['type']
|
||||
|
||||
def properties(self) -> List[str]:
|
||||
model = self.model.get(self._path, {})
|
||||
model = self.config.model.get(self._path, {})
|
||||
if self.isfollower():
|
||||
model = model.get(None, {})
|
||||
return self.config.get_properties(model, self._path, None)
|
||||
|
||||
def requires(self) -> None:
|
||||
# FIXME
|
||||
return None
|
||||
#
|
||||
# def requires(self) -> None:
|
||||
# # FIXME
|
||||
# return None
|
||||
|
||||
def pattern(self):
|
||||
if self._path in self.form:
|
||||
@ -110,26 +127,29 @@ class TiramisuOptionOption:
|
||||
else:
|
||||
return None
|
||||
|
||||
def defaultmulti(self):
|
||||
if not self.schema.get('isMulti'):
|
||||
raise Exception('defaultmulti avalaible only for a multi')
|
||||
return self.schema.get('defaultmulti')
|
||||
|
||||
|
||||
class TiramisuOptionProperty:
|
||||
# config.option(path).property
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
path: str,
|
||||
index: Optional[int],
|
||||
model: Dict) -> None:
|
||||
index: Optional[int]) -> None:
|
||||
self.config = config
|
||||
self.path = path
|
||||
self.index = index
|
||||
self.model = model
|
||||
|
||||
def get(self, only_raises=False):
|
||||
if not only_raises:
|
||||
props = self.config.get_properties(self.model, self.path, self.index, only_raises)
|
||||
props = self.config.get_properties(self.config.model.get(self.path, {}), self.path, self.index, only_raises)
|
||||
else:
|
||||
props = []
|
||||
if self.config.is_hidden(self.path,
|
||||
self.index):
|
||||
self.index):
|
||||
props.append('hidden')
|
||||
return props
|
||||
|
||||
@ -140,30 +160,40 @@ class _Value:
|
||||
schema: Dict,
|
||||
root: str,
|
||||
fullpath: bool,
|
||||
withwarning: bool) -> None:
|
||||
withwarning: bool,
|
||||
flatten: bool,
|
||||
len_parent: Optional[int]) -> None:
|
||||
leadership_len = None
|
||||
for key, option in schema['properties'].items():
|
||||
if self.config.is_hidden(key, None) is False:
|
||||
if flatten:
|
||||
nkey = key.split('.')[-1]
|
||||
elif len_parent is not None:
|
||||
nkey = key[len_parent:]
|
||||
else:
|
||||
nkey = key
|
||||
if option['type'] in ['object', 'array']:
|
||||
# optiondescription or leadership
|
||||
self._dict_walk(ret,
|
||||
option,
|
||||
root,
|
||||
fullpath,
|
||||
withwarning)
|
||||
withwarning,
|
||||
flatten,
|
||||
len_parent)
|
||||
elif schema.get('type') == 'array' and leadership_len is not None:
|
||||
# followers
|
||||
values = []
|
||||
for index in range(leadership_len):
|
||||
value = self.config.get_value(key,
|
||||
index)
|
||||
self._display_warnings(key, value, option['type'], key, withwarning)
|
||||
self.config._check_raises_warnings(key, index, value, option['type'], withwarning)
|
||||
values.append(value)
|
||||
ret[key] = values
|
||||
ret[nkey] = values
|
||||
else:
|
||||
value = self.config.get_value(key)
|
||||
self._display_warnings(key, value, option['type'], key, withwarning)
|
||||
ret[key] = value
|
||||
self.config._check_raises_warnings(key, None, value, option['type'], withwarning)
|
||||
ret[nkey] = value
|
||||
if schema.get('type') == 'array':
|
||||
leadership_len = len(value)
|
||||
elif schema.get('type') == 'array' and leadership_len is None:
|
||||
@ -172,47 +202,30 @@ class _Value:
|
||||
|
||||
def dict(self,
|
||||
fullpath: bool=False,
|
||||
withwarning: bool=False):
|
||||
withwarning: bool=False,
|
||||
flatten: bool=False):
|
||||
ret = {}
|
||||
self._dict_walk(ret,
|
||||
self.schema,
|
||||
self.path,
|
||||
fullpath,
|
||||
withwarning)
|
||||
withwarning,
|
||||
flatten,
|
||||
None)
|
||||
return ret
|
||||
|
||||
def _display_warnings(self, path, value, type, name, withwarning=True):
|
||||
for err in self.model.get(path, {}).get('error', []):
|
||||
warnings.warn_explicit(ValueErrorWarning(value,
|
||||
type,
|
||||
Option(path),
|
||||
'{0}'.format(err)),
|
||||
ValueErrorWarning,
|
||||
self.__class__.__name__, 0)
|
||||
|
||||
if withwarning and self.model.get(path, {}).get('warnings'):
|
||||
for warn in self.model.get(path, {}).get('warnings'):
|
||||
warnings.warn_explicit(ValueErrorWarning(value,
|
||||
type,
|
||||
Option(path),
|
||||
'{0}'.format(err)),
|
||||
ValueErrorWarning,
|
||||
self.__class__.__name__, 0)
|
||||
|
||||
|
||||
class TiramisuOptionOwner:
|
||||
# config.option(path).owner
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
schema: Dict,
|
||||
model: List[Dict],
|
||||
form: List[Dict],
|
||||
temp: List[Dict],
|
||||
path: str,
|
||||
index: int) -> None:
|
||||
self.config = config
|
||||
self.schema = schema
|
||||
self.model = model
|
||||
self.form = form
|
||||
self.temp = temp
|
||||
self.path = path
|
||||
@ -225,35 +238,67 @@ class TiramisuOptionOwner:
|
||||
return self.config.get_owner(self.path, self.index)
|
||||
|
||||
|
||||
class TiramisuOptionValue(_Value):
|
||||
# config.option(path).value
|
||||
class TiramisuOptionDescriptionValue(_Value):
|
||||
# config.option(descr_path).value
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
schema: Dict,
|
||||
form: List[Dict],
|
||||
temp: List[Dict],
|
||||
path: str,
|
||||
index: int) -> None:
|
||||
self.config = config
|
||||
self.schema = schema
|
||||
self.form = form
|
||||
self.temp = temp
|
||||
self.path = path
|
||||
self.index = index
|
||||
|
||||
def dict(self,
|
||||
fullpath: bool=False,
|
||||
withwarning: bool=False,
|
||||
flatten: bool=False):
|
||||
ret = {}
|
||||
len_parent = len(self.path) + 1
|
||||
self._dict_walk(ret,
|
||||
self.schema,
|
||||
self.path,
|
||||
fullpath,
|
||||
withwarning,
|
||||
flatten,
|
||||
len_parent)
|
||||
return ret
|
||||
|
||||
|
||||
class TiramisuOptionValue(_Value):
|
||||
# config.option(path).value
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
schema: Dict,
|
||||
model: List[Dict],
|
||||
form: List[Dict],
|
||||
temp: List[Dict],
|
||||
path: str,
|
||||
index: int) -> None:
|
||||
self.config = config
|
||||
self.schema = schema
|
||||
self.model = model
|
||||
self.form = form
|
||||
self.temp = temp
|
||||
self.path = path
|
||||
self.index = index
|
||||
|
||||
def get(self) -> Any:
|
||||
if self.config.isfollower(self.path):
|
||||
if self.schema['type'] == 'symlink':
|
||||
# FIXME should tested it too
|
||||
pass
|
||||
elif self.config.isfollower(self.path):
|
||||
if self.index is None:
|
||||
raise APIError(_('index must be set with the follower option "{}"').format(self.path))
|
||||
value = self.config.get_value(self.path, self.index)
|
||||
self._display_warnings(self.path, value, self.schema['type'], self.path)
|
||||
return value
|
||||
if self.index is not None:
|
||||
elif self.index is not None:
|
||||
raise APIError(_('index must only be set with a follower option, not for "{}"').format(self.path))
|
||||
value = self.config.get_value(self.path)
|
||||
self._display_warnings(self.path, value, self.schema['type'], self.path)
|
||||
if self.config.is_hidden(self.path, self.index):
|
||||
raise PropertiesOptionError(None, {'disabled'}, None, opt_type='option')
|
||||
value = self.config.get_value(self.path, self.index)
|
||||
self.config._check_raises_warnings(self.path, self.index, value, self.schema['type'])
|
||||
return value
|
||||
|
||||
def list(self):
|
||||
@ -262,8 +307,10 @@ class TiramisuOptionValue(_Value):
|
||||
def _validate(self, type_, value):
|
||||
if value in [None, undefined]:
|
||||
return
|
||||
if type_ == 'symlink':
|
||||
raise ConfigError(_("can't assign to a SymLinkOption"))
|
||||
if type_ == 'choice':
|
||||
if value not in self.schema['enum']:
|
||||
if 'enum' in self.schema and value not in self.schema['enum']:
|
||||
raise ValueError('value {} is not in {}'.format(value, self.schema['enum']))
|
||||
elif not isinstance(value, TYPE[type_]):
|
||||
raise ValueError('value {} is not a valid {} '.format(value, type_))
|
||||
@ -271,12 +318,14 @@ class TiramisuOptionValue(_Value):
|
||||
def set(self, value):
|
||||
type_ = self.schema['type']
|
||||
leader_old_value = undefined
|
||||
if self.config.is_hidden(self.path, self.index):
|
||||
raise PropertiesOptionError(None, {'disabled'}, None, opt_type='option')
|
||||
if self.config.isleader(self.path):
|
||||
leader_old_value = self.config.get_value(self.path)
|
||||
remote = self.form.get(self.path, {}).get('remote', False)
|
||||
if self.index is None and self.schema.get('isMulti', False):
|
||||
if not isinstance(value, list):
|
||||
raise Exception('value must be a list')
|
||||
raise ValueError('value must be a list')
|
||||
for val in value:
|
||||
if self.schema.get('isSubMulti', False):
|
||||
for v in val:
|
||||
@ -294,19 +343,32 @@ class TiramisuOptionValue(_Value):
|
||||
value,
|
||||
remote,
|
||||
leader_old_value)
|
||||
self._display_warnings(self.path, value, type_, self.path)
|
||||
self.config._check_raises_warnings(self.path, self.index, value, type_)
|
||||
|
||||
def reset(self):
|
||||
self.config.delete_value(self.path,
|
||||
self.index)
|
||||
|
||||
def default(self):
|
||||
return self.schema.get('value')
|
||||
if self.schema.get('isMulti'):
|
||||
if self.config.isfollower(self.path):
|
||||
if self.index is not None:
|
||||
value = self.schema['defaultmulti']
|
||||
else:
|
||||
leader = next(iter(self.config.option(self.path.rsplit('.', 1)[0]).schema['properties']))
|
||||
len_value = len(self.config.get_value(leader))
|
||||
value = [self.schema['defaultmulti']] * len_value
|
||||
else:
|
||||
value = self.schema.get('value', [])
|
||||
else:
|
||||
value = self.schema.get('value')
|
||||
return value
|
||||
|
||||
|
||||
class _Option:
|
||||
def list(self,
|
||||
type='option'):
|
||||
type='option',
|
||||
recursive=False):
|
||||
if type not in ['all', 'option', 'optiondescription']:
|
||||
raise Exception('unknown list type {}'.format(type))
|
||||
for path, schema in self.schema['properties'].items():
|
||||
@ -315,14 +377,18 @@ class _Option:
|
||||
if type in ['all', 'optiondescription']:
|
||||
yield TiramisuOptionDescription(self.config,
|
||||
schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
path)
|
||||
if recursive:
|
||||
yield from TiramisuOptionDescription(self.config,
|
||||
schema,
|
||||
self.form,
|
||||
self.temp,
|
||||
path).list(type, recursive)
|
||||
elif type in ['all', 'option']:
|
||||
yield TiramisuOption(self.config,
|
||||
schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
path,
|
||||
@ -334,13 +400,11 @@ class TiramisuOptionDescription(_Option):
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
schema: Dict,
|
||||
model: List[Dict],
|
||||
form: List[Dict],
|
||||
temp: List[Dict],
|
||||
path: str) -> None:
|
||||
self.config = config
|
||||
self.schema = schema
|
||||
self.model = model
|
||||
self.form = form
|
||||
self.temp = temp
|
||||
self.path = path
|
||||
@ -352,51 +416,34 @@ class TiramisuOptionDescription(_Option):
|
||||
return TiramisuOptionOption(self.config,
|
||||
self.path,
|
||||
self.schema,
|
||||
self.model,
|
||||
self.form)
|
||||
if subfunc == 'property':
|
||||
return TiramisuOptionProperty(self.config,
|
||||
self.path,
|
||||
self.model.get(self.path, {}))
|
||||
if subfunc == 'value' and self.schema['type'] == 'array':
|
||||
return TiramisuLeadershipValue(self.config,
|
||||
self.schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
self.path,
|
||||
self.index)
|
||||
None)
|
||||
if subfunc == 'value':
|
||||
return TiramisuOptionDescriptionValue(self.config,
|
||||
self.schema,
|
||||
self.form,
|
||||
self.temp,
|
||||
self.path,
|
||||
self.index)
|
||||
raise APIError(_('please specify a valid sub function ({})').format(subfunc))
|
||||
|
||||
def group_type(self):
|
||||
if self.config.is_hidden(self.path, None):
|
||||
if not self.config.is_hidden(self.path, None):
|
||||
# FIXME
|
||||
return 'default'
|
||||
raise PropertiesOptionError(None, None, None, opt_type='optiondescription')
|
||||
raise PropertiesOptionError(None, {'disabled'}, None, opt_type='optiondescription')
|
||||
|
||||
|
||||
class TiramisuLeadershipValue:
|
||||
def __init__(self,
|
||||
config,
|
||||
schema,
|
||||
model,
|
||||
form,
|
||||
temp,
|
||||
path):
|
||||
self.config = config
|
||||
self.schema = schema
|
||||
self.model = model
|
||||
self.form = form
|
||||
self.temp = temp
|
||||
self.path = path
|
||||
|
||||
class TiramisuLeadershipValue(TiramisuOptionValue):
|
||||
def len(self):
|
||||
return len(self.config.get_value(self.schema['properties'][0]))
|
||||
return len(self.config.get_value(self.path))
|
||||
|
||||
def pop(self,
|
||||
index: int) -> None:
|
||||
leadership_path = self.schema['properties'][0]
|
||||
self.config.delete_value(leadership_path, index)
|
||||
self.config.delete_value(self.path, index)
|
||||
|
||||
|
||||
class TiramisuOption:
|
||||
@ -404,14 +451,12 @@ class TiramisuOption:
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
schema: Dict,
|
||||
model: List[Dict],
|
||||
form: List[Dict],
|
||||
temp: List[Dict],
|
||||
path: str,
|
||||
index: Optional[int]) -> None:
|
||||
self.config = config
|
||||
self.schema = schema
|
||||
self.model = model
|
||||
self.form = form
|
||||
self.temp = temp
|
||||
self.path = path
|
||||
@ -425,20 +470,21 @@ class TiramisuOption:
|
||||
return TiramisuOptionOption(self.config,
|
||||
self.path,
|
||||
self.schema,
|
||||
self.model,
|
||||
self.form)
|
||||
if subfunc == 'value':
|
||||
return TiramisuOptionValue(self.config,
|
||||
self.schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
self.path,
|
||||
self.index)
|
||||
if self.config.isleader(self.path):
|
||||
obj = TiramisuLeadershipValue
|
||||
else:
|
||||
obj = TiramisuOptionValue
|
||||
return obj(self.config,
|
||||
self.schema,
|
||||
self.form,
|
||||
self.temp,
|
||||
self.path,
|
||||
self.index)
|
||||
if subfunc == 'owner':
|
||||
return TiramisuOptionOwner(self.config,
|
||||
self.schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
self.path,
|
||||
@ -446,32 +492,28 @@ class TiramisuOption:
|
||||
if subfunc == 'property':
|
||||
return TiramisuOptionProperty(self.config,
|
||||
self.path,
|
||||
self.index,
|
||||
self.model.get(self.path, {}))
|
||||
self.index)
|
||||
raise APIError(_('please specify a valid sub function ({})').format(subfunc))
|
||||
|
||||
|
||||
class TiramisuContextProperty:
|
||||
# config.property
|
||||
# def __init__(self,
|
||||
# json):
|
||||
# self.json = json
|
||||
def __init__(self,
|
||||
config):
|
||||
self.config = config
|
||||
|
||||
def get(self):
|
||||
# FIXME ?
|
||||
return ['demoting_error_warning']
|
||||
return self.config.global_model.get('properties')
|
||||
|
||||
|
||||
class ContextOption(_Option):
|
||||
# config.option
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
model: Dict,
|
||||
form: Dict,
|
||||
schema: Dict,
|
||||
temp: Dict) -> None:
|
||||
self.config = config
|
||||
self.model = model
|
||||
self.form = form
|
||||
self.schema = {'properties': schema}
|
||||
self.temp = temp
|
||||
@ -484,29 +526,42 @@ class ContextOption(_Option):
|
||||
if schema['type'] in ['object', 'array']:
|
||||
return TiramisuOptionDescription(self.config,
|
||||
schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
path)
|
||||
return TiramisuOption(self.config,
|
||||
schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
path,
|
||||
index)
|
||||
|
||||
|
||||
class ContextValue(_Value):
|
||||
# config.value
|
||||
class ContextOwner:
|
||||
# config.owner
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
form: Dict,
|
||||
schema: Dict,
|
||||
temp: Dict) -> None:
|
||||
self.config = config
|
||||
self.form = form
|
||||
self.schema = {'properties': schema}
|
||||
self.temp = temp
|
||||
self.index = None
|
||||
|
||||
def get(self):
|
||||
return self.config.global_model.get('owner', 'tmp')
|
||||
|
||||
|
||||
class ContextValue(_Value):
|
||||
# config.value
|
||||
def __init__(self,
|
||||
config: 'Config',
|
||||
model: Dict,
|
||||
form: Dict,
|
||||
schema: Dict,
|
||||
temp: Dict) -> None:
|
||||
self.config = config
|
||||
self.model = model
|
||||
self.form = form
|
||||
first = next(iter(schema.keys()))
|
||||
self.path = first.rsplit('.', 1)[0]
|
||||
@ -516,7 +571,6 @@ class ContextValue(_Value):
|
||||
def __call__(self) -> TiramisuOptionValue:
|
||||
return TiramisuOptionValue(self.config,
|
||||
self.schema,
|
||||
self.model,
|
||||
self.form,
|
||||
self.temp,
|
||||
path,
|
||||
@ -525,7 +579,7 @@ class ContextValue(_Value):
|
||||
def mandatory(self):
|
||||
for key, value in self.dict().items():
|
||||
if self.config.isfollower(key):
|
||||
if self.model.get(key, {}).get(None, {}).get('required'):
|
||||
if self.config.model.get(key, {}).get(None, {}).get('required'):
|
||||
# FIXME test with index
|
||||
if self.config.get_schema(key).get('isSubMulti'):
|
||||
for val in value:
|
||||
@ -535,11 +589,11 @@ class ContextValue(_Value):
|
||||
elif None in value or '' in value:
|
||||
yield key
|
||||
elif self.config.get_schema(key).get('isMulti'):
|
||||
if self.model.get(key, {}).get('required') and (None in value or '' in value):
|
||||
if self.config.model.get(key, {}).get('required') and (None in value or '' in value):
|
||||
yield key
|
||||
if self.model.get(key, {}).get('needs_len') and not value:
|
||||
if self.config.model.get(key, {}).get('needs_len') and not value:
|
||||
yield key
|
||||
elif self.model.get(key, {}).get('required') and value is None:
|
||||
elif self.config.model.get(key, {}).get('required') and value is None:
|
||||
yield key
|
||||
|
||||
|
||||
@ -547,18 +601,26 @@ class Config:
|
||||
# config
|
||||
def __init__(self,
|
||||
json):
|
||||
if DEBUG:
|
||||
from pprint import pprint
|
||||
pprint(json)
|
||||
if json.get('version') != TIRAMISU_JSON_VERSION:
|
||||
raise Exception('incompatible tiramisu-json format version (got {}, expected {})'.format(json.get('version', '0.0'), TIRAMISU_JSON_VERSION))
|
||||
self.model = json['model']
|
||||
self.form = json['form']
|
||||
self.model = json.get('model')
|
||||
self.global_model = json.get('global')
|
||||
self.form = json.get('form')
|
||||
# support pattern
|
||||
for key, option in self.form.items():
|
||||
if key != 'null' and 'pattern' in option:
|
||||
option['pattern'] = re.compile(option['pattern'])
|
||||
if self.form:
|
||||
for key, option in self.form.items():
|
||||
if key != 'null' and 'pattern' in option:
|
||||
option['pattern'] = re.compile(option['pattern'])
|
||||
self.temp = {}
|
||||
self.schema = json['schema']
|
||||
self.schema = json.get('schema')
|
||||
self.updates = []
|
||||
first_path = next(iter(self.schema.keys()))
|
||||
if self.schema:
|
||||
first_path = next(iter(self.schema.keys()))
|
||||
else:
|
||||
first_path = ''
|
||||
if '.' in first_path:
|
||||
self.root = first_path.rsplit('.', 1)[0]
|
||||
else:
|
||||
@ -567,16 +629,19 @@ class Config:
|
||||
def __getattr__(self,
|
||||
subfunc: str) -> Any:
|
||||
if subfunc == 'property':
|
||||
return TiramisuContextProperty()
|
||||
return TiramisuContextProperty(self)
|
||||
if subfunc == 'option':
|
||||
return ContextOption(self,
|
||||
self.model,
|
||||
self.form,
|
||||
self.schema,
|
||||
self.temp)
|
||||
if subfunc == 'value':
|
||||
return ContextValue(self,
|
||||
self.model,
|
||||
self.form,
|
||||
self.schema,
|
||||
self.temp)
|
||||
if subfunc == 'owner':
|
||||
return ContextOwner(self,
|
||||
self.form,
|
||||
self.schema,
|
||||
self.temp)
|
||||
@ -587,15 +652,21 @@ class Config:
|
||||
index: Optional[int],
|
||||
value: Any,
|
||||
remote: bool) -> None:
|
||||
self.manage_updates('add',
|
||||
path,
|
||||
index,
|
||||
value)
|
||||
if remote:
|
||||
self.manage_updates('add',
|
||||
path,
|
||||
index,
|
||||
value)
|
||||
self.updates_value('add',
|
||||
path,
|
||||
index,
|
||||
value,
|
||||
remote)
|
||||
if not remote:
|
||||
self.manage_updates('add',
|
||||
path,
|
||||
index,
|
||||
value)
|
||||
|
||||
def modify_value(self,
|
||||
path: str,
|
||||
@ -603,41 +674,70 @@ class Config:
|
||||
value: Any,
|
||||
remote: bool,
|
||||
leader_old_value: Any) -> None:
|
||||
if not remote:
|
||||
self.updates_value('modify',
|
||||
path,
|
||||
index,
|
||||
value,
|
||||
remote,
|
||||
False,
|
||||
leader_old_value)
|
||||
schema = self.get_schema(path)
|
||||
if value and isinstance(value, list) and value[-1] is undefined:
|
||||
new_value = schema.get('defaultvalue')
|
||||
if new_value is None:
|
||||
len_value = len(value)
|
||||
schema_value = schema.get('value', [])
|
||||
if len(schema_value) >= len_value:
|
||||
new_value = schema_value[len_value - 1]
|
||||
value[-1] = new_value
|
||||
|
||||
self.manage_updates('modify',
|
||||
path,
|
||||
index,
|
||||
value)
|
||||
self.updates_value('modify',
|
||||
path,
|
||||
index,
|
||||
value,
|
||||
remote,
|
||||
False,
|
||||
leader_old_value)
|
||||
if value and isinstance(value, list) and undefined in value:
|
||||
new_value = schema.get('defaultmulti')
|
||||
if remote:
|
||||
for idx, val in enumerate(value):
|
||||
self.manage_updates('modify',
|
||||
path,
|
||||
idx,
|
||||
val)
|
||||
else:
|
||||
while undefined in value:
|
||||
undefined_index = value.index(undefined)
|
||||
schema_value = schema.get('value', [])
|
||||
if len(schema_value) > undefined_index:
|
||||
value[undefined_index] = schema_value[undefined_index]
|
||||
else:
|
||||
value[undefined_index] = new_value
|
||||
self.manage_updates('modify',
|
||||
path,
|
||||
index,
|
||||
value)
|
||||
else:
|
||||
self.manage_updates('modify',
|
||||
path,
|
||||
index,
|
||||
value)
|
||||
if remote:
|
||||
self.updates_value('modify',
|
||||
path,
|
||||
index,
|
||||
value,
|
||||
remote,
|
||||
False,
|
||||
leader_old_value)
|
||||
|
||||
def delete_value(self,
|
||||
path: str,
|
||||
index: Optional[int]) -> None:
|
||||
if self.get_schema(path)['type'] == 'symlink':
|
||||
raise ConfigError(_("can't delete a SymLinkOption"))
|
||||
remote = self.form.get(path, {}).get('remote', False)
|
||||
self.manage_updates('delete',
|
||||
path,
|
||||
index,
|
||||
None)
|
||||
if remote:
|
||||
self.manage_updates('delete',
|
||||
path,
|
||||
index,
|
||||
None)
|
||||
self.updates_value('delete',
|
||||
path,
|
||||
index,
|
||||
None,
|
||||
remote)
|
||||
if not remote:
|
||||
self.manage_updates('delete',
|
||||
path,
|
||||
index,
|
||||
None)
|
||||
|
||||
def get_properties(self,
|
||||
model,
|
||||
@ -703,23 +803,44 @@ class Config:
|
||||
|
||||
def is_hidden(self,
|
||||
path: str,
|
||||
index: Optional[int]) -> bool:
|
||||
for property_, needs in {'hidden': True, 'display': False}.items():
|
||||
if index is not None and property_ in self.temp.get(path, {}).get(str(index), {}):
|
||||
return self.temp[path][str(index)][property_]
|
||||
if property_ in self.temp.get(path, {}):
|
||||
return self.temp[path][property_]
|
||||
elif self.isfollower(path):
|
||||
if self.model.get(path, {}).get('null', {}).get(property_, None) == needs:
|
||||
return True
|
||||
elif self.model.get(path, {}).get(property_, None) == needs:
|
||||
index: Optional[int],
|
||||
permissive: bool=False) -> bool:
|
||||
if permissive:
|
||||
property_ = 'hidden'
|
||||
needs = True
|
||||
if property_ in self.global_model.get('permissives', []):
|
||||
return False
|
||||
else:
|
||||
property_ = 'display'
|
||||
needs = False
|
||||
if index is not None and property_ in self.temp.get(path, {}).get(str(index), {}):
|
||||
return self.temp[path][str(index)][property_] == needs
|
||||
if property_ in self.temp.get(path, {}):
|
||||
return self.temp[path][property_] == needs
|
||||
elif self.isfollower(path):
|
||||
if self.model.get(path, {}).get('null', {}).get(property_, None) == needs:
|
||||
return True
|
||||
elif self.model.get(path, {}).get(property_, None) == needs:
|
||||
return True
|
||||
if index is not None:
|
||||
index = str(index)
|
||||
if self.model.get(path, {}).get(index, {}).get(property_) == needs:
|
||||
return True
|
||||
if index is not None:
|
||||
index = str(index)
|
||||
if self.model.get(path, {}).get(index, {}).get(property_) == needs:
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_from_temp_model(self,
|
||||
path,
|
||||
index):
|
||||
if path in self.temp:
|
||||
is_delete = 'delete' in self.temp[path] and self.temp[path]['delete'] == True
|
||||
if index is not None and not is_delete and 'delete' in self.temp[path].get(index, {}):
|
||||
is_delete = self.temp[path][index]['delete'] == True
|
||||
if is_delete:
|
||||
return None
|
||||
if index is None and 'value' in self.temp[path] or 'value' in self.temp[path].get(index, {}):
|
||||
return self.temp[path]
|
||||
return self.model.get(path)
|
||||
|
||||
def get_value(self,
|
||||
path: str,
|
||||
index: int=None) -> Any:
|
||||
@ -728,30 +849,37 @@ class Config:
|
||||
path = schema['opt_path']
|
||||
schema = self.get_schema(path)
|
||||
if index is None:
|
||||
if 'value' in self.temp.get(path, {}):
|
||||
value = self.temp[path]['value']
|
||||
else:
|
||||
value = self.model.get(path, {}).get('value')
|
||||
if value is None and schema.get('isMulti', False):
|
||||
if self.isfollower(path):
|
||||
value = []
|
||||
parent_schema = self.get_schema(path.rsplit('.', 1)[0])
|
||||
leader = next(iter(parent_schema['properties'].keys()))
|
||||
leadership_len = len(self.get_value(leader))
|
||||
for idx in range(leadership_len):
|
||||
val = self.get_value(path,
|
||||
idx)
|
||||
self._check_raises_warnings(path, idx, val, schema['type'])
|
||||
value.append(val)
|
||||
else:
|
||||
value = self.get_from_temp_model(path, index)
|
||||
if value is not None and 'value' in value:
|
||||
value = value['value']
|
||||
else:
|
||||
value = schema.get('value')
|
||||
if value is None and schema.get('isMulti', False):
|
||||
value = []
|
||||
else:
|
||||
index = str(index)
|
||||
if 'delete' in self.temp.get(path, {}):
|
||||
value = None
|
||||
elif self.temp.get(path, {}).get(index, {}).get('delete') == True:
|
||||
value = None
|
||||
elif 'value' in self.temp.get(path, {}).get(index, {}):
|
||||
value = self.temp[path]
|
||||
else:
|
||||
value = self.model.get(path)
|
||||
if self.isfollower(path):
|
||||
if self.is_hidden(path, index):
|
||||
value = PropertiesOptionError(None, None, None, opt_type='option')
|
||||
elif value is not None and 'value' in value.get(index, {}):
|
||||
value = value[index]['value']
|
||||
value = PropertiesOptionError(None, {'disabled'}, None, opt_type='option')
|
||||
else:
|
||||
value = schema.get('default')
|
||||
value = self.get_from_temp_model(path, index)
|
||||
if value is not None and 'value' in value.get(index, {}):
|
||||
value = value[index]['value']
|
||||
else:
|
||||
value = schema.get('defaultmulti')
|
||||
else:
|
||||
value = self.get_from_temp_model(path, index)
|
||||
if value is not None and index in value and 'value' in value[index]:
|
||||
value = value[index]['value']
|
||||
else:
|
||||
@ -765,20 +893,24 @@ class Config:
|
||||
def get_owner(self,
|
||||
path: str,
|
||||
index: int) -> str:
|
||||
if not self.isfollower(path):
|
||||
schema = self.get_schema(path)
|
||||
if schema['type'] == 'symlink':
|
||||
opt_path = schema['opt_path']
|
||||
index = str(index)
|
||||
if self.is_hidden(opt_path, index):
|
||||
raise PropertiesOptionError(None, {'disabled'}, None, opt_type='option')
|
||||
return self.get_owner(opt_path, index)
|
||||
elif not self.isfollower(path):
|
||||
if 'owner' in self.temp.get(path, {}):
|
||||
owner = self.temp[path]['owner']
|
||||
else:
|
||||
owner = self.model.get(path, {}).get('owner', 'default')
|
||||
else:
|
||||
if 'value' in self.temp.get(path, {}):
|
||||
value = self.temp[path]
|
||||
else:
|
||||
value = self.model.get(path, {})
|
||||
index = str(index)
|
||||
if self.is_hidden(path, index):
|
||||
raise PropertiesOptionError(None, None, None, opt_type='option')
|
||||
if 'owner' in value.get(index, {}):
|
||||
raise PropertiesOptionError(None, {'disabled'}, None, opt_type='option')
|
||||
value = self.get_from_temp_model(path, index)
|
||||
if value is not None and 'owner' in value.get(index, {}):
|
||||
owner = value[index]['owner']
|
||||
else:
|
||||
owner = 'default'
|
||||
@ -804,7 +936,7 @@ class Config:
|
||||
del self.updates[-1]
|
||||
else:
|
||||
break
|
||||
elif last_body['index'] == index:
|
||||
elif last_body.get('index') == index:
|
||||
if last_body['action'] == 'add' and action == 'modify':
|
||||
action = 'add'
|
||||
update_last_action = True
|
||||
@ -826,12 +958,19 @@ class Config:
|
||||
else:
|
||||
data = {'action': action,
|
||||
'name': path}
|
||||
if action != 'delete' and value is not None:
|
||||
if action != 'delete' and value is not undefined:
|
||||
data['value'] = value
|
||||
if index is not None:
|
||||
data['index'] = index
|
||||
self.updates.append(data)
|
||||
|
||||
def send(self):
|
||||
if DEBUG:
|
||||
print('<===== send')
|
||||
print(self.updates)
|
||||
self.updates_data(self.send_data({'updates': self.updates,
|
||||
'model': self.model}))
|
||||
|
||||
def updates_value(self,
|
||||
action: str,
|
||||
path: str,
|
||||
@ -840,93 +979,101 @@ class Config:
|
||||
remote: bool,
|
||||
default_value: bool=False,
|
||||
leader_old_value: Optional[Any]=undefined) -> None:
|
||||
if 'pattern' in self.form.get(path, {}) and (not isinstance(value, list) or undefined not in value):
|
||||
match = self.test_value(path, value, remote)
|
||||
if 'pattern' in self.form.get(path, {}) and (not isinstance(value, list) or undefined not in value) and not self.test_value(path, index, value, remote):
|
||||
return
|
||||
if remote:
|
||||
self.send()
|
||||
else:
|
||||
match = True
|
||||
if match:
|
||||
if remote:
|
||||
self.updates_data(self.send_data({'updates': self.updates,
|
||||
'model': self.model}))
|
||||
|
||||
else:
|
||||
if action == 'delete':
|
||||
if index is None:
|
||||
# leader or standard option
|
||||
# set value to default value
|
||||
value = self.default_value(path)
|
||||
self._set_temp_value(path, None, value, 'default')
|
||||
if self.option(path).option.isleader():
|
||||
# if leader, set follower to default value
|
||||
leadership_path = path.rsplit('.', 1)[0]
|
||||
parent_schema = self.get_schema(leadership_path)
|
||||
iter_leadership = list(parent_schema['properties'].keys())
|
||||
for follower in iter_leadership[1:]:
|
||||
# delete all values
|
||||
self._del_temp_value(follower, None)
|
||||
value = self.get_value(path)
|
||||
elif self.option(path).option.isleader():
|
||||
# if remove an indexed leader value
|
||||
if path in self.model and (index is None or str(index) in self.model[path]):
|
||||
model = self.model[path]
|
||||
if index is not None:
|
||||
model = model[str(index)]
|
||||
if 'warnings' in model:
|
||||
del model['warnings']
|
||||
if 'error' in model:
|
||||
del model['error']
|
||||
if action == 'delete':
|
||||
if self.option(path).option.isleader():
|
||||
# if remove an indexed leader value
|
||||
if index is not None:
|
||||
leader_value = self.option(path).value.get()
|
||||
leader_value.pop(index)
|
||||
max_value = len(leader_value)
|
||||
self._set_temp_value(path, None, leader_value, 'tmp')
|
||||
leadership_path = path.rsplit('.', 1)[0]
|
||||
parent_schema = self.get_schema(leadership_path)
|
||||
iter_leadership = list(parent_schema['properties'].keys())
|
||||
for follower in iter_leadership[1:]:
|
||||
# remove value for this index and reduce len
|
||||
new_temp = {}
|
||||
for idx in range(max_value):
|
||||
owner = self.global_model.get('owner', 'tmp')
|
||||
else:
|
||||
leader_value = self.default_value(path)
|
||||
owner = 'default'
|
||||
max_value = len(leader_value) + 1
|
||||
self._set_temp_value(path, None, leader_value, owner)
|
||||
leadership_path = path.rsplit('.', 1)[0]
|
||||
parent_schema = self.get_schema(leadership_path)
|
||||
iter_leadership = list(parent_schema['properties'].keys())
|
||||
for follower in iter_leadership[1:]:
|
||||
# remove value for this index and reduce len
|
||||
new_temp = {}
|
||||
for idx in range(max_value):
|
||||
cur_index = idx
|
||||
if index is not None:
|
||||
if index == idx:
|
||||
continue
|
||||
cur_index = idx
|
||||
if index < cur_index:
|
||||
cur_index = -1
|
||||
if 'delete' in self.temp.get(follower, {}):
|
||||
#FIXME copier les attributs hidden, ... depuis self.temp[follower][index] ?
|
||||
cur_index -= 1
|
||||
if 'delete' in self.temp.get(follower, {}):
|
||||
#FIXME copier les attributs hidden, ... depuis self.temp[follower][index] ?
|
||||
new_temp[str(cur_index)] = {'delete': True}
|
||||
elif self.temp.get(follower, {}).get(str(idx)) is not None:
|
||||
if index is None or index == idx:
|
||||
new_temp[str(cur_index)] = {'delete': True}
|
||||
elif self.temp.get(follower, {}).get(str(idx)) is not None:
|
||||
else:
|
||||
new_temp[str(cur_index)] = self.temp[follower][str(idx)]
|
||||
elif self.model.get(follower, {}).get(str(idx)) is not None:
|
||||
elif self.model.get(follower, {}).get(str(idx)) is not None:
|
||||
if index is None or index == idx:
|
||||
new_temp[str(cur_index)] = {'delete': True}
|
||||
else:
|
||||
new_temp[str(cur_index)] = self.model[follower][str(idx)]
|
||||
if self.model[follower].get(str(max_value)) is not None:
|
||||
# FIXME copier les attributs hidden, ... depuis self.temp[follower][index] ?
|
||||
new_temp[str(max_value)] = {'delete': True}
|
||||
self.temp[follower] = new_temp
|
||||
value = leader_value
|
||||
index = None
|
||||
else:
|
||||
# it's a follower with index
|
||||
self.temp.setdefault(path, {})[str(index)] = {'delete': True}
|
||||
self._del_temp_value(path, index)
|
||||
value = self.get_value(path, index)
|
||||
default_value = True
|
||||
if self.model.get(follower, {}).get(str(max_value)) is not None:
|
||||
# FIXME copier les attributs hidden, ... depuis self.temp[follower][index] ?
|
||||
new_temp[str(max_value)] = {'delete': True}
|
||||
self.temp[follower] = new_temp
|
||||
value = leader_value
|
||||
index = None
|
||||
elif index is None:
|
||||
# set a value for a not follower option
|
||||
if default_value is True:
|
||||
self.model[path]['value'] = value
|
||||
else:
|
||||
self._set_temp_value(path, None, value, 'tmp')
|
||||
self._del_temp_value(path, index)
|
||||
value = self.get_value(path)
|
||||
else:
|
||||
# set a value for a follower option
|
||||
self.temp.setdefault(path, {})[str(index)] = {'value': value, 'owner': 'tmp'}
|
||||
if default_value is True:
|
||||
self.model[path][str(index)]['value'] = value
|
||||
else:
|
||||
self._set_temp_value(path, index, value, 'tmp')
|
||||
self.set_dependencies(path, value, index=index)
|
||||
self.set_not_equal(path, value)
|
||||
self.do_copy(path, value)
|
||||
if leader_old_value is not undefined and len(leader_old_value) < len(value):
|
||||
# if leader and length is change, display/hide follower from follower's default value
|
||||
index = len(value) - 1
|
||||
parent_path = '.'.join(path.split('.')[:-1])
|
||||
followers = list(self.option(parent_path).list())[1:]
|
||||
for follower in followers:
|
||||
follower_path = follower.option.path()
|
||||
# it's a follower with index
|
||||
self.temp.setdefault(path, {})[str(index)] = {'delete': True}
|
||||
self._del_temp_value(path, index)
|
||||
value = self.get_value(path, index)
|
||||
default_value = True
|
||||
elif index is None:
|
||||
# set a value for a not follower option
|
||||
self.set_not_equal(path, value, index)
|
||||
if default_value is True:
|
||||
self.model[path]['value'] = value
|
||||
else:
|
||||
self._set_temp_value(path, None, value, self.global_model.get('owner', 'tmp'))
|
||||
else:
|
||||
self.set_not_equal(path, value, index)
|
||||
# set a value for a follower option
|
||||
self.temp.setdefault(path, {})[str(index)] = {'value': value, 'owner': self.global_model.get('owner', 'tmp')}
|
||||
if default_value is True:
|
||||
self.model[path][str(index)]['value'] = value
|
||||
else:
|
||||
self._set_temp_value(path, index, value, self.global_model.get('owner', 'tmp'))
|
||||
self.set_dependencies(path, value, index=index)
|
||||
self.do_copy(path, value)
|
||||
if leader_old_value is not undefined and len(leader_old_value) < len(value):
|
||||
# if leader and length is change, display/hide follower from follower's default value
|
||||
index = len(value) - 1
|
||||
parent_path = '.'.join(path.split('.')[:-1])
|
||||
followers = list(self.option(parent_path).list())[1:]
|
||||
for follower in followers:
|
||||
follower_path = follower.option.path()
|
||||
try:
|
||||
follower_value = self.option(follower_path, index).value.get()
|
||||
self.set_dependencies(follower_path, follower_value, None, index)
|
||||
except PropertiesOptionError:
|
||||
pass
|
||||
|
||||
def _set_temp_value(self, path, index, value, owner):
|
||||
if index is not None:
|
||||
@ -958,17 +1105,24 @@ class Config:
|
||||
return value
|
||||
|
||||
def updates_data(self, data):
|
||||
if DEBUG:
|
||||
from pprint import pprint
|
||||
print('====> updates_data')
|
||||
pprint(data)
|
||||
self.updates = []
|
||||
self.temp.clear()
|
||||
self.model = data['model']
|
||||
|
||||
def test_value(self,
|
||||
path: str,
|
||||
index: Optional[int],
|
||||
value: Any,
|
||||
remote: bool):
|
||||
if isinstance(value, list):
|
||||
for val in value:
|
||||
if not self.test_value(path, val, remote):
|
||||
if not self.test_value(path, index, val, remote):
|
||||
if not 'demoting_error_warning' in self.global_model.get('properties', ['demoting_error_warning']):
|
||||
raise ValueError('value {} is not valid for {}'.format(value, path))
|
||||
return False
|
||||
return True
|
||||
else:
|
||||
@ -977,12 +1131,25 @@ class Config:
|
||||
else:
|
||||
if isinstance(value, int):
|
||||
value = str(value)
|
||||
match = self.form[path]['pattern'].search(value)
|
||||
match = self.form[path]['pattern'].search(value) is not None
|
||||
if not remote:
|
||||
if not match:
|
||||
self.temp.setdefault(path, {})['error'] = ['']
|
||||
elif 'error' in self.model[path]:
|
||||
if index is None:
|
||||
self.temp.setdefault(path, {})['error'] = ['']
|
||||
else:
|
||||
self.temp.setdefault(path, {})
|
||||
self.temp[path].setdefault(str(index), {})
|
||||
self.temp[path][str(index)]= ['']
|
||||
elif index is not None and 'error' in self.temp.get(path, {}).get(str(index), {}):
|
||||
del self.temp[path][str(index)]['error']
|
||||
elif 'error' in self.temp.get(path, {}):
|
||||
del self.temp[path]['error']
|
||||
if index is not None and 'error' in self.model.get(path, {}).get(str(index), {}):
|
||||
del self.model[path][str(index)]['error']
|
||||
elif 'error' in self.model.get(path, {}):
|
||||
del self.model[path]['error']
|
||||
if not match and not 'demoting_error_warning' in self.global_model.get('properties', ['demoting_error_warning']):
|
||||
raise ValueError('value {} is not valid for {}'.format(value, path))
|
||||
return match
|
||||
|
||||
def set_dependencies(self,
|
||||
@ -992,30 +1159,43 @@ class Config:
|
||||
index: Optional[int]=None) -> None:
|
||||
dependencies = self.form.get(path, {}).get('dependencies', {})
|
||||
if dependencies:
|
||||
if ori_value in dependencies['expected']:
|
||||
expected = dependencies['expected'][ori_value]
|
||||
if not isinstance(ori_value, list):
|
||||
self._set_dependencies(path, ori_value, dependencies, force_hide, index)
|
||||
else:
|
||||
expected = dependencies['default']
|
||||
for action in ['hide', 'show']:
|
||||
expected_actions = expected.get(action)
|
||||
if expected_actions:
|
||||
if force_hide:
|
||||
hidden = True
|
||||
else:
|
||||
hidden = action == 'hide'
|
||||
for expected_path in expected_actions:
|
||||
if index is not None:
|
||||
self.temp.setdefault(expected_path, {}).setdefault(str(index), {})['hidden'] = hidden
|
||||
for idx, ori_val in enumerate(ori_value):
|
||||
self._set_dependencies(path, ori_val, dependencies, force_hide, idx)
|
||||
|
||||
def _set_dependencies(self,
|
||||
path: str,
|
||||
ori_value: Any,
|
||||
dependencies: Dict,
|
||||
force_hide: bool,
|
||||
index: Optional[int]) -> None:
|
||||
if ori_value in dependencies['expected']:
|
||||
expected = dependencies['expected'][ori_value]
|
||||
else:
|
||||
expected = dependencies['default']
|
||||
for action in ['hide', 'show']:
|
||||
expected_actions = expected.get(action)
|
||||
if expected_actions:
|
||||
if force_hide:
|
||||
display = False
|
||||
else:
|
||||
self.temp.setdefault(expected_path, {})['hidden'] = hidden
|
||||
value = self.get_value(expected_path, index)
|
||||
self.set_dependencies(expected_path, value, hidden, index)
|
||||
display = action == 'show'
|
||||
for expected_path in expected_actions:
|
||||
if index is not None:
|
||||
self.temp.setdefault(expected_path, {}).setdefault(str(index), {})['display'] = display
|
||||
else:
|
||||
self.temp.setdefault(expected_path, {})['display'] = display
|
||||
value = self.get_value(expected_path, index)
|
||||
self.set_dependencies(expected_path, value, not display, index)
|
||||
|
||||
def set_not_equal(self,
|
||||
path: str,
|
||||
value: Any) -> None:
|
||||
not_equal = self.form.get(path, {}).get('not_equal', {})
|
||||
if not_equal:
|
||||
value: Any,
|
||||
index: Optional[int]) -> None:
|
||||
not_equals = self.form.get(path, {}).get('not_equal', [])
|
||||
if not_equals:
|
||||
vals = []
|
||||
opts = []
|
||||
if isinstance(value, list):
|
||||
@ -1025,55 +1205,59 @@ class Config:
|
||||
else:
|
||||
vals.append(value)
|
||||
opts.append(path)
|
||||
for path_ in self.form[path]['not_equal']['options']:
|
||||
schema = self.get_schema(path_)
|
||||
p_value = self.get_value(path_)
|
||||
if isinstance(p_value, list):
|
||||
for val in p_value:
|
||||
vals.append(val)
|
||||
for not_equal in not_equals:
|
||||
for path_ in not_equal['options']:
|
||||
if self.is_hidden(path_, index, permissive=True):
|
||||
raise PropertiesOptionError(None, {'hidden'}, None, opt_type='option')
|
||||
schema = self.get_schema(path_)
|
||||
p_value = self.get_value(path_)
|
||||
if isinstance(p_value, list):
|
||||
for val in p_value:
|
||||
vals.append(val)
|
||||
opts.append(path_)
|
||||
else:
|
||||
vals.append(p_value)
|
||||
opts.append(path_)
|
||||
equal = []
|
||||
warnings_only = not_equal.get('warnings', False)
|
||||
if warnings_only and 'warnings' not in self.global_model.get('properties', []):
|
||||
continue
|
||||
if warnings_only:
|
||||
msg = _('should be different from the value of {}')
|
||||
#msgcurr = _('value for {} should be different')
|
||||
else:
|
||||
vals.append(p_value)
|
||||
opts.append(path_)
|
||||
equal = []
|
||||
warnings_only = self.form[path]['not_equal'].get('warnings', False)
|
||||
if warnings_only:
|
||||
msg = _('should be different from the value of "{}"')
|
||||
msgcurr = _('value for {} should be different')
|
||||
else:
|
||||
msg = _('must be different from the value of "{}"')
|
||||
msgcurr = _('value for {} must be different')
|
||||
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:
|
||||
for opt_ in [opts[idx_inf], opts[idx_inf + idx_sup + 1]]:
|
||||
if opt_ not in equal:
|
||||
equal.append(opt_)
|
||||
if equal:
|
||||
equal_name = {}
|
||||
for opt in equal:
|
||||
schema = self.get_schema(opt)
|
||||
equal_name[opt] = schema['title']
|
||||
for opt_ in equal:
|
||||
msg = _('must be different from the value of {}')
|
||||
#msgcurr = _('value for {} must be different')
|
||||
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:
|
||||
for opt_ in [opts[idx_inf], opts[idx_inf + idx_sup + 1]]:
|
||||
if opt_ not in equal:
|
||||
equal.append(opt_)
|
||||
if equal:
|
||||
equal_name = {}
|
||||
display_equal = []
|
||||
for opt__ in equal:
|
||||
if opt_ != opt__:
|
||||
display_equal.append(equal_name[opt_])
|
||||
display_equal = ', '.join(display_equal)
|
||||
if opt_ == path:
|
||||
msg_ = msgcurr.format(display_equal)
|
||||
else:
|
||||
msg_ = msg.format(display_equal)
|
||||
if warnings_only:
|
||||
self.model[opt_].setdefault('warnings', []).append(msg_)
|
||||
else:
|
||||
self.model[opt_].setdefault('error', []).append(msg_)
|
||||
else:
|
||||
for opt in opts:
|
||||
if 'warnings' in self.model[opt]:
|
||||
del self.model[opt]['warnings']
|
||||
if 'error' in self.model[opt]:
|
||||
del self.model[opt]['error']
|
||||
for opt_ in equal:
|
||||
display_equal.append('"' + self.get_schema(opt_)['title'] + '"')
|
||||
display_equal = display_list(display_equal)
|
||||
#if opt_ == path:
|
||||
# msg_ = msgcurr.format(display_equal)
|
||||
#else:
|
||||
msg_ = msg.format(display_equal)
|
||||
for path_ in not_equal['options'] + [path]:
|
||||
if path_ not in self.model:
|
||||
self.model[path_] = {}
|
||||
model = self.model[path_]
|
||||
if index is not None:
|
||||
if index not in model:
|
||||
model[str(index)] = {}
|
||||
model = model[str(index)]
|
||||
if warnings_only:
|
||||
model.setdefault('warnings', []).append(msg_)
|
||||
else:
|
||||
if 'demoting_error_warning' not in self.global_model.get('properties', []):
|
||||
raise ValueError(msg_)
|
||||
model.setdefault('error', []).append(msg_)
|
||||
|
||||
def do_copy(self,
|
||||
path: str,
|
||||
@ -1092,6 +1276,33 @@ class Config:
|
||||
remote = self.form.get(opt, {}).get('remote', False)
|
||||
self.updates_value('modify', opt, None, value, remote, True)
|
||||
|
||||
def _check_raises_warnings(self, path, index, value, type, withwarning=True):
|
||||
model = self.model.get(path, {})
|
||||
if index is not None:
|
||||
model = model.get(str(index), {})
|
||||
for err in model.get('error', []):
|
||||
if 'demoting_error_warning' in self.global_model.get('properties', []):
|
||||
warnings.warn_explicit(ValueErrorWarning(value,
|
||||
type,
|
||||
Option(path, path),
|
||||
'{0}'.format(err),
|
||||
index),
|
||||
ValueErrorWarning,
|
||||
'Option', 0)
|
||||
else:
|
||||
del model['error']
|
||||
raise ValueError(err)
|
||||
|
||||
if withwarning and model.get('warnings'):
|
||||
for warn in model.get('warnings'):
|
||||
warnings.warn_explicit(ValueErrorWarning(value,
|
||||
type,
|
||||
Option(path, path),
|
||||
'{0}'.format(warn),
|
||||
index),
|
||||
ValueErrorWarning,
|
||||
'Option', 0)
|
||||
|
||||
def send_data(self,
|
||||
updates):
|
||||
raise NotImplementedError('please implement send_data method')
|
||||
|
@ -1,5 +1,5 @@
|
||||
try:
|
||||
from tiramisu.error import APIError, ValueWarning, ValueOptionError, ValueErrorWarning, PropertiesOptionError
|
||||
from tiramisu.error import APIError, ValueWarning, ValueOptionError, ValueErrorWarning, PropertiesOptionError, ConfigError, display_list
|
||||
except ModuleNotFoundError:
|
||||
import weakref
|
||||
from .i18n import _
|
||||
@ -34,6 +34,18 @@ except ModuleNotFoundError:
|
||||
last = '"{}"'.format(last)
|
||||
return ', '.join(lst_) + _(' {} ').format(separator) + '{}'.format(last)
|
||||
|
||||
#____________________________________________________________
|
||||
# Exceptions for a Config
|
||||
class ConfigError(Exception):
|
||||
"""attempt to change an option's owner without a value
|
||||
or in case of `_cfgimpl_descr` is None
|
||||
or if a calculation cannot be carried out"""
|
||||
def __init__(self,
|
||||
exp,
|
||||
ori_err=None):
|
||||
super().__init__(exp)
|
||||
self.ori_err = ori_err
|
||||
|
||||
class APIError(Exception):
|
||||
pass
|
||||
|
||||
@ -42,20 +54,25 @@ except ModuleNotFoundError:
|
||||
val,
|
||||
display_type,
|
||||
opt,
|
||||
err_msg):
|
||||
err_msg,
|
||||
index):
|
||||
self.val = val
|
||||
self.display_type = display_type
|
||||
self.opt = weakref.ref(opt)
|
||||
self.err_msg = err_msg
|
||||
self.index = index
|
||||
super().__init__(self.err_msg)
|
||||
|
||||
def __str__(self):
|
||||
try:
|
||||
msg = self.prefix
|
||||
except AttributeError:
|
||||
self.prefix = self.tmpl.format(self.val,
|
||||
self.display_type,
|
||||
self.opt().impl_get_display_name())
|
||||
if self.opt() is None:
|
||||
self.prefix = ''
|
||||
else:
|
||||
self.prefix = self.tmpl.format(self.val,
|
||||
self.display_type,
|
||||
self.opt().impl_get_display_name())
|
||||
msg = self.prefix
|
||||
if self.err_msg:
|
||||
if msg:
|
||||
@ -112,6 +129,8 @@ except ModuleNotFoundError:
|
||||
# this part is a bit slow, so only execute when display
|
||||
if self.msg:
|
||||
return self.msg
|
||||
if self._option_bag is None:
|
||||
return "unknown error"
|
||||
req = self._settings.apply_requires(self._option_bag,
|
||||
True)
|
||||
# if req != {} or self._orig_opt is not None:
|
||||
|
Reference in New Issue
Block a user