don't display warning in mandatory_warnings
[tiramisu.git] / tiramisu / value.py
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)
4 #
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.
9 #
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
13 # details.
14 #
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 # ____________________________________________________________
18 from time import time
19 import sys
20 import weakref
21 from .error import ConfigError, SlaveError, PropertiesOptionError
22 from .setting import owners, expires_time, undefined
23 from .autolib import carry_out_calculation
24 from .i18n import _
25 from .option import SymLinkOption, DynSymLinkOption, Option
26
27
28 class Values(object):
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.
32     """
33     __slots__ = ('context', '_p_', '__weakref__')
34
35     def __init__(self, context, storage):
36         """
37         Initializes the values's dict.
38
39         :param context: the context is the home config's values
40
41         """
42         self.context = weakref.ref(context)
43         # the storage type is dictionary or sqlite3
44         self._p_ = storage
45
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`)
51         """
52         context = self.context()
53         if context is None:  # pragma: optional cover
54             raise ConfigError(_('the context does not exist anymore'))
55         return context
56
57     def _get_multi(self, opt, path):
58         return Multi([], self.context, opt, path)
59
60     def _getdefaultvalue(self, opt, path, with_meta, index, submulti_index,
61                          returns_raise):
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(),
66                                           callback=callback,
67                                           callback_params=callback_params,
68                                           index=index,
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)):
75                     return value
76             else:
77                 return value
78         if with_meta:
79             meta = self._getcontext().cfgimpl_get_meta()
80             if meta is not None:
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):
86                         raise value
87                 else:
88                     if isinstance(value, Multi):
89                         if index is not None:
90                             value = value[index]
91                         else:
92                             value = list(value)
93                     return value
94         # now try to get default value
95         value = opt.impl_getdefault()
96         if opt.impl_is_multi() and index is not None:
97             if value == []:
98                 value = opt.impl_getdefault_multi()
99             else:
100                 if len(value) > index:
101                     value = value[index]
102                 else:
103                     value = opt.impl_getdefault_multi()
104         return value
105
106     def _getvalue(self, opt, path, self_properties, index, submulti_index,
107                   with_meta, masterlen, session):
108         """actually retrieves the value
109
110         :param opt: the `option.Option()` object
111         :returns: the option's value (or the default value if not set)
112         """
113         force_default = 'frozen' in self_properties and \
114             'force_default_on_freeze' in self_properties
115         # not default value
116         is_default = self._is_default_owner(opt, path, session,
117                                             validate_properties=False,
118                                             validate_meta=False,
119                                             self_properties=self_properties,
120                                             index=index)
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)
124             else:
125                 value = self._p_.getvalue(path, session)
126                 if index is not None:
127                     if len(value) > index:
128                         return value[index]
129                     #value is smaller than expected
130                     #so return default value
131                 else:
132                     return value
133         return self._getdefaultvalue(opt, path, with_meta, index,
134                                      submulti_index, True)
135
136     def get_modified_values(self):
137         return self._p_.get_modified_values()
138
139     def __contains__(self, opt):
140         """
141         implements the 'in' keyword syntax in order provide a pythonic way
142         to kow if an option have a value
143
144         :param opt: the `option.Option()` object
145         """
146         path = opt.impl_getpath(self._getcontext())
147         return self._contains(path)
148
149     def _contains(self, path, session=None):
150         if session is None:
151             session = self._p_.getsession()
152         return self._p_.hasvalue(path, session)
153
154     def __delitem__(self, opt):
155         """overrides the builtins `del()` instructions"""
156         self.reset(opt)
157
158     def reset(self, opt, path=None, validate=True, _setting_properties=None):
159         context = self._getcontext()
160         setting = context.cfgimpl_get_settings()
161         if path is None:
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)
167
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,
175                                          check_frozen=True)
176         if opt.impl_is_master_slaves('master'):
177             opt.impl_get_master_slaves().reset(opt, self, _setting_properties)
178         if hasvalue:
179             if 'force_store_value' in setting._getproperties(opt=opt,
180                                                              path=path,
181                                                              setting_properties=_setting_properties,
182                                                              read_write=False,
183                                                              apply_requires=False):
184                 value = self._getdefaultvalue(opt, path, True, undefined, undefined, False)
185                 self._setvalue(opt, path, value, force_owner=owners.forced)
186             else:
187                 self._p_.resetvalue(path, session)
188             context.cfgimpl_reset_cache()
189
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:
193             return False
194         else:
195             empty = opt._empty
196             if index in [None, undefined] and opt.impl_is_multi():
197                 if force_allow_empty_list:
198                     allow_empty_list = True
199                 else:
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
204                         else:
205                             allow_empty_list = False
206                 isempty = value is None or (not allow_empty_list and value == []) or \
207                     None in value or empty in value
208             else:
209                 isempty = value is None or value == empty
210         return isempty
211
212     def __getitem__(self, opt):
213         "enables us to use the pythonic dictionary-like access to values"
214         return self.getitem(opt)
215
216     def getitem(self, opt, validate=True, force_permissive=False):
217         """
218         """
219         return self._get_cached_value(opt, validate=validate,
220                                       force_permissive=force_permissive)
221
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, display_warnings=True):
229         context = self._getcontext()
230         settings = context.cfgimpl_get_settings()
231         if path is None:
232             path = opt.impl_getpath(context)
233         ntime = None
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,
238                                                       read_write=False,
239                                                       setting_properties=setting_properties,
240                                                       index=index)
241         if 'cache' in setting_properties and self._p_.hascache(path, index):
242             if 'expire' in setting_properties:
243                 ntime = int(time())
244             is_cached, value = self._p_.getcache(path, ntime, index)
245             if is_cached:
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,
251                                                          path=path,
252                                                          force_permissive=force_permissive,
253                                                          setting_properties=setting_properties,
254                                                          self_properties=self_properties,
255                                                          index=index)
256                     if props:
257                         if returns_raise:
258                             return props
259                         else:
260                             raise props
261                 return value
262         if session is None:
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,
266                                                        validate,
267                                                        force_permissive,
268                                                        trusted_cached_properties,
269                                                        validate_properties,
270                                                        session,
271                                                        setting_properties=setting_properties,
272                                                        index=index,
273                                                        self_properties=self_properties,
274                                                        returns_raise=returns_raise)
275         else:
276             val = self._get_validated_value(opt, path, validate,
277                                             force_permissive,
278                                             validate_properties,
279                                             setting_properties=setting_properties,
280                                             self_properties=self_properties,
281                                             with_meta=with_meta,
282                                             masterlen=masterlen,
283                                             index=index,
284                                             submulti_index=submulti_index,
285                                             check_frozen=check_frozen,
286                                             returns_raise=returns_raise,
287                                             session=session,
288                                             display_warnings=display_warnings)
289         if isinstance(val, Exception):
290             if returns_raise:
291                 return val
292             else:
293                 raise val
294         # cache doesn't work with SubMulti yet
295         if not isinstance(val, SubMulti) and 'cache' in setting_properties and \
296                 validate and validate_properties and force_permissive is False \
297                 and trusted_cached_properties is True:
298             if 'expire' in setting_properties:
299                 if ntime is None:
300                     ntime = int(time())
301                 ntime = ntime + expires_time
302             self._p_.setcache(path, val, ntime, index)
303         return val
304
305     def _get_validated_value(self, opt, path, validate, force_permissive,
306                              validate_properties,
307                              index=None, submulti_index=undefined,
308                              with_meta=True, setting_properties=undefined,
309                              self_properties=undefined, masterlen=undefined,
310                              check_frozen=False, returns_raise=False,
311                              session=None, display_warnings=True):
312         """same has getitem but don't touch the cache
313         index is None for slave value, if value returned is not a list, just return []
314         """
315         context = self._getcontext()
316         setting = context.cfgimpl_get_settings()
317         if setting_properties is undefined:
318             setting_properties = setting._getproperties(read_write=False)
319         if self_properties is undefined:
320             self_properties = setting._getproperties(opt, path, read_write=False, index=index)
321         config_error = None
322         if session is None:
323             session = self._p_.getsession()
324         value = self._getvalue(opt, path, self_properties, index, submulti_index,
325                                with_meta, masterlen, session)
326         if isinstance(value, Exception):
327             if isinstance(value, ConfigError):
328                 # For calculating properties, we need value (ie for mandatory
329                 # value).
330                 # If value is calculating with a PropertiesOptionError's option
331                 # _getvalue raise a ConfigError.
332                 # We can not raise ConfigError if this option should raise
333                 # PropertiesOptionError too. So we get config_error and raise
334                 # ConfigError if properties did not raise.
335                 config_error = value
336                 # value is not set, for 'undefined' (cannot set None because of
337                 # mandatory property)
338                 value = undefined
339             else:
340                 raise value
341         else:
342             if index is undefined:
343                 force_index = None
344             else:
345                 force_index = index
346             if opt.impl_is_multi():
347                 if force_index is None:
348                     value = Multi(value, self.context, opt, path)
349                 elif opt.impl_is_submulti() and submulti_index is undefined:
350                     value = SubMulti(value, self.context, opt, path,
351                                      force_index)
352
353             if validate:
354                 if submulti_index is undefined:
355                     force_submulti_index = None
356                 else:
357                     force_submulti_index = submulti_index
358                 err = opt.impl_validate(value, context,
359                                         'validator' in setting_properties,
360                                         force_index=force_index,
361                                         force_submulti_index=force_submulti_index,
362                                         display_warnings=display_warnings)
363                 if err:
364                     config_error = err
365                     value = None
366
367         if validate_properties:
368             if config_error is not None:
369                 # should not raise PropertiesOptionError if option is
370                 # mandatory
371                 val_props = undefined
372             else:
373                 val_props = value
374             props = setting.validate_properties(opt, False, check_frozen, value=val_props,
375                                                 path=path,
376                                                 force_permissive=force_permissive,
377                                                 setting_properties=setting_properties,
378                                                 self_properties=self_properties,
379                                                 index=index)
380             if props:
381                 if returns_raise:
382                     return props
383                 else:
384                     raise props
385         if config_error is not None:
386             if returns_raise:
387                 return config_error
388             else:
389                 raise config_error
390         return value
391
392     def __setitem__(self, opt, value):  # pragma: optional cover
393         raise ConfigError(_('you should only set value with config'))
394
395     def setitem(self, opt, value, path, force_permissive=False,
396                 check_frozen=True, not_raises=False):
397         # check_frozen is, for example, used with "force_store_value"
398         # user didn't change value, so not write
399         # valid opt
400         context = self._getcontext()
401         setting_properties = context.cfgimpl_get_settings()._getproperties(read_write=False)
402         if 'validator' in setting_properties:
403             session = context.cfgimpl_get_values()._p_.getsession()
404             fake_context = context._gen_fake_values(session)
405             fake_values = fake_context.cfgimpl_get_values()
406             fake_values._setvalue(opt, path, value)
407             props = fake_values.validate(opt, value, path,
408                                          check_frozen=check_frozen,
409                                          force_permissive=force_permissive,
410                                          setting_properties=setting_properties,
411                                          session=session, not_raises=not_raises)
412             if props and not_raises:
413                 return
414             err = opt.impl_validate(value, fake_context)
415             if err:
416                 raise err
417         self._setvalue(opt, path, value)
418
419     def _setvalue(self, opt, path, value, force_owner=undefined, index=None):
420         context = self._getcontext()
421         context.cfgimpl_reset_cache()
422         if force_owner is undefined:
423             owner = context.cfgimpl_get_settings().getowner()
424         else:
425             owner = force_owner
426         # in storage, value must not be a multi
427         if isinstance(value, Multi):
428             value = list(value)
429             if opt.impl_is_submulti():
430                 for idx, val in enumerate(value):
431                     if isinstance(val, SubMulti):
432                         value[idx] = list(val)
433         session = self._p_.getsession()
434         #FIXME pourquoi là et pas dans masterslaves ??
435         if opt.impl_is_master_slaves('slave'):
436             if index is not None:
437                 self._p_.setvalue(path, value[index], owner, index, session)
438             else:
439                 self._p_.resetvalue(path, session)
440                 for idx, val in enumerate(value):
441                     self._p_.setvalue(path, val, owner, idx, session)
442         else:
443             self._p_.setvalue(path, value, owner, None, session)
444         del(session)
445
446     def validate(self, opt, value, path, check_frozen=True, force_permissive=False,
447                  setting_properties=undefined, valid_masterslave=True,
448                  not_raises=False, returns_raise=False, session=None):
449         if valid_masterslave and opt.impl_is_master_slaves():
450             if session is None:
451                 session = self._p_.getsession()
452             opt.impl_get_master_slaves().validate(self, opt, value, path, returns_raise, session)
453         props = self._getcontext().cfgimpl_get_settings().validate_properties(opt,
454                                                                               False,
455                                                                               check_frozen,
456                                                                               value=value,
457                                                                               path=path,
458                                                                               force_permissive=force_permissive,
459                                                                               setting_properties=setting_properties)
460         if props:
461             if not_raises:
462                 return props
463             raise props
464
465     def _is_meta(self, opt, path, session):
466         context = self._getcontext()
467         setting = context.cfgimpl_get_settings()
468         self_properties = setting._getproperties(opt, path, read_write=False)
469         if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
470             return False
471         if self._p_.getowner(path, owners.default, session, only_default=True) is not owners.default:
472             return False
473         if context.cfgimpl_get_meta() is not None:
474             return True
475         return False
476
477     def getowner(self, opt, index=None, force_permissive=False, session=None):
478         """
479         retrieves the option's owner
480
481         :param opt: the `option.Option` object
482         :param force_permissive: behaves as if the permissive property
483                                  was present
484         :returns: a `setting.owners.Owner` object
485         """
486         if isinstance(opt, SymLinkOption) and \
487                 not isinstance(opt, DynSymLinkOption):
488             opt = opt._impl_getopt()
489         path = opt.impl_getpath(self._getcontext())
490         return self._getowner(opt, path, session, index=index, force_permissive=force_permissive)
491
492     def _getowner(self, opt, path, session, validate_properties=True,
493                   force_permissive=False, validate_meta=undefined,
494                   self_properties=undefined, only_default=False,
495                   index=None):
496         """get owner of an option
497         """
498         if session is None:
499             session = self._p_.getsession()
500         if not isinstance(opt, Option) and not isinstance(opt,
501                                                           DynSymLinkOption):
502             raise ConfigError(_('owner only avalaible for an option'))
503         context = self._getcontext()
504         if self_properties is undefined:
505             self_properties = context.cfgimpl_get_settings()._getproperties(
506                 opt, path, read_write=False)
507         if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
508             return owners.default
509         if validate_properties:
510             self._get_cached_value(opt, path, True, force_permissive, None, True,
511                                    self_properties=self_properties, session=session)
512         owner = self._p_.getowner(path, owners.default, session, only_default=only_default, index=index)
513         if validate_meta is undefined:
514             if opt.impl_is_master_slaves('slave'):
515                 master = opt.impl_get_master_slaves().getmaster(opt)
516                 masterp = master.impl_getpath(context)
517                 validate_meta = self._is_meta(opt, masterp, session)
518             else:
519                 validate_meta = True
520         if validate_meta:
521             meta = context.cfgimpl_get_meta()
522             if owner is owners.default and meta is not None:
523                 owner = meta.cfgimpl_get_values()._getowner(opt, path, session,
524                                                             validate_properties=validate_properties,
525                                                             force_permissive=force_permissive,
526                                                             self_properties=self_properties,
527                                                             only_default=only_default, index=index)
528         return owner
529
530     def setowner(self, opt, owner, index=None):
531         """
532         sets a owner to an option
533
534         :param opt: the `option.Option` object
535         :param owner: a valid owner, that is a `setting.owners.Owner` object
536         """
537         if not isinstance(owner, owners.Owner):  # pragma: optional cover
538             raise TypeError(_("invalid generic owner {0}").format(str(owner)))
539
540         path = opt.impl_getpath(self._getcontext())
541         session = self._p_.getsession()
542         if not self._p_.hasvalue(path, session):  # pragma: optional cover
543             raise ConfigError(_('no value for {0} cannot change owner to {1}'
544                                 '').format(path, owner))
545         props = self._getcontext().cfgimpl_get_settings().validate_properties(opt,
546                                                                               False,
547                                                                               True,
548                                                                               path,
549                                                                               index=index)
550         if props:
551             raise props
552         self._p_.setowner(path, owner, session, index=index)
553
554     def is_default_owner(self, opt, validate_properties=True,
555                          validate_meta=True, index=None,
556                          force_permissive=False):
557         """
558         :param config: *must* be only the **parent** config
559                        (not the toplevel config)
560         :return: boolean
561         """
562         path = opt.impl_getpath(self._getcontext())
563         return self._is_default_owner(opt, path, session=None,
564                                       validate_properties=validate_properties,
565                                       validate_meta=validate_meta, index=index,
566                                       force_permissive=force_permissive)
567
568     def _is_default_owner(self, opt, path, session, validate_properties=True,
569                           validate_meta=True, self_properties=undefined,
570                           index=None, force_permissive=False):
571         if not opt.impl_is_master_slaves('slave'):
572             index = None
573         d = self._getowner(opt, path, session, validate_properties=validate_properties,
574                            validate_meta=validate_meta,
575                            self_properties=self_properties, only_default=True,
576                            index=index, force_permissive=force_permissive)
577         return d == owners.default
578
579     def reset_cache(self, only_expired):
580         """
581         clears the cache if necessary
582         """
583         if only_expired:
584             self._p_.reset_expired_cache(int(time()))
585         else:
586             self._p_.reset_all_cache()
587
588     # information
589     def set_information(self, key, value):
590         """updates the information's attribute
591
592         :param key: information's key (ex: "help", "doc"
593         :param value: information's value (ex: "the help string")
594         """
595         self._p_.set_information(key, value)
596
597     def get_information(self, key, default=undefined):
598         """retrieves one information's item
599
600         :param key: the item string (ex: "help")
601         """
602         return self._p_.get_information(key, default)
603
604     def del_information(self, key, raises=True):
605         self._p_.del_information(key, raises)
606
607     def mandatory_warnings(self):
608         """convenience function to trace Options that are mandatory and
609         where no value has been set
610
611         :returns: generator of mandatory Option's path
612         """
613         context = self._getcontext()
614         settings = context.cfgimpl_get_settings()
615         setting_properties = context.cfgimpl_get_settings()._getproperties()
616         setting_properties.update(['mandatory', 'empty'])
617
618         def _mandatory_warnings(description, currpath=None):
619             if currpath is None:
620                 currpath = []
621             for opt in description._impl_getchildren(context=context):
622                 name = opt.impl_getname()
623                 path = '.'.join(currpath + [name])
624
625                 if opt.impl_is_optiondescription():
626                     if not settings.validate_properties(opt, True, False, path=path,
627                                                         force_permissive=True,
628                                                         setting_properties=setting_properties):
629                         for path in _mandatory_warnings(opt, currpath + [name]):
630                             yield path
631                 else:
632                     if isinstance(opt, SymLinkOption) and \
633                             not isinstance(opt, DynSymLinkOption):
634                         continue
635                     self_properties = settings._getproperties(opt, path,
636                                                               read_write=False,
637                                                               setting_properties=setting_properties)
638                     if 'mandatory' in self_properties or 'empty' in self_properties:
639                         err = self._get_cached_value(opt, path=path,
640                                                      trusted_cached_properties=False,
641                                                      force_permissive=True,
642                                                      setting_properties=setting_properties,
643                                                      self_properties=self_properties,
644                                                      validate=True, returns_raise=True,
645                                                      display_warnings=False)
646                         if not isinstance(err, Exception):
647                             pass
648                         elif isinstance(err, PropertiesOptionError):
649                             if err.proptype == ['mandatory']:
650                                 yield path
651                         elif isinstance(err, ConfigError):
652                             #assume that uncalculated value is an empty value
653                             yield path
654                         else:
655                             raise err
656
657         descr = self._getcontext().cfgimpl_get_description()
658         for path in _mandatory_warnings(descr):
659             yield path
660
661     def force_cache(self):
662         """parse all option to force data in cache
663         """
664         context = self.context()
665         if not 'cache' in context.cfgimpl_get_settings():
666             raise ConfigError(_('can force cache only if cache '
667                                 'is actived in config'))
668         #remove all cached properties and value to update "expired" time
669         context.cfgimpl_reset_cache()
670         for path in context.cfgimpl_get_description().impl_getpaths(
671                 include_groups=True):
672             err = context.getattr(path, returns_raise=True)
673             if isinstance(err, Exception) and not isinstance(err, PropertiesOptionError):
674                 raise err
675
676     def __getstate__(self):
677         return {'_p_': self._p_}
678
679     def _impl_setstate(self, storage):
680         self._p_._storage = storage
681
682     def __setstate__(self, states):
683         self._p_ = states['_p_']
684
685
686 # ____________________________________________________________
687 # multi types
688 class Multi(list):
689     """multi options values container
690     that support item notation for the values of multi options"""
691     __slots__ = ('opt', 'path', 'context', '__weakref__')
692
693     def __init__(self, value, context, opt, path):
694         """
695         :param value: the Multi wraps a list value
696         :param context: the home config that has the values
697         :param opt: the option object that have this Multi value
698         :param path: path of the option
699         """
700         if value is None:
701             value = []
702         if not opt.impl_is_submulti() and isinstance(value, Multi):  # pragma: optional cover
703             raise ValueError(_('{0} is already a Multi ').format(
704                 opt.impl_getname()))
705         self.opt = opt
706         self.path = path
707         if not isinstance(context, weakref.ReferenceType):  # pragma: optional cover
708             raise ValueError('context must be a Weakref')
709         self.context = context
710         if not isinstance(value, list):
711             if not '_index' in self.__slots__ and opt.impl_is_submulti():
712                 value = [[value]]
713             else:
714                 value = [value]
715         elif value != [] and not '_index' in self.__slots__ and \
716                 opt.impl_is_submulti() and not isinstance(value[0], list):
717             value = [value]
718         super(Multi, self).__init__(value)
719         if opt.impl_is_submulti():
720             if not '_index' in self.__slots__:
721                 for idx, val in enumerate(self):
722                     if not isinstance(val, SubMulti):
723                         super(Multi, self).__setitem__(idx, SubMulti(val,
724                                                                      context,
725                                                                      opt, path,
726                                                                      idx))
727                     self[idx].submulti = weakref.ref(self)
728
729     def _getcontext(self):
730         """context could be None, we need to test it
731         context is None only if all reference to `Config` object is deleted
732         (for example we delete a `Config` and we manipulate a reference to
733         old `SubConfig`, `Values`, `Multi` or `Settings`)
734         """
735         context = self.context()
736         if context is None:  # pragma: optional cover
737             raise ConfigError(_('the context does not exist anymore'))
738         return context
739
740     def __setitem__(self, index, value):
741         self._setitem(index, value)
742
743     def _setitem(self, index, value, validate=True):
744         context = self._getcontext()
745         setting = context.cfgimpl_get_settings()
746         setting_properties = setting._getproperties(read_write=False)
747         if index < 0:
748             index = self.__len__() + index
749         if 'validator' in setting_properties and validate:
750             session = context.cfgimpl_get_values()._p_.getsession()
751             fake_context = context._gen_fake_values(session)
752             fake_multi = fake_context.cfgimpl_get_values()._get_cached_value(
753                 self.opt, path=self.path, validate=False)
754             fake_multi._setitem(index, value, validate=False)
755             self._validate(value, fake_context, index, True)
756         #assume not checking mandatory property
757         super(Multi, self).__setitem__(index, value)
758         self._store(index=index)
759
760     #def __repr__(self, *args, **kwargs):
761     #    return super(Multi, self).__repr__(*args, **kwargs)
762
763     def __getitem__(self, index):
764         value = super(Multi, self).__getitem__(index)
765         if isinstance(value, PropertiesOptionError):
766             raise value
767         return value
768
769     def _getdefaultvalue(self, index):
770         values = self._getcontext().cfgimpl_get_values()
771         value = values._getdefaultvalue(self.opt, self.path, True, index,
772                                         undefined, True)
773         if self.opt.impl_is_submulti():
774             value = SubMulti(value, self.context, self.opt, self.path, index)
775         return value
776
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
781         """
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._getdefaultvalue(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,
799                                   setitem=setitem)
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)
806         if setitem:
807             self._store(force=force)
808
809     def append_properties_error(self, err):
810         super(Multi, self).append(err)
811
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:
817             if cmp is not None:
818                 raise ValueError(_('cmp is not permitted in python v3 or '
819                                    'greater'))
820             super(Multi, self).sort(key=key, reverse=reverse)
821         else:
822             super(Multi, self).sort(cmp=cmp, key=key, reverse=reverse)
823         self._store()
824
825     def reverse(self):
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()
830         self._store()
831
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)
847         self._store()
848
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)
865         self._store()
866
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)
870         if err:
871             raise err
872
873     def pop(self, index, force=False):
874         """the list value can be updated (poped)
875         only if the option is a master
876
877         :param index: remove item a index
878         :type index: int
879         :param force: force pop item (withoud check master/slave)
880         :type force: boolean
881         :returns: item at index
882         """
883         context = self._getcontext()
884         if not force:
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)
894         return ret
895
896     def _store(self, force=False, index=None):
897         values = self._getcontext().cfgimpl_get_values()
898         if not force:
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)
903
904
905 class SubMulti(Multi):
906     __slots__ = ('_index', 'submulti')
907
908     def __init__(self, value, context, opt, path, index):
909         """
910         :param index: index (only for slave with submulti)
911         :type index: `int`
912         """
913         self._index = index
914         super(SubMulti, self).__init__(value, context, opt, path)
915
916     def append(self, value=undefined):
917         super(SubMulti, self).append(value, force=True)
918
919     def pop(self, index):
920         return super(SubMulti, self).pop(index, force=True)
921
922     def __setitem__(self, index, value):
923         self._setitem(index, value)
924
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())
930
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)
936             else:
937                 err = self.opt.impl_validate(value, context=fake_context,
938                                              force_index=self._index,
939                                              force_submulti_index=force_index)
940                 if err:
941                     raise err
942
943     def _getdefaultvalue(self, index):
944         values = self._getcontext().cfgimpl_get_values()
945         return values._getdefaultvalue(self.opt, self.path, True, index,
946                                        self._index, True)