1 # -*- coding: utf-8 -*-
2 "takes care of the option's values and multi values"
3 # Copyright (C) 2013 Team tiramisu (see AUTHORS for all contributors)
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 # ____________________________________________________________
24 from tiramisu.error import ConfigError, SlaveError
25 from tiramisu.setting import owners, multitypes, expires_time
26 from tiramisu.autolib import carry_out_calculation
27 from tiramisu.i18n import _
28 from tiramisu.option import SymLinkOption
32 """The `Config`'s root is indeed in charge of the `Option()`'s values,
33 but the values are physicaly located here, in `Values`, wich is also
34 responsible of a caching utility.
36 __slots__ = ('context', '_p_', '__weakref__')
38 def __init__(self, context, storage):
40 Initializes the values's dict.
42 :param context: the context is the home config's values
45 self.context = weakref.ref(context)
46 # the storage type is dictionary or sqlite3
49 def _getdefault(self, opt):
51 actually retrieves the default value
53 :param opt: the `option.Option()` object
55 meta = self.context().cfgimpl_get_meta()
57 value = meta.cfgimpl_get_values()[opt]
59 value = opt.impl_getdefault()
60 if opt.impl_is_multi():
65 def _getvalue(self, opt, path, validate=True):
66 """actually retrieves the value
68 :param opt: the `option.Option()` object
69 :returns: the option's value (or the default value if not set)
71 if not self._p_.hasvalue(path):
72 # if there is no value
73 value = self._getdefault(opt)
74 if opt.impl_is_multi():
75 value = Multi(value, self.context, opt, path, validate)
78 value = self._p_.getvalue(path)
79 if opt.impl_is_multi() and not isinstance(value, Multi):
80 # load value so don't need to validate if is not a Multi
81 value = Multi(value, self.context, opt, path, validate=False)
84 def get_modified_values(self):
85 return self._p_.get_modified_values()
87 def __contains__(self, opt):
89 implements the 'in' keyword syntax in order provide a pythonic way
90 to kow if an option have a value
92 :param opt: the `option.Option()` object
94 path = self._get_opt_path(opt)
95 return self._contains(path)
97 def _contains(self, path):
98 return self._p_.hasvalue(path)
100 def __delitem__(self, opt):
101 """overrides the builtins `del()` instructions"""
104 def reset(self, opt, path=None):
106 path = self._get_opt_path(opt)
107 if self._p_.hasvalue(path):
108 setting = self.context().cfgimpl_get_settings()
109 opt.impl_validate(opt.impl_getdefault(), self.context(),
110 'validator' in setting)
111 self.context().cfgimpl_reset_cache()
112 if (opt.impl_is_multi() and
113 opt.impl_get_multitype() == multitypes.master):
114 for slave in opt.impl_get_master_slaves():
116 self._p_.resetvalue(path)
118 def _isempty(self, opt, value):
119 "convenience method to know if an option is empty"
121 if (not opt.impl_is_multi() and (value is None or value == empty)) or \
122 (opt.impl_is_multi() and (value == [] or
123 None in value or empty in value)):
127 def _getcallback_value(self, opt, index=None):
129 retrieves a value for the options that have a callback
131 :param opt: the `option.Option()` object
132 :param index: if an option is multi, only calculates the nth value
134 :returns: a calculated value
136 callback, callback_params = opt._callback
137 if callback_params is None:
139 return carry_out_calculation(opt._name, config=self.context(),
141 callback_params=callback_params,
144 def __getitem__(self, opt):
145 "enables us to use the pythonic dictionary-like access to values"
146 return self.getitem(opt)
148 def getitem(self, opt, path=None, validate=True, force_permissive=False,
149 force_properties=None, validate_properties=True):
152 path = self._get_opt_path(opt)
153 if self._p_.hascache('value', path):
155 is_cached, value = self._p_.getcache('value', path, ntime)
157 if opt.impl_is_multi() and not isinstance(value, Multi):
158 #load value so don't need to validate if is not a Multi
159 value = Multi(value, self.context, opt, path, validate=False)
161 val = self._getitem(opt, path, validate, force_permissive, force_properties,
163 if 'expire' in self.context().cfgimpl_get_settings() and validate and \
164 validate_properties and force_permissive is False and \
165 force_properties is None:
168 self._p_.setcache('value', path, val, ntime + expires_time)
172 def _getitem(self, opt, path, validate, force_permissive, force_properties,
173 validate_properties):
174 # options with callbacks
175 setting = self.context().cfgimpl_get_settings()
176 is_frozen = 'frozen' in setting[opt]
177 # if value is callback and is not set
178 # or frozen with force_default_on_freeze
179 if opt.impl_has_callback() and (
180 self._is_default_owner(path) or
181 (is_frozen and 'force_default_on_freeze' in setting[opt])):
182 no_value_slave = False
183 if (opt.impl_is_multi() and
184 opt.impl_get_multitype() == multitypes.slave):
185 masterp = self._get_opt_path(opt.impl_get_master_slaves())
186 mastervalue = getattr(self.context(), masterp)
187 lenmaster = len(mastervalue)
190 no_value_slave = True
192 if not no_value_slave:
193 value = self._getcallback_value(opt)
194 if (opt.impl_is_multi() and
195 opt.impl_get_multitype() == multitypes.slave):
196 if not isinstance(value, list):
197 value = [value for i in range(lenmaster)]
198 if opt.impl_is_multi():
199 value = Multi(value, self.context, opt, path, validate)
200 # suppress value if already set
201 self.reset(opt, path)
202 # frozen and force default
203 elif is_frozen and 'force_default_on_freeze' in setting[opt]:
204 value = self._getdefault(opt)
205 if opt.impl_is_multi():
206 value = Multi(value, self.context, opt, path, validate)
208 value = self._getvalue(opt, path, validate)
210 opt.impl_validate(value, self.context(), 'validator' in setting)
211 if self._is_default_owner(path) and \
212 'force_store_value' in setting[opt]:
213 self.setitem(opt, value, path, is_write=False)
214 if validate_properties:
215 setting.validate_properties(opt, False, False, value=value, path=path,
216 force_permissive=force_permissive,
217 force_properties=force_properties)
220 def __setitem__(self, opt, value):
221 raise ValueError('you should only set value with config')
223 def setitem(self, opt, value, path, force_permissive=False,
225 # is_write is, for example, used with "force_store_value"
226 # user didn't change value, so not write
228 opt.impl_validate(value, self.context(),
229 'validator' in self.context().cfgimpl_get_settings())
230 if opt.impl_is_multi() and not isinstance(value, Multi):
231 value = Multi(value, self.context, opt, path)
232 self._setvalue(opt, path, value, force_permissive=force_permissive,
235 def _setvalue(self, opt, path, value, force_permissive=False,
236 force_properties=None,
237 is_write=True, validate_properties=True):
238 self.context().cfgimpl_reset_cache()
239 if validate_properties:
240 setting = self.context().cfgimpl_get_settings()
241 setting.validate_properties(opt, False, is_write,
242 value=value, path=path,
243 force_permissive=force_permissive,
244 force_properties=force_properties)
245 owner = self.context().cfgimpl_get_settings().getowner()
246 self._p_.setvalue(path, value, owner)
248 def getowner(self, opt):
250 retrieves the option's owner
252 :param opt: the `option.Option` object
253 :returns: a `setting.owners.Owner` object
255 if isinstance(opt, SymLinkOption):
257 path = self._get_opt_path(opt)
258 return self._getowner(path)
260 def _getowner(self, path):
261 owner = self._p_.getowner(path, owners.default)
262 meta = self.context().cfgimpl_get_meta()
263 if owner is owners.default and meta is not None:
264 owner = meta.cfgimpl_get_values()._getowner(path)
267 def setowner(self, opt, owner):
269 sets a owner to an option
271 :param opt: the `option.Option` object
272 :param owner: a valid owner, that is a `setting.owners.Owner` object
274 if not isinstance(owner, owners.Owner):
275 raise TypeError(_("invalid generic owner {0}").format(str(owner)))
277 path = self._get_opt_path(opt)
278 self._setowner(path, owner)
280 def _setowner(self, path, owner):
281 if self._getowner(path) == owners.default:
282 raise ConfigError(_('no value for {0} cannot change owner to {1}'
283 '').format(path, owner))
284 self._p_.setowner(path, owner)
286 def is_default_owner(self, opt):
288 :param config: *must* be only the **parent** config
289 (not the toplevel config)
292 path = self._get_opt_path(opt)
293 return self._is_default_owner(path)
295 def _is_default_owner(self, path):
296 return self._getowner(path) == owners.default
298 def reset_cache(self, only_expired):
300 clears the cache if necessary
303 self._p_.reset_expired_cache('value', time())
305 self._p_.reset_all_cache('value')
307 def _get_opt_path(self, opt):
309 retrieve the option's path in the config
311 :param opt: the `option.Option` object
312 :returns: a string with points like "gc.dummy.my_option"
314 return self.context().cfgimpl_get_description().impl_get_path_by_opt(opt)
317 def set_information(self, key, value):
318 """updates the information's attribute
320 :param key: information's key (ex: "help", "doc"
321 :param value: information's value (ex: "the help string")
323 self._p_.set_information(key, value)
325 def get_information(self, key, default=None):
326 """retrieves one information's item
328 :param key: the item string (ex: "help")
331 return self._p_.get_information(key)
333 if default is not None:
336 raise ValueError(_("information's item"
337 " not found: {0}").format(key))
340 # ____________________________________________________________
345 """multi options values container
346 that support item notation for the values of multi options"""
347 __slots__ = ('opt', 'path', 'context')
349 def __init__(self, value, context, opt, path, validate=True):
351 :param value: the Multi wraps a list value
352 :param context: the home config that has the values
353 :param opt: the option object that have this Multi value
357 if not isinstance(context, weakref.ReferenceType):
358 raise ValueError('context must be a Weakref')
359 self.context = context
360 if not isinstance(value, list):
362 if validate and self.opt.impl_get_multitype() == multitypes.slave:
363 value = self._valid_slave(value)
364 elif self.opt.impl_get_multitype() == multitypes.master:
365 self._valid_master(value)
366 super(Multi, self).__init__(value)
368 def _valid_slave(self, value):
369 #if slave, had values until master's one
370 masterp = self.context().cfgimpl_get_description().impl_get_path_by_opt(
371 self.opt.impl_get_master_slaves())
372 mastervalue = getattr(self.context(), masterp)
373 masterlen = len(mastervalue)
374 valuelen = len(value)
375 if valuelen > masterlen or (valuelen < masterlen and
376 not self.context().cfgimpl_get_values(
377 )._is_default_owner(self.path)):
378 raise SlaveError(_("invalid len for the slave: {0}"
379 " which has {1} as master").format(
380 self.opt._name, masterp))
381 elif valuelen < masterlen:
382 for num in range(0, masterlen - valuelen):
383 value.append(self.opt.impl_getdefault_multi())
384 #else: same len so do nothing
387 def _valid_master(self, value):
388 masterlen = len(value)
389 values = self.context().cfgimpl_get_values()
390 for slave in self.opt._master_slaves:
391 path = values._get_opt_path(slave)
392 if not values._is_default_owner(path):
393 value_slave = values._getvalue(slave, path)
394 if len(value_slave) > masterlen:
395 raise SlaveError(_("invalid len for the master: {0}"
396 " which has {1} as slave with"
397 " greater len").format(
398 self.opt._name, slave._name))
399 elif len(value_slave) < masterlen:
400 for num in range(0, masterlen - len(value_slave)):
401 value_slave.append(slave.impl_getdefault_multi(),
404 def __setitem__(self, key, value):
405 self._validate(value)
406 #assume not checking mandatory property
407 super(Multi, self).__setitem__(key, value)
408 self.context().cfgimpl_get_values()._setvalue(self.opt, self.path, self)
410 def append(self, value, force=False):
411 """the list value can be updated (appened)
412 only if the option is a master
415 if self.opt.impl_get_multitype() == multitypes.slave:
416 raise SlaveError(_("cannot append a value on a multi option {0}"
417 " which is a slave").format(self.opt._name))
418 elif self.opt.impl_get_multitype() == multitypes.master:
419 values = self.context().cfgimpl_get_values()
420 if value is None and self.opt.impl_has_callback():
421 value = values._getcallback_value(self.opt)
422 #Force None il return a list
423 if isinstance(value, list):
425 self._validate(value)
426 super(Multi, self).append(value)
427 self.context().cfgimpl_get_values()._setvalue(self.opt, self.path, self, validate_properties=not force)
428 if not force and self.opt.impl_get_multitype() == multitypes.master:
429 for slave in self.opt.impl_get_master_slaves():
430 path = values._get_opt_path(slave)
431 if not values._is_default_owner(path):
432 if slave.impl_has_callback():
433 index = self.__len__() - 1
434 dvalue = values._getcallback_value(slave, index=index)
436 dvalue = slave.impl_getdefault_multi()
437 old_value = values.getitem(slave, path,
438 validate_properties=False)
439 if len(old_value) < self.__len__():
440 values.getitem(slave, path,
441 validate_properties=False).append(
444 values.getitem(slave, path,
445 validate_properties=False)[
448 def sort(self, cmp=None, key=None, reverse=False):
449 if self.opt.impl_get_multitype() in [multitypes.slave,
451 raise SlaveError(_("cannot sort multi option {0} if master or slave"
452 "").format(self.opt._name))
453 if sys.version_info[0] >= 3:
455 raise ValueError(_('cmp is not permitted in python v3 or greater'))
456 super(Multi, self).sort(key=key, reverse=reverse)
458 super(Multi, self).sort(cmp=cmp, key=key, reverse=reverse)
459 self.context().cfgimpl_get_values()._setvalue(self.opt, self.path, self)
462 if self.opt.impl_get_multitype() in [multitypes.slave,
464 raise SlaveError(_("cannot reverse multi option {0} if master or "
465 "slave").format(self.opt._name))
466 super(Multi, self).reverse()
467 self.context().cfgimpl_get_values()._setvalue(self.opt, self.path, self)
469 def insert(self, index, obj):
470 if self.opt.impl_get_multitype() in [multitypes.slave,
472 raise SlaveError(_("cannot insert multi option {0} if master or "
473 "slave").format(self.opt._name))
474 super(Multi, self).insert(index, obj)
475 self.context().cfgimpl_get_values()._setvalue(self.opt, self.path, self)
477 def extend(self, iterable):
478 if self.opt.impl_get_multitype() in [multitypes.slave,
480 raise SlaveError(_("cannot extend multi option {0} if master or "
481 "slave").format(self.opt._name))
482 super(Multi, self).extend(iterable)
483 self.context().cfgimpl_get_values()._setvalue(self.opt, self.path, self)
485 def _validate(self, value):
486 if value is not None:
488 self.opt._validate(value)
489 except ValueError as err:
490 raise ValueError(_("invalid value {0} "
491 "for option {1}: {2}"
492 "").format(str(value),
493 self.opt._name, err))
495 def pop(self, key, force=False):
496 """the list value can be updated (poped)
497 only if the option is a master
499 :param key: index of the element to pop
500 :return: the requested element
503 if self.opt.impl_get_multitype() == multitypes.slave:
504 raise SlaveError(_("cannot pop a value on a multi option {0}"
505 " which is a slave").format(self.opt._name))
506 elif self.opt.impl_get_multitype() == multitypes.master:
507 for slave in self.opt.impl_get_master_slaves():
508 values = self.context().cfgimpl_get_values()
509 if not values.is_default_owner(slave):
510 #get multi without valid properties
511 values.getitem(slave,
512 validate_properties=False
513 ).pop(key, force=True)
514 #set value without valid properties
515 ret = super(Multi, self).pop(key)
516 self.context().cfgimpl_get_values()._setvalue(self.opt, self.path, self, validate_properties=not force)