1 # -*- coding: utf-8 -*-
2 "takes care of the option's values and multi values"
3 # Copyright (C) 2013-2014 Team tiramisu (see AUTHORS for all contributors)
5 # This program is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by the
7 # Free Software Foundation, either version 3 of the License, or (at your
8 # option) any later version.
10 # This program is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 # ____________________________________________________________
21 from .error import ConfigError, SlaveError, PropertiesOptionError
22 from .setting import owners, expires_time, undefined
23 from .autolib import carry_out_calculation
25 from .option import SymLinkOption, DynSymLinkOption, Option
29 """The `Config`'s root is indeed in charge of the `Option()`'s values,
30 but the values are physicaly located here, in `Values`, wich is also
31 responsible of a caching utility.
33 __slots__ = ('context', '_p_', '__weakref__')
35 def __init__(self, context, storage):
37 Initializes the values's dict.
39 :param context: the context is the home config's values
42 self.context = weakref.ref(context)
43 # the storage type is dictionary or sqlite3
46 def _getcontext(self):
47 """context could be None, we need to test it
48 context is None only if all reference to `Config` object is deleted
49 (for example we delete a `Config` and we manipulate a reference to
50 old `SubConfig`, `Values`, `Multi` or `Settings`)
52 context = self.context()
53 if context is None: # pragma: optional cover
54 raise ConfigError(_('the context does not exist anymore'))
57 def _get_multi(self, opt, path):
58 return Multi([], self.context, opt, path)
60 def _getdefaultvalue(self, opt, path, with_meta, index, submulti_index,
62 # if value has callback and is not set
63 if opt.impl_has_callback():
64 callback, callback_params = opt.impl_get_callback()
65 value = carry_out_calculation(opt, context=self._getcontext(),
67 callback_params=callback_params,
69 returns_raise=returns_raise)
70 if isinstance(value, list) and index is not None:
71 #if return a list and index is set, return value only if
72 #it's a submulti without submulti_index and without list of list
73 if opt.impl_is_submulti() and submulti_index is undefined and \
74 (len(value) == 0 or not isinstance(value[0], list)):
79 meta = self._getcontext().cfgimpl_get_meta()
81 value = meta.cfgimpl_get_values(
82 )._get_cached_value(opt, path, index=index, submulti_index=submulti_index,
83 from_masterslave=True, returns_raise=True)
84 if isinstance(value, Exception):
85 if not isinstance(value, PropertiesOptionError):
88 if isinstance(value, Multi):
94 # now try to get default value
95 value = opt.impl_getdefault()
96 if opt.impl_is_multi() and index is not None:
98 value = opt.impl_getdefault_multi()
100 if len(value) > index:
103 value = opt.impl_getdefault_multi()
106 def _getvalue(self, opt, path, self_properties, index, submulti_index,
107 with_meta, masterlen, session):
108 """actually retrieves the value
110 :param opt: the `option.Option()` object
111 :returns: the option's value (or the default value if not set)
113 force_default = 'frozen' in self_properties and \
114 'force_default_on_freeze' in self_properties
116 is_default = self._is_default_owner(opt, path, session,
117 validate_properties=False,
119 self_properties=self_properties,
121 if not is_default and not force_default:
122 if opt.impl_is_master_slaves('slave'):
123 return self._p_.getvalue(path, session, index)
125 value = self._p_.getvalue(path, session)
126 if index is not None:
127 if len(value) > index:
129 #value is smaller than expected
130 #so return default value
133 return self._getdefaultvalue(opt, path, with_meta, index,
134 submulti_index, True)
136 def get_modified_values(self):
137 return self._p_.get_modified_values()
139 def __contains__(self, opt):
141 implements the 'in' keyword syntax in order provide a pythonic way
142 to kow if an option have a value
144 :param opt: the `option.Option()` object
146 path = opt.impl_getpath(self._getcontext())
147 return self._contains(path)
149 def _contains(self, path, session=None):
151 session = self._p_.getsession()
152 return self._p_.hasvalue(path, session)
154 def __delitem__(self, opt):
155 """overrides the builtins `del()` instructions"""
158 def reset(self, opt, path=None, validate=True, _setting_properties=None):
159 context = self._getcontext()
160 setting = context.cfgimpl_get_settings()
162 path = opt.impl_getpath(context)
163 if _setting_properties is None:
164 _setting_properties = setting._getproperties(read_write=False)
165 session = self._p_.getsession()
166 hasvalue = self._contains(path, session)
168 if validate and hasvalue and 'validator' in _setting_properties:
169 session = context.cfgimpl_get_values()._p_.getsession()
170 fake_context = context._gen_fake_values(session)
171 fake_value = fake_context.cfgimpl_get_values()
172 fake_value.reset(opt, path, validate=False)
173 fake_value._get_cached_value(opt, path,
174 setting_properties=_setting_properties,
176 if opt.impl_is_master_slaves('master'):
177 opt.impl_get_master_slaves().reset(opt, self, _setting_properties)
179 if 'force_store_value' in setting._getproperties(opt=opt,
181 setting_properties=_setting_properties,
183 apply_requires=False):
184 value = self._getdefaultvalue(opt, path, True, undefined, undefined, False)
185 self._setvalue(opt, path, value, force_owner=owners.forced)
187 self._p_.resetvalue(path, session)
188 context.cfgimpl_reset_cache()
190 def _isempty(self, opt, value, force_allow_empty_list=False, index=None):
191 "convenience method to know if an option is empty"
192 if value is undefined:
196 if index in [None, undefined] and opt.impl_is_multi():
197 if force_allow_empty_list:
198 allow_empty_list = True
200 allow_empty_list = opt.impl_allow_empty_list()
201 if allow_empty_list is undefined:
202 if opt.impl_is_master_slaves('slave'):
203 allow_empty_list = True
205 allow_empty_list = False
206 isempty = (not allow_empty_list and value == []) or \
207 None in value or empty in value
209 isempty = value is None or value == empty
212 def __getitem__(self, opt):
213 "enables us to use the pythonic dictionary-like access to values"
214 return self.getitem(opt)
216 def getitem(self, opt, validate=True, force_permissive=False):
219 return self._get_cached_value(opt, validate=validate,
220 force_permissive=force_permissive)
222 def _get_cached_value(self, opt, path=None, validate=True,
223 force_permissive=False, trusted_cached_properties=True,
224 validate_properties=True,
225 setting_properties=undefined, self_properties=undefined,
226 index=None, submulti_index=undefined, from_masterslave=False,
227 with_meta=True, masterlen=undefined, check_frozen=False,
228 returns_raise=False, session=None):
229 context = self._getcontext()
230 settings = context.cfgimpl_get_settings()
232 path = opt.impl_getpath(context)
234 if setting_properties is undefined:
235 setting_properties = settings._getproperties(read_write=False)
236 if self_properties is undefined:
237 self_properties = settings._getproperties(opt, path,
239 setting_properties=setting_properties,
241 if 'cache' in setting_properties and self._p_.hascache(path, index):
242 if 'expire' in setting_properties:
244 is_cached, value = self._p_.getcache(path, ntime, index)
246 if opt.impl_is_multi() and not isinstance(value, Multi) and index is None:
247 value = Multi(value, self.context, opt, path)
248 if not trusted_cached_properties:
249 # revalidate properties (because of not default properties)
250 props = settings.validate_properties(opt, False, False, value=value,
252 force_permissive=force_permissive,
253 setting_properties=setting_properties,
254 self_properties=self_properties,
263 session = self._p_.getsession()
264 if not from_masterslave and opt.impl_is_master_slaves():
265 val = opt.impl_get_master_slaves().getitem(self, opt, path,
268 trusted_cached_properties,
271 setting_properties=setting_properties,
273 self_properties=self_properties,
274 returns_raise=returns_raise)
276 val = self._get_validated_value(opt, path, validate,
279 setting_properties=setting_properties,
280 self_properties=self_properties,
284 submulti_index=submulti_index,
285 check_frozen=check_frozen,
286 returns_raise=returns_raise,
288 if isinstance(val, Exception):
293 # cache doesn't work with SubMulti yet
294 if not isinstance(val, SubMulti) and 'cache' in setting_properties and \
295 validate and validate_properties and force_permissive is False \
296 and trusted_cached_properties is True:
297 if 'expire' in setting_properties:
300 ntime = ntime + expires_time
301 self._p_.setcache(path, val, ntime, index)
304 def _get_validated_value(self, opt, path, validate, force_permissive,
306 index=None, submulti_index=undefined,
307 with_meta=True, setting_properties=undefined,
308 self_properties=undefined, masterlen=undefined,
309 check_frozen=False, returns_raise=False,
311 """same has getitem but don't touch the cache
312 index is None for slave value, if value returned is not a list, just return []
314 context = self._getcontext()
315 setting = context.cfgimpl_get_settings()
316 if setting_properties is undefined:
317 setting_properties = setting._getproperties(read_write=False)
318 if self_properties is undefined:
319 self_properties = setting._getproperties(opt, path, read_write=False, index=index)
322 session = self._p_.getsession()
323 value = self._getvalue(opt, path, self_properties, index, submulti_index,
324 with_meta, masterlen, session)
325 if isinstance(value, Exception):
326 if isinstance(value, ConfigError):
327 # For calculating properties, we need value (ie for mandatory
329 # If value is calculating with a PropertiesOptionError's option
330 # _getvalue raise a ConfigError.
331 # We can not raise ConfigError if this option should raise
332 # PropertiesOptionError too. So we get config_error and raise
333 # ConfigError if properties did not raise.
335 # value is not set, for 'undefined' (cannot set None because of
336 # mandatory property)
341 if index is undefined:
345 if opt.impl_is_multi():
346 if force_index is None:
347 value = Multi(value, self.context, opt, path)
348 elif opt.impl_is_submulti() and submulti_index is undefined:
349 value = SubMulti(value, self.context, opt, path,
353 if submulti_index is undefined:
354 force_submulti_index = None
356 force_submulti_index = submulti_index
357 err = opt.impl_validate(value, context,
358 'validator' in setting_properties,
359 force_index=force_index,
360 force_submulti_index=force_submulti_index)
365 if validate_properties:
366 if config_error is not None:
367 # should not raise PropertiesOptionError if option is
369 val_props = undefined
372 props = setting.validate_properties(opt, False, check_frozen, value=val_props,
374 force_permissive=force_permissive,
375 setting_properties=setting_properties,
376 self_properties=self_properties,
383 if config_error is not None:
390 def __setitem__(self, opt, value): # pragma: optional cover
391 raise ConfigError(_('you should only set value with config'))
393 def setitem(self, opt, value, path, force_permissive=False,
394 check_frozen=True, not_raises=False):
395 # check_frozen is, for example, used with "force_store_value"
396 # user didn't change value, so not write
398 context = self._getcontext()
399 setting_properties = context.cfgimpl_get_settings()._getproperties(read_write=False)
400 if 'validator' in setting_properties:
401 session = context.cfgimpl_get_values()._p_.getsession()
402 fake_context = context._gen_fake_values(session)
403 fake_values = fake_context.cfgimpl_get_values()
404 fake_values._setvalue(opt, path, value)
405 props = fake_values.validate(opt, value, path,
406 check_frozen=check_frozen,
407 force_permissive=force_permissive,
408 setting_properties=setting_properties,
409 session=session, not_raises=not_raises)
410 if props and not_raises:
412 err = opt.impl_validate(value, fake_context)
415 self._setvalue(opt, path, value)
417 def _setvalue(self, opt, path, value, force_owner=undefined, index=None):
418 context = self._getcontext()
419 context.cfgimpl_reset_cache()
420 if force_owner is undefined:
421 owner = context.cfgimpl_get_settings().getowner()
424 # in storage, value must not be a multi
425 if isinstance(value, Multi):
427 if opt.impl_is_submulti():
428 for idx, val in enumerate(value):
429 if isinstance(val, SubMulti):
430 value[idx] = list(val)
431 session = self._p_.getsession()
432 #FIXME pourquoi là et pas dans masterslaves ??
433 if opt.impl_is_master_slaves('slave'):
434 if index is not None:
435 self._p_.setvalue(path, value[index], owner, index, session)
437 self._p_.resetvalue(path, session)
438 for idx, val in enumerate(value):
439 self._p_.setvalue(path, val, owner, idx, session)
441 self._p_.setvalue(path, value, owner, None, session)
444 def validate(self, opt, value, path, check_frozen=True, force_permissive=False,
445 setting_properties=undefined, valid_masterslave=True,
446 not_raises=False, returns_raise=False, session=None):
447 if valid_masterslave and opt.impl_is_master_slaves():
449 session = self._p_.getsession()
450 opt.impl_get_master_slaves().validate(self, opt, value, path, returns_raise, session)
451 props = self._getcontext().cfgimpl_get_settings().validate_properties(opt,
456 force_permissive=force_permissive,
457 setting_properties=setting_properties)
463 def _is_meta(self, opt, path, session):
464 context = self._getcontext()
465 setting = context.cfgimpl_get_settings()
466 self_properties = setting._getproperties(opt, path, read_write=False)
467 if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
469 if self._p_.getowner(path, owners.default, session, only_default=True) is not owners.default:
471 if context.cfgimpl_get_meta() is not None:
475 def getowner(self, opt, index=None, force_permissive=False, session=None):
477 retrieves the option's owner
479 :param opt: the `option.Option` object
480 :param force_permissive: behaves as if the permissive property
482 :returns: a `setting.owners.Owner` object
484 if isinstance(opt, SymLinkOption) and \
485 not isinstance(opt, DynSymLinkOption):
486 opt = opt._impl_getopt()
487 path = opt.impl_getpath(self._getcontext())
488 return self._getowner(opt, path, session, index=index, force_permissive=force_permissive)
490 def _getowner(self, opt, path, session, validate_properties=True,
491 force_permissive=False, validate_meta=undefined,
492 self_properties=undefined, only_default=False,
494 """get owner of an option
497 session = self._p_.getsession()
498 if not isinstance(opt, Option) and not isinstance(opt,
500 raise ConfigError(_('owner only avalaible for an option'))
501 context = self._getcontext()
502 if self_properties is undefined:
503 self_properties = context.cfgimpl_get_settings()._getproperties(
504 opt, path, read_write=False)
505 if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
506 return owners.default
507 if validate_properties:
508 self._get_cached_value(opt, path, True, force_permissive, None, True,
509 self_properties=self_properties, session=session)
510 owner = self._p_.getowner(path, owners.default, session, only_default=only_default, index=index)
511 if validate_meta is undefined:
512 if opt.impl_is_master_slaves('slave'):
513 master = opt.impl_get_master_slaves().getmaster(opt)
514 masterp = master.impl_getpath(context)
515 validate_meta = self._is_meta(opt, masterp, session)
519 meta = context.cfgimpl_get_meta()
520 if owner is owners.default and meta is not None:
521 owner = meta.cfgimpl_get_values()._getowner(opt, path, session,
522 validate_properties=validate_properties,
523 force_permissive=force_permissive,
524 self_properties=self_properties,
525 only_default=only_default, index=index)
528 def setowner(self, opt, owner, index=None):
530 sets a owner to an option
532 :param opt: the `option.Option` object
533 :param owner: a valid owner, that is a `setting.owners.Owner` object
535 if not isinstance(owner, owners.Owner): # pragma: optional cover
536 raise TypeError(_("invalid generic owner {0}").format(str(owner)))
538 path = opt.impl_getpath(self._getcontext())
539 session = self._p_.getsession()
540 if not self._p_.hasvalue(path, session): # pragma: optional cover
541 raise ConfigError(_('no value for {0} cannot change owner to {1}'
542 '').format(path, owner))
543 props = self._getcontext().cfgimpl_get_settings().validate_properties(opt,
550 self._p_.setowner(path, owner, session, index=index)
552 def is_default_owner(self, opt, validate_properties=True,
553 validate_meta=True, index=None,
554 force_permissive=False):
556 :param config: *must* be only the **parent** config
557 (not the toplevel config)
560 path = opt.impl_getpath(self._getcontext())
561 return self._is_default_owner(opt, path, session=None,
562 validate_properties=validate_properties,
563 validate_meta=validate_meta, index=index,
564 force_permissive=force_permissive)
566 def _is_default_owner(self, opt, path, session, validate_properties=True,
567 validate_meta=True, self_properties=undefined,
568 index=None, force_permissive=False):
569 if not opt.impl_is_master_slaves('slave'):
571 d = self._getowner(opt, path, session, validate_properties=validate_properties,
572 validate_meta=validate_meta,
573 self_properties=self_properties, only_default=True,
574 index=index, force_permissive=force_permissive)
575 return d == owners.default
577 def reset_cache(self, only_expired):
579 clears the cache if necessary
582 self._p_.reset_expired_cache(int(time()))
584 self._p_.reset_all_cache()
587 def set_information(self, key, value):
588 """updates the information's attribute
590 :param key: information's key (ex: "help", "doc"
591 :param value: information's value (ex: "the help string")
593 self._p_.set_information(key, value)
595 def get_information(self, key, default=undefined):
596 """retrieves one information's item
598 :param key: the item string (ex: "help")
600 return self._p_.get_information(key, default)
602 def mandatory_warnings(self, force_permissive=False, validate=True):
603 """convenience function to trace Options that are mandatory and
604 where no value has been set
606 :param force_permissive: do raise with permissives properties
607 :type force_permissive: `bool`
608 :param validate: validate value when calculating properties
609 :type validate: `bool`
611 :returns: generator of mandatory Option's path
613 context = self._getcontext()
614 settings = context.cfgimpl_get_settings()
615 setting_properties = context.cfgimpl_get_settings()._getproperties()
616 setting_properties.add('mandatory')
618 def _mandatory_warnings(description, currpath=None):
621 for opt in description._impl_getchildren(context=context):
622 name = opt.impl_getname()
623 path = '.'.join(currpath + [name])
625 if opt.impl_is_optiondescription():
626 if not settings.validate_properties(opt, True, False, path=path,
627 force_permissive=force_permissive,
628 setting_properties=setting_properties):
629 for path in _mandatory_warnings(opt, currpath + [name]):
632 if isinstance(opt, SymLinkOption) and \
633 not isinstance(opt, DynSymLinkOption):
635 self_properties = settings._getproperties(opt, path,
637 setting_properties=setting_properties)
638 if 'mandatory' in self_properties:
639 err = self._get_cached_value(opt, path=path,
640 trusted_cached_properties=False,
641 force_permissive=force_permissive,
642 setting_properties=setting_properties,
643 self_properties=self_properties,
644 validate=validate, returns_raise=True)
645 if not isinstance(err, Exception):
647 elif isinstance(err, PropertiesOptionError):
648 if err.proptype == ['mandatory']:
650 elif isinstance(err, ConfigError):
654 #assume that uncalculated value is an empty value
659 descr = self._getcontext().cfgimpl_get_description()
660 for path in _mandatory_warnings(descr):
663 def force_cache(self):
664 """parse all option to force data in cache
666 context = self.context()
667 if not 'cache' in context.cfgimpl_get_settings():
668 raise ConfigError(_('can force cache only if cache '
669 'is actived in config'))
670 #remove all cached properties and value to update "expired" time
671 context.cfgimpl_reset_cache()
672 for path in context.cfgimpl_get_description().impl_getpaths(
673 include_groups=True):
674 err = context.getattr(path, returns_raise=True)
675 if isinstance(err, Exception) and not isinstance(err, PropertiesOptionError):
678 def __getstate__(self):
679 return {'_p_': self._p_}
681 def _impl_setstate(self, storage):
682 self._p_._storage = storage
684 def __setstate__(self, states):
685 self._p_ = states['_p_']
688 # ____________________________________________________________
691 """multi options values container
692 that support item notation for the values of multi options"""
693 __slots__ = ('opt', 'path', 'context', '__weakref__')
695 def __init__(self, value, context, opt, path):
697 :param value: the Multi wraps a list value
698 :param context: the home config that has the values
699 :param opt: the option object that have this Multi value
700 :param path: path of the option
704 if not opt.impl_is_submulti() and isinstance(value, Multi): # pragma: optional cover
705 raise ValueError(_('{0} is already a Multi ').format(
709 if not isinstance(context, weakref.ReferenceType): # pragma: optional cover
710 raise ValueError('context must be a Weakref')
711 self.context = context
712 if not isinstance(value, list):
713 if not '_index' in self.__slots__ and opt.impl_is_submulti():
717 elif value != [] and not '_index' in self.__slots__ and \
718 opt.impl_is_submulti() and not isinstance(value[0], list):
720 super(Multi, self).__init__(value)
721 if opt.impl_is_submulti():
722 if not '_index' in self.__slots__:
723 for idx, val in enumerate(self):
724 if not isinstance(val, SubMulti):
725 super(Multi, self).__setitem__(idx, SubMulti(val,
729 self[idx].submulti = weakref.ref(self)
731 def _getcontext(self):
732 """context could be None, we need to test it
733 context is None only if all reference to `Config` object is deleted
734 (for example we delete a `Config` and we manipulate a reference to
735 old `SubConfig`, `Values`, `Multi` or `Settings`)
737 context = self.context()
738 if context is None: # pragma: optional cover
739 raise ConfigError(_('the context does not exist anymore'))
742 def __setitem__(self, index, value):
743 self._setitem(index, value)
745 def _setitem(self, index, value, validate=True):
746 context = self._getcontext()
747 setting = context.cfgimpl_get_settings()
748 setting_properties = setting._getproperties(read_write=False)
750 index = self.__len__() + index
751 if 'validator' in setting_properties and validate:
752 session = context.cfgimpl_get_values()._p_.getsession()
753 fake_context = context._gen_fake_values(session)
754 fake_multi = fake_context.cfgimpl_get_values()._get_cached_value(
755 self.opt, path=self.path, validate=False)
756 fake_multi._setitem(index, value, validate=False)
757 self._validate(value, fake_context, index, True)
758 #assume not checking mandatory property
759 super(Multi, self).__setitem__(index, value)
760 self._store(index=index)
762 #def __repr__(self, *args, **kwargs):
763 # return super(Multi, self).__repr__(*args, **kwargs)
765 def __getitem__(self, index):
766 value = super(Multi, self).__getitem__(index)
767 if isinstance(value, PropertiesOptionError):
771 def _get_validated_value(self, index):
772 values = self._getcontext().cfgimpl_get_values()
773 return values._get_validated_value(self.opt, self.path,
777 def append(self, value=undefined, force=False, setitem=True, validate=True,
778 force_permissive=False):
779 """the list value can be updated (appened)
780 only if the option is a master
782 if not force and self.opt.impl_is_master_slaves('slave'): # pragma: optional cover
783 raise SlaveError(_("cannot append a value on a multi option {0}"
784 " which is a slave").format(self.opt.impl_getname()))
785 index = self.__len__()
786 if value is undefined:
787 value = self._get_validated_value(index)
788 if validate and value not in [None, undefined]:
789 context = self._getcontext()
790 setting = context.cfgimpl_get_settings()
791 setting_properties = setting._getproperties(read_write=False)
792 if 'validator' in setting_properties:
793 session = context.cfgimpl_get_values()._p_.getsession()
794 fake_context = context._gen_fake_values(session)
795 fake_multi = fake_context.cfgimpl_get_values()._get_cached_value(
796 self.opt, path=self.path, validate=False,
797 force_permissive=force_permissive)
798 fake_multi.append(value, validate=False, force=True,
800 self._validate(value, fake_context, index, True)
801 if not '_index' in self.__slots__ and self.opt.impl_is_submulti():
802 if not isinstance(value, SubMulti):
803 value = SubMulti(value, self.context, self.opt, self.path, index)
804 value.submulti = weakref.ref(self)
805 super(Multi, self).append(value)
807 self._store(force=force)
809 def append_properties_error(self, err):
810 super(Multi, self).append(err)
812 def sort(self, cmp=None, key=None, reverse=False):
813 if self.opt.impl_is_master_slaves():
814 raise SlaveError(_("cannot sort multi option {0} if master or slave"
815 "").format(self.opt.impl_getname()))
816 if sys.version_info[0] >= 3:
818 raise ValueError(_('cmp is not permitted in python v3 or '
820 super(Multi, self).sort(key=key, reverse=reverse)
822 super(Multi, self).sort(cmp=cmp, key=key, reverse=reverse)
826 if self.opt.impl_is_master_slaves():
827 raise SlaveError(_("cannot reverse multi option {0} if master or "
828 "slave").format(self.opt.impl_getname()))
829 super(Multi, self).reverse()
832 def insert(self, index, value, validate=True):
833 if self.opt.impl_is_master_slaves():
834 raise SlaveError(_("cannot insert multi option {0} if master or "
835 "slave").format(self.opt.impl_getname()))
836 context = self._getcontext()
837 setting = setting = context.cfgimpl_get_settings()
838 setting_properties = setting._getproperties(read_write=False)
839 if 'validator' in setting_properties and validate and value is not None:
840 session = context.cfgimpl_get_values()._p_.getsession()
841 fake_context = context._gen_fake_values(session)
842 fake_multi = fake_context.cfgimpl_get_values()._get_cached_value(
843 self.opt, path=self.path, validate=False)
844 fake_multi.insert(index, value, validate=False)
845 self._validate(value, fake_context, index, True)
846 super(Multi, self).insert(index, value)
849 def extend(self, iterable, validate=True):
850 if self.opt.impl_is_master_slaves():
851 raise SlaveError(_("cannot extend multi option {0} if master or "
852 "slave").format(self.opt.impl_getname()))
853 index = getattr(self, '_index', None)
854 context = self._getcontext()
855 setting = context.cfgimpl_get_settings()
856 setting_properties = setting._getproperties(read_write=False)
857 if 'validator' in setting_properties and validate:
858 session = context.cfgimpl_get_values()._p_.getsession()
859 fake_context = context._gen_fake_values(session)
860 fake_multi = fake_context.cfgimpl_get_values()._get_cached_value(
861 self.opt, path=self.path, validate=False)
862 fake_multi.extend(iterable, validate=False)
863 self._validate(iterable, fake_context, index)
864 super(Multi, self).extend(iterable)
867 def _validate(self, value, fake_context, force_index, submulti=False):
868 err = self.opt.impl_validate(value, context=fake_context,
869 force_index=force_index)
873 def pop(self, index, force=False):
874 """the list value can be updated (poped)
875 only if the option is a master
877 :param index: remove item a index
879 :param force: force pop item (withoud check master/slave)
881 :returns: item at index
883 context = self._getcontext()
885 if self.opt.impl_is_master_slaves('slave'): # pragma: optional cover
886 raise SlaveError(_("cannot pop a value on a multi option {0}"
887 " which is a slave").format(self.opt.impl_getname()))
888 if self.opt.impl_is_master_slaves('master'):
889 self.opt.impl_get_master_slaves().pop(self.opt,
890 context.cfgimpl_get_values(), index)
891 #set value without valid properties
892 ret = super(Multi, self).pop(index)
893 self._store(force=force)
896 def _store(self, force=False, index=None):
897 values = self._getcontext().cfgimpl_get_values()
899 #FIXME could get properties an pass it
900 values.validate(self.opt, self, self.path,
901 valid_masterslave=False)
902 values._setvalue(self.opt, self.path, self, index=index)
905 class SubMulti(Multi):
906 __slots__ = ('_index', 'submulti')
908 def __init__(self, value, context, opt, path, index):
910 :param index: index (only for slave with submulti)
914 super(SubMulti, self).__init__(value, context, opt, path)
916 def append(self, value=undefined):
917 super(SubMulti, self).append(value, force=True)
919 def pop(self, index):
920 return super(SubMulti, self).pop(index, force=True)
922 def __setitem__(self, index, value):
923 self._setitem(index, value)
925 def _store(self, force=False, index=None):
926 #force is unused here
927 values = self._getcontext().cfgimpl_get_values()
928 values.validate(self.opt, self, self.path, valid_masterslave=False)
929 values._setvalue(self.opt, self.path, self.submulti())
931 def _validate(self, value, fake_context, force_index, submulti=False):
932 if value is not None:
933 if submulti is False:
934 super(SubMulti, self)._validate(value, fake_context,
935 force_index, submulti)
937 err = self.opt.impl_validate(value, context=fake_context,
938 force_index=self._index,
939 force_submulti_index=force_index)
943 def _get_validated_value(self, index):
944 values = self._getcontext().cfgimpl_get_values()
945 return values._get_validated_value(self.opt, self.path,
948 submulti_index=self._index)