symplify tiramisu/option/option.py

This commit is contained in:
Emmanuel Garette 2018-11-15 18:35:14 +01:00
parent 92b469bd43
commit f6bdd0c17e
13 changed files with 115 additions and 119 deletions

View File

@ -19,7 +19,7 @@
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -30,8 +30,8 @@ class BoolOption(Option):
_display_name = _('boolean') _display_name = _('boolean')
def _validate(self, def _validate(self,
value, value: bool,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, bool): if not isinstance(value, bool):
raise ValueError() raise ValueError()

View File

@ -21,7 +21,7 @@
from IPy import IP from IPy import IP
from ..error import ConfigError from ..error import ConfigError
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -31,9 +31,9 @@ class BroadcastOption(Option):
_display_name = _('broadcast address') _display_name = _('broadcast address')
def _validate(self, def _validate(self,
value, value: str,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))
if value.count('.') != 3: if value.count('.') != 3:

View File

@ -20,7 +20,7 @@
# ____________________________________________________________ # ____________________________________________________________
from datetime import datetime from datetime import datetime
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -30,9 +30,9 @@ class DateOption(Option):
_display_name = _('date') _display_name = _('date')
def _validate(self, def _validate(self,
value, value: str,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))
try: try:

View File

@ -21,7 +21,7 @@
import re import re
from IPy import IP from IPy import IP
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -98,9 +98,9 @@ class DomainnameOption(Option):
return 63 return 63
def _validate(self, def _validate(self,
value, value: str,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
def _valid_length(val): def _valid_length(val):
if len(val) < 1: if len(val) < 1:
raise ValueError(_("invalid length (min 1)")) raise ValueError(_("invalid length (min 1)"))

View File

@ -19,7 +19,7 @@
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -30,8 +30,8 @@ class FloatOption(Option):
_display_name = _('float') _display_name = _('float')
def _validate(self, def _validate(self,
value, value: float,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, float): if not isinstance(value, float):
raise ValueError() raise ValueError()

View File

@ -19,7 +19,7 @@
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -44,9 +44,9 @@ class IntOption(Option):
def _validate(self, def _validate(self,
value, value: int,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, int): if not isinstance(value, int):
raise ValueError() raise ValueError()
min_number = self.impl_get_extra('min_number') min_number = self.impl_get_extra('min_number')

View File

@ -21,7 +21,7 @@
from IPy import IP from IPy import IP
from ..error import ConfigError from ..error import ConfigError
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -63,9 +63,9 @@ class IPOption(Option):
extra=extra) extra=extra)
def _validate(self, def _validate(self,
value, value: str,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
# sometimes an ip term starts with a zero # sometimes an ip term starts with a zero
# but this does not fit in some case, for example bind does not like it # but this does not fit in some case, for example bind does not like it
if not isinstance(value, str): if not isinstance(value, str):

View File

@ -21,7 +21,7 @@
from IPy import IP from IPy import IP
from ..error import ConfigError from ..error import ConfigError
from ..setting import undefined from ..setting import undefined, OptionBag, Undefined
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -33,8 +33,8 @@ class NetmaskOption(Option):
def _validate(self, def _validate(self,
value: str, value: str,
*args, option_bag: OptionBag,
**kwargs) -> None: current_opt: Option=Undefined) -> None:
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))
if value.count('.') != 3: if value.count('.') != 3:

View File

@ -21,11 +21,11 @@
# ____________________________________________________________ # ____________________________________________________________
import warnings import warnings
import weakref import weakref
from typing import Any, List, Callable, Optional from typing import Any, List, Callable, Optional, Dict, Union, Tuple
from .baseoption import BaseOption, submulti, STATIC_TUPLE from .baseoption import BaseOption, submulti, STATIC_TUPLE
from ..i18n import _ from ..i18n import _
from ..setting import log, undefined, OptionBag from ..setting import log, undefined, OptionBag, Undefined
from ..autolib import carry_out_calculation from ..autolib import carry_out_calculation
from ..error import (ConfigError, ValueWarning, PropertiesOptionError, from ..error import (ConfigError, ValueWarning, PropertiesOptionError,
ValueOptionError, display_list) ValueOptionError, display_list)
@ -58,22 +58,21 @@ class Option(BaseOption):
) )
_empty = '' _empty = ''
def __init__(self, def __init__(self,
name, name: str,
doc, doc: str,
default=undefined, default: Any=undefined,
default_multi=None, default_multi: Any=None,
requires=None, requires: List[Dict]=None,
multi=False, multi: bool=False,
unique=undefined, unique: bool=undefined,
callback=None, callback: Optional[Callable]=None,
callback_params=None, callback_params: Optional[Params]=None,
validator=None, validator: Optional[Callable]=None,
validator_params=None, validator_params: Optional[Params]=None,
properties=None, properties: Optional[List[str]]=None,
warnings_only=False, warnings_only: bool=False,
extra=None, extra: Optional[Dict]=None,
allow_empty_list=undefined): allow_empty_list: bool=undefined) -> None:
_setattr = object.__setattr__ _setattr = object.__setattr__
if not multi and default_multi is not None: if not multi and default_multi is not None:
raise ValueError(_("default_multi is set whereas multi is False" raise ValueError(_("default_multi is set whereas multi is False"
@ -165,22 +164,22 @@ class Option(BaseOption):
#__________________________________________________________________________ #__________________________________________________________________________
# option's information # option's information
def impl_is_multi(self): def impl_is_multi(self) -> bool:
return getattr(self, '_multi', 1) != 1 return getattr(self, '_multi', 1) != 1
def impl_is_submulti(self): def impl_is_submulti(self) -> bool:
return getattr(self, '_multi', 1) == 2 return getattr(self, '_multi', 1) == 2
def impl_is_unique(self): def impl_is_unique(self) -> bool:
return getattr(self, '_unique', False) return getattr(self, '_unique', False)
def impl_allow_empty_list(self): def impl_allow_empty_list(self) -> Union[Undefined, bool]:
return getattr(self, '_allow_empty_list', undefined) return getattr(self, '_allow_empty_list', undefined)
def impl_is_dynsymlinkoption(self): def impl_is_dynsymlinkoption(self) -> bool:
return False return False
def impl_getdefault(self): def impl_getdefault(self) -> Any:
"accessing the default value" "accessing the default value"
is_multi = self.impl_is_multi() is_multi = self.impl_is_multi()
default = getattr(self, '_default', undefined) default = getattr(self, '_default', undefined)
@ -194,7 +193,7 @@ class Option(BaseOption):
default = list(default) default = list(default)
return default return default
def impl_getdefault_multi(self): def impl_getdefault_multi(self) -> Any:
"accessing the default value for a multi" "accessing the default value for a multi"
if self.impl_is_submulti(): if self.impl_is_submulti():
default_value = [] default_value = []
@ -203,7 +202,7 @@ class Option(BaseOption):
return getattr(self, '_default_multi', default_value) return getattr(self, '_default_multi', default_value)
def impl_get_extra(self, def impl_get_extra(self,
key): key: str) -> Any:
extra = getattr(self, '_extra', {}) extra = getattr(self, '_extra', {})
if isinstance(extra, tuple): if isinstance(extra, tuple):
if key in extra[0]: if key in extra[0]:
@ -215,7 +214,7 @@ class Option(BaseOption):
#__________________________________________________________________________ #__________________________________________________________________________
# validator # validator
def impl_get_validator(self): def impl_get_validator(self) -> Tuple[Callable, Params]:
val = getattr(self, '_val_call', (None,))[0] val = getattr(self, '_val_call', (None,))[0]
if val is None: if val is None:
ret_val = (None, None) ret_val = (None, None)
@ -226,9 +225,9 @@ class Option(BaseOption):
return ret_val return ret_val
def impl_validate(self, def impl_validate(self,
value, value: Any,
option_bag, option_bag: OptionBag,
check_error=True): check_error: bool=True) -> None:
""" """
""" """
config_bag = option_bag.config_bag config_bag = option_bag.config_bag
@ -353,12 +352,8 @@ class Option(BaseOption):
'{0}'.format(err)) '{0}'.format(err))
def _validate_calculator(self, def _validate_calculator(self,
callback, callback: Callable,
callback_params): callback_params: Optional[Params]=None) -> None:
"""callback_params:
* None
* {'': ((option, permissive),), 'ip': ((None,), (option, permissive))
"""
if callback is None: if callback is None:
return return
default_multi = getattr(self, '_default_multi', None) default_multi = getattr(self, '_default_multi', None)
@ -370,14 +365,15 @@ class Option(BaseOption):
'is calculated').format(self.impl_getname())) 'is calculated').format(self.impl_getname()))
def _second_level_validation(self, def _second_level_validation(self,
value, value: Any,
warnings_only): warnings_only: bool) -> None:
pass pass
#__________________________________________________________________________ #__________________________________________________________________________
# master/slaves # master/slaves
def impl_is_master_slaves(self, type_='both'): def impl_is_master_slaves(self,
type_: str='both') -> bool:
master_slaves = self.impl_get_master_slaves() master_slaves = self.impl_get_master_slaves()
if master_slaves is not None: if master_slaves is not None:
if type_ == 'both': if type_ == 'both':
@ -397,9 +393,9 @@ class Option(BaseOption):
# consistencies # consistencies
def impl_add_consistency(self, def impl_add_consistency(self,
func, func: str,
*other_opts, *other_opts,
**params): **params) -> None:
"""Add consistency means that value will be validate with other_opts """Add consistency means that value will be validate with other_opts
option's values. option's values.
@ -453,9 +449,9 @@ class Option(BaseOption):
opt._add_dependency(self) opt._add_dependency(self)
def _add_consistency(self, def _add_consistency(self,
func, func: str,
all_cons_opts, all_cons_opts: List[BaseOption],
params): params: Dict) -> None:
cons = (-1, func, all_cons_opts, params) cons = (-1, func, all_cons_opts, params)
consistencies = getattr(self, '_consistencies', None) consistencies = getattr(self, '_consistencies', None)
if consistencies is None: if consistencies is None:
@ -466,17 +462,17 @@ class Option(BaseOption):
def get_consistencies(self): def get_consistencies(self):
return getattr(self, '_consistencies', STATIC_TUPLE) return getattr(self, '_consistencies', STATIC_TUPLE)
def has_consistencies(self, context): def has_consistencies(self, context) -> bool:
descr = context.cfgimpl_get_description() descr = context.cfgimpl_get_description()
if getattr(descr, '_cache_consistencies', None) is None: if getattr(descr, '_cache_consistencies', None) is None:
return False return False
return self in descr._cache_consistencies return self in descr._cache_consistencies
def valid_consistency(self, def valid_consistency(self,
option_bag, option_bag: OptionBag,
value, value: Any,
check_error, check_error: bool,
option_warnings_only): option_warnings_only: bool) -> None:
if option_bag.config_bag is not undefined: if option_bag.config_bag is not undefined:
descr = option_bag.config_bag.context.cfgimpl_get_description() descr = option_bag.config_bag.context.cfgimpl_get_description()
# no consistency found at all # no consistency found at all
@ -529,9 +525,9 @@ class Option(BaseOption):
option_bag.fromconsistency = [] option_bag.fromconsistency = []
def _valid_consistencies(self, def _valid_consistencies(self,
other_opts, other_opts: List[BaseOption],
init=True, init: bool=True,
func=None): func: Optional[str]=None) -> None:
if self.issubdyn(): if self.issubdyn():
dynod = self.getsubdyn() dynod = self.getsubdyn()
else: else:
@ -561,10 +557,9 @@ class Option(BaseOption):
if is_multi != opt.impl_is_multi(): if is_multi != opt.impl_is_multi():
raise ConfigError(_('every options in consistency must be ' raise ConfigError(_('every options in consistency must be '
'multi or none')) 'multi or none'))
if init: # FIXME
# FIXME if init and func != 'not_equal':
if func != 'not_equal': opt._has_dependency = True
opt._has_dependency = True
def launch_consistency(self, def launch_consistency(self,
current_opt: BaseOption, current_opt: BaseOption,
@ -574,7 +569,7 @@ class Option(BaseOption):
value: Any, value: Any,
opts: List[BaseOption], opts: List[BaseOption],
warnings_only: bool, warnings_only: bool,
transitive: bool): transitive: bool) -> None:
"""Launch consistency now """Launch consistency now
""" """
all_cons_vals = [] all_cons_vals = []
@ -642,11 +637,11 @@ class Option(BaseOption):
raise err raise err
def get_consistency_value(self, def get_consistency_value(self,
option_bag, option_bag: OptionBag,
current_option, current_option: BaseOption,
cons_id, cons_id: int,
value, value: Any,
func): func: str) -> Any:
if option_bag.ori_option == current_option: if option_bag.ori_option == current_option:
# orig_option is current option # orig_option is current option
# we have already value, so use it # we have already value, so use it
@ -682,11 +677,11 @@ class Option(BaseOption):
return current_value return current_value
def _cons_not_equal(self, def _cons_not_equal(self,
current_opt, current_opt: BaseOption,
opts, opts: List[BaseOption],
vals, vals: List[Any],
warnings_only, warnings_only: bool,
context): context) -> None:
equal = [] equal = []
is_current = False is_current = False
for idx_inf, val_inf in enumerate(vals): for idx_inf, val_inf in enumerate(vals):
@ -726,9 +721,9 @@ class RegexpOption(Option):
__slots__ = tuple() __slots__ = tuple()
def _validate(self, def _validate(self,
value, value: Any,
*args, option_bag: OptionBag,
**kwargs): current_opt: BaseOption=Undefined) -> None:
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))
match = self._regexp.search(value) match = self._regexp.search(value)

View File

@ -19,7 +19,7 @@
# the whole pypy projet is under MIT licence # the whole pypy projet is under MIT licence
# ____________________________________________________________ # ____________________________________________________________
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -30,8 +30,8 @@ class PasswordOption(Option):
_display_name = _('password') _display_name = _('password')
def _validate(self, def _validate(self,
value, value: str,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))

View File

@ -20,8 +20,9 @@
# ____________________________________________________________ # ____________________________________________________________
import re import re
import sys import sys
from typing import Union
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -97,9 +98,9 @@ class PortOption(Option):
extra=extra) extra=extra)
def _validate(self, def _validate(self,
value, value: Union[int,str],
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if isinstance(value, int): if isinstance(value, int):
value = str(value) value = str(value)
if not isinstance(value, str): if not isinstance(value, str):

View File

@ -20,7 +20,7 @@
# ____________________________________________________________ # ____________________________________________________________
import sys import sys
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
@ -31,9 +31,9 @@ class StrOption(Option):
_display_name = _('string') _display_name = _('string')
def _validate(self, def _validate(self,
value, value: str,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError() raise ValueError()

View File

@ -20,7 +20,7 @@
# ____________________________________________________________ # ____________________________________________________________
import re import re
from ..setting import undefined from ..setting import undefined, Undefined, OptionBag
from ..i18n import _ from ..i18n import _
from .option import Option from .option import Option
from .domainnameoption import DomainnameOption from .domainnameoption import DomainnameOption
@ -33,9 +33,9 @@ class URLOption(DomainnameOption):
_display_name = _('URL') _display_name = _('URL')
def _validate(self, def _validate(self,
value, value: str,
*args, option_bag: OptionBag,
**kwargs): current_opt: Option=Undefined) -> None:
if not isinstance(value, str): if not isinstance(value, str):
raise ValueError(_('invalid string')) raise ValueError(_('invalid string'))
match = self.proto_re.search(value) match = self.proto_re.search(value)
@ -62,8 +62,8 @@ class URLOption(DomainnameOption):
'65536')) '65536'))
# validate domainname # validate domainname
super(URLOption, self)._validate(domain, super(URLOption, self)._validate(domain,
*args, option_bag,
**kwargs) current_opt)
super(URLOption, self)._second_level_validation(domain, False) super(URLOption, self)._second_level_validation(domain, False)
# validate file # validate file
if files is not None and files != '' and not self.path_re.search(files): if files is not None and files != '' and not self.path_re.search(files):