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 # ____________________________________________________________
22 from tiramisu.error import ConfigError, SlaveError
23 from tiramisu.setting import owners, multitypes, expires_time
24 from tiramisu.autolib import carry_out_calculation
25 from tiramisu.i18n import _
26 from tiramisu.option import SymLinkOption
30 """The `Config`'s root is indeed in charge of the `Option()`'s values,
31 but the values are physicaly located here, in `Values`, wich is also
32 responsible of a caching utility.
34 __slots__ = ('context', '_p_')
36 def __init__(self, context, storage):
38 Initializes the values's dict.
40 :param context: the context is the home config's values
43 self.context = context
44 # the storage type is dictionary or sqlite3
45 import_lib = 'tiramisu.storage.{0}.value'.format(storage.storage)
46 self._p_ = __import__(import_lib, globals(), locals(), ['Values'],
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 dictionnary-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)
316 # ____________________________________________________________
321 """multi options values container
322 that support item notation for the values of multi options"""
323 __slots__ = ('opt', 'path', 'context')
325 def __init__(self, value, context, opt, path, validate=True):
327 :param value: the Multi wraps a list value
328 :param context: the home config that has the values
329 :param opt: the option object that have this Multi value
333 self.context = context
334 if not isinstance(value, list):
336 if validate and self.opt.impl_get_multitype() == multitypes.slave:
337 value = self._valid_slave(value)
338 elif self.opt.impl_get_multitype() == multitypes.master:
339 self._valid_master(value)
340 super(Multi, self).__init__(value)
342 def _valid_slave(self, value):
343 #if slave, had values until master's one
344 masterp = self.context.cfgimpl_get_description().impl_get_path_by_opt(
345 self.opt.impl_get_master_slaves())
346 mastervalue = getattr(self.context, masterp)
347 masterlen = len(mastervalue)
348 valuelen = len(value)
349 if valuelen > masterlen or (valuelen < masterlen and
350 not self.context.cfgimpl_get_values(
351 )._is_default_owner(self.path)):
352 raise SlaveError(_("invalid len for the slave: {0}"
353 " which has {1} as master").format(
354 self.opt._name, masterp))
355 elif valuelen < masterlen:
356 for num in range(0, masterlen - valuelen):
357 value.append(self.opt.impl_getdefault_multi())
358 #else: same len so do nothing
361 def _valid_master(self, value):
362 masterlen = len(value)
363 values = self.context.cfgimpl_get_values()
364 for slave in self.opt._master_slaves:
365 path = values._get_opt_path(slave)
366 if not values._is_default_owner(path):
367 value_slave = values._getvalue(slave, path)
368 if len(value_slave) > masterlen:
369 raise SlaveError(_("invalid len for the master: {0}"
370 " which has {1} as slave with"
371 " greater len").format(
372 self.opt._name, slave._name))
373 elif len(value_slave) < masterlen:
374 for num in range(0, masterlen - len(value_slave)):
375 value_slave.append(slave.impl_getdefault_multi(),
378 def __setitem__(self, key, value):
379 self._validate(value)
380 #assume not checking mandatory property
381 super(Multi, self).__setitem__(key, value)
382 self.context.cfgimpl_get_values()._setvalue(self.opt, self.path, self)
384 def append(self, value, force=False):
385 """the list value can be updated (appened)
386 only if the option is a master
389 if self.opt.impl_get_multitype() == multitypes.slave:
390 raise SlaveError(_("cannot append a value on a multi option {0}"
391 " which is a slave").format(self.opt._name))
392 elif self.opt.impl_get_multitype() == multitypes.master:
393 values = self.context.cfgimpl_get_values()
394 if value is None and self.opt.impl_has_callback():
395 value = values._getcallback_value(self.opt)
396 #Force None il return a list
397 if isinstance(value, list):
399 self._validate(value)
400 super(Multi, self).append(value)
401 self.context.cfgimpl_get_values()._setvalue(self.opt, self.path, self, validate_properties=not force)
402 if not force and self.opt.impl_get_multitype() == multitypes.master:
403 for slave in self.opt.impl_get_master_slaves():
404 path = values._get_opt_path(slave)
405 if not values._is_default_owner(path):
406 if slave.impl_has_callback():
407 index = self.__len__() - 1
408 dvalue = values._getcallback_value(slave, index=index)
410 dvalue = slave.impl_getdefault_multi()
411 old_value = values.getitem(slave, path,
412 validate_properties=False)
413 if len(old_value) < self.__len__():
414 values.getitem(slave, path,
415 validate_properties=False).append(
418 values.getitem(slave, path,
419 validate_properties=False)[
422 def sort(self, cmp=None, key=None, reverse=False):
423 if self.opt.impl_get_multitype() in [multitypes.slave,
425 raise SlaveError(_("cannot sort multi option {0} if master or slave"
426 "").format(self.opt._name))
427 super(Multi, self).sort(cmp=cmp, key=key, reverse=reverse)
428 self.context.cfgimpl_get_values()._setvalue(self.opt, self.path, self)
431 if self.opt.impl_get_multitype() in [multitypes.slave,
433 raise SlaveError(_("cannot reverse multi option {0} if master or "
434 "slave").format(self.opt._name))
435 super(Multi, self).reverse()
436 self.context.cfgimpl_get_values()._setvalue(self.opt, self.path, self)
438 def insert(self, index, obj):
439 if self.opt.impl_get_multitype() in [multitypes.slave,
441 raise SlaveError(_("cannot insert multi option {0} if master or "
442 "slave").format(self.opt._name))
443 super(Multi, self).insert(index, obj)
444 self.context.cfgimpl_get_values()._setvalue(self.opt, self.path, self)
446 def extend(self, iterable):
447 if self.opt.impl_get_multitype() in [multitypes.slave,
449 raise SlaveError(_("cannot extend multi option {0} if master or "
450 "slave").format(self.opt._name))
451 super(Multi, self).extend(iterable)
452 self.context.cfgimpl_get_values()._setvalue(self.opt, self.path, self)
454 def _validate(self, value):
455 if value is not None:
457 self.opt._validate(value)
458 except ValueError, err:
459 raise ValueError(_("invalid value {0} "
460 "for option {1}: {2}"
461 "").format(str(value),
462 self.opt._name, err))
464 def pop(self, key, force=False):
465 """the list value can be updated (poped)
466 only if the option is a master
468 :param key: index of the element to pop
469 :return: the requested element
472 if self.opt.impl_get_multitype() == multitypes.slave:
473 raise SlaveError(_("cannot pop a value on a multi option {0}"
474 " which is a slave").format(self.opt._name))
475 elif self.opt.impl_get_multitype() == multitypes.master:
476 for slave in self.opt.impl_get_master_slaves():
477 values = self.context.cfgimpl_get_values()
478 if not values.is_default_owner(slave):
479 #get multi without valid properties
480 values.getitem(slave,
481 validate_properties=False
482 ).pop(key, force=True)
483 #set value without valid properties
484 ret = super(Multi, self).pop(key)
485 self.context.cfgimpl_get_values()._setvalue(self.opt, self.path, self, validate_properties=not force)