69e391fbe91cebc56a6ff887925c32bd2a8bf305
[tiramisu.git] / tiramisu / option / masterslave.py
1 # -*- coding: utf-8 -*-
2 "master slave support"
3 # Copyright (C) 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 # The original `Config` design model is unproudly borrowed from
19 # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
20 # the whole pypy projet is under MIT licence
21 # ____________________________________________________________
22 from ..i18n import _
23 from ..setting import log, undefined
24 from ..error import SlaveError, PropertiesOptionError
25 from .baseoption import DynSymLinkOption, SymLinkOption, Option
26
27
28 class MasterSlaves(object):
29     __slots__ = ('master', 'slaves')
30
31     def __init__(self, name, childs, validate=True):
32         #if master (same name has group) is set
33         #for collect all slaves
34         self.master = None
35         slaves = []
36         for child in childs:
37             if isinstance(child, SymLinkOption):  # pragma: optional cover
38                 raise ValueError(_("master group {0} shall not have "
39                                    "a symlinkoption").format(name))
40             if not isinstance(child, Option):  # pragma: optional cover
41                 raise ValueError(_("master group {0} shall not have "
42                                    "a subgroup").format(name))
43             if not child.impl_is_multi():  # pragma: optional cover
44                 raise ValueError(_("not allowed option {0} "
45                                    "in group {1}"
46                                    ": this option is not a multi"
47                                    "").format(child.impl_getname(), name))
48             if child.impl_getname() == name:
49                 self.master = child
50             else:
51                 if child.impl_getdefault() != []:
52                     raise ValueError(_("not allowed default value for option {0} "
53                                        "in group {1}").format(child.impl_getname(),
54                                                               name))
55                 slaves.append(child)
56         if self.master is None:  # pragma: optional cover
57             raise ValueError(_('master group with wrong'
58                                ' master name for {0}'
59                                ).format(name))
60         if validate:
61             callback, callback_params = self.master.impl_get_callback()
62             if callback is not None and callback_params != {}:  # pragma: optional cover
63                 for key, callbacks in callback_params.items():
64                     for callbk in callbacks:
65                         if isinstance(callbk, tuple):
66                             if callbk[0] in slaves:
67                                 raise ValueError(_("callback of master's option shall "
68                                                    "not refered a slave's ones"))
69         #everything is ok, store references
70         self.slaves = tuple(slaves)
71         for child in childs:
72             child._master_slaves = self
73
74     def is_master(self, opt):
75         return opt == self.master or (isinstance(opt, DynSymLinkOption) and
76                                       opt._opt == self.master)
77
78     def getmaster(self, opt):
79         if isinstance(opt, DynSymLinkOption):
80             suffix = opt.impl_getsuffix()
81             name = self.master.impl_getname() + suffix
82             base_path = opt._dyn.split('.')[0] + '.'
83             path = base_path + name
84             master = self.master._impl_to_dyn(name, path)
85         else:  # pragma: no dynoptiondescription cover
86             master = self.master
87         return master
88
89     def getslaves(self, opt):
90         if isinstance(opt, DynSymLinkOption):
91             for slave in self.slaves:
92                 suffix = opt.impl_getsuffix()
93                 name = slave.impl_getname() + suffix
94                 base_path = opt._dyn.split('.')[0] + '.'
95                 path = base_path + name
96                 yield slave._impl_to_dyn(name, path)
97         else:  # pragma: no dynoptiondescription cover
98             for slave in self.slaves:
99                 yield slave
100
101     def in_same_group(self, opt):
102         if isinstance(opt, DynSymLinkOption):
103             return opt._opt == self.master or opt._opt in self.slaves
104         else:  # pragma: no dynoptiondescription cover
105             return opt == self.master or opt in self.slaves
106
107     def reset(self, opt, values, setting_properties):
108         for slave in self.getslaves(opt):
109             values.reset(slave, validate=False, _setting_properties=setting_properties)
110
111     def pop(self, opt, values, index):
112         for slave in self.getslaves(opt):
113             if not values.is_default_owner(slave, validate_properties=False,
114                                            validate_meta=False, index=index):
115                 values._get_cached_value(slave, validate=False,
116                                          validate_properties=False
117                                          ).pop(index, force=True)
118         pass
119
120     def getitem(self, values, opt, path, validate, force_permissive,
121                 trusted_cached_properties, validate_properties, slave_path=undefined,
122                 slave_value=undefined, setting_properties=undefined,
123                 self_properties=undefined, index=None,
124                 returns_raise=False):
125         if self.is_master(opt):
126             return self._getmaster(values, opt, path, validate,
127                                    force_permissive,
128                                    validate_properties, slave_path,
129                                    slave_value, self_properties, index,
130                                    returns_raise, setting_properties)
131         else:
132             return self._getslave(values, opt, path, validate,
133                                   force_permissive, trusted_cached_properties,
134                                   validate_properties, setting_properties,
135                                   self_properties, index, returns_raise)
136
137     def _getmaster(self, values, opt, path, validate, force_permissive,
138                    validate_properties, c_slave_path,
139                    c_slave_value, self_properties, index, returns_raise,
140                    setting_properties):
141         value = values._get_cached_value(opt, path=path, validate=validate,
142                                          force_permissive=force_permissive,
143                                          validate_properties=validate_properties,
144                                          self_properties=self_properties,
145                                          from_masterslave=True, index=index,
146                                          returns_raise=True,
147                                          setting_properties=setting_properties)
148         if isinstance(value, Exception):
149             return value
150         if index is None and validate is True:
151             masterlen = len(value)
152             for slave in self.getslaves(opt):
153                 slave_path = slave.impl_getpath(values._getcontext())
154                 slavelen = values._p_.get_max_length(slave_path)
155                 self.validate_slave_length(masterlen, slavelen, slave.impl_getname(), opt)
156         return value
157
158     def _getslave(self, values, opt, path, validate, force_permissive,
159                   trusted_cached_properties, validate_properties, setting_properties,
160                   self_properties, index, returns_raise):
161         """
162         if master has length 0:
163             return []
164         if master has length bigger than 0:
165             if default owner:
166                 if has callback:
167                     if return a list:
168                         list same length as master: return list
169                         list is smaller than master: return list + None
170                         list is greater than master: raise SlaveError
171                 if has default value:
172                     list same length as master: return list
173                     list is smaller than master: return list + None
174                     list is greater than master: raise SlaveError
175                 if has default_multi value:
176                     return default_multi * master's length
177             if has value:
178                 list same length as master: return list
179                 list is smaller than master: return list + None
180                 list is greater than master: raise SlaveError
181         """
182         master = self.getmaster(opt)
183         context = values._getcontext()
184         masterp = master.impl_getpath(context)
185         masterlen = self.get_length(values, opt, validate, undefined,
186                                     undefined, force_permissive,
187                                     master=master, returns_raise=returns_raise)
188         if isinstance(masterlen, Exception):
189             return masterlen
190         master_is_meta = values._is_meta(master, masterp)
191         multi = values._get_multi(opt, path)
192         #if masterlen is [], test properties (has no value, don't get any value)
193         if masterlen == 0:
194             if validate_properties:
195                 props = context.cfgimpl_get_settings().validate_properties(opt, False,
196                                                                            False,
197                                                                            value=multi,
198                                                                            path=path,
199                                                                            force_permissive=force_permissive,
200                                                                            setting_properties=setting_properties)
201                 if props:
202                     if returns_raise:
203                         return props
204                     else:
205                         raise props
206         else:
207             one_has_value = False
208             if index is None:
209                 indexes = range(0, masterlen)
210             else:
211                 indexes = [index]
212             for idx in indexes:
213                 value = values._get_cached_value(opt, path, validate,
214                                                  force_permissive,
215                                                  trusted_cached_properties,
216                                                  validate_properties,
217                                                  with_meta=master_is_meta,
218                                                  index=idx,
219                                                  # not self_properties,
220                                                  # depends to index
221                                                  #self_properties=self_properties,
222                                                  masterlen=masterlen,
223                                                  from_masterslave=True,
224                                                  returns_raise=True)
225                 if isinstance(value, Exception):
226                     if isinstance(value, PropertiesOptionError):
227                         err = value
228                         multi.append_properties_error(value)
229                     else:
230                         return value
231                 else:
232                     multi.append(value, setitem=False, force=True, validate=validate,
233                                  force_permissive=force_permissive)
234                     one_has_value = True
235             if not one_has_value:
236                 #raise last err
237                 if returns_raise:
238                     return err
239                 else:
240                     raise err
241         return multi
242
243     def validate(self, values, opt, value, path, returns_raise):
244         if self.is_master(opt):
245             masterlen = len(value)
246             #for regen slave path
247             base_path = '.'.join(path.split('.')[:-1]) + '.'
248             for slave in self.getslaves(opt):
249                 slave_path = base_path + slave.impl_getname()
250                 slavelen = values._p_.get_max_length(slave_path)
251                 self.validate_slave_length(masterlen, slavelen, slave.impl_getname(), opt)
252         else:
253             val_len = self.get_length(values, opt, slave_path=path, returns_raise=returns_raise)
254             if isinstance(val_len, Exception):
255                 return val_len
256             self.validate_slave_length(val_len,
257                                        len(value),
258                                        opt.impl_getname(), opt, setitem=True)
259
260     def get_length(self, values, opt, validate=True, slave_path=undefined,
261                    slave_value=undefined, force_permissive=False, master=None,
262                    masterp=None, returns_raise=False):
263         """get master len with slave option"""
264         if master is None:
265             master = self.getmaster(opt)
266         if masterp is None:
267             masterp = master.impl_getpath(values._getcontext())
268         if slave_value is undefined:
269             slave_path = undefined
270         value = self.getitem(values, master, masterp, validate,
271                              force_permissive, None, True, slave_path,
272                              slave_value, returns_raise=returns_raise)
273         if isinstance(value, Exception):
274             return value
275         return len(value)
276
277     def validate_slave_length(self, masterlen, valuelen, name, opt, setitem=False):
278         if valuelen > masterlen or (valuelen < masterlen and setitem):  # pragma: optional cover
279             log.debug('validate_slave_length: masterlen: {0}, valuelen: {1}, '
280                       'setitem: {2}'.format(masterlen, valuelen, setitem))
281             raise SlaveError(_("invalid len for the slave: {0}"
282                                " which has {1} as master").format(
283                                    name, self.getmaster(opt).impl_getname()))