add some optimisation
[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, ConfigError, 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):
108         for slave in self.getslaves(opt):
109             values.reset(slave, validate=False)
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         if self.is_master(opt):
125             return self._getmaster(values, opt, path, validate,
126                                    force_permissive,
127                                    validate_properties, slave_path,
128                                    slave_value, self_properties, index)
129         else:
130             return self._getslave(values, opt, path, validate,
131                                   force_permissive, trusted_cached_properties,
132                                   validate_properties, setting_properties,
133                                   self_properties, index)
134
135     def _getmaster(self, values, opt, path, validate, force_permissive,
136                    validate_properties, c_slave_path,
137                    c_slave_value, self_properties, index):
138         value = values._get_validated_value(opt, path, validate,
139                                             force_permissive,
140                                             validate_properties,
141                                             self_properties=self_properties,
142                                             index=index)
143         if index is None and validate is True:
144             masterlen = len(value)
145             for slave in self.getslaves(opt):
146                 try:
147                     slave_path = slave.impl_getpath(values._getcontext())
148                     slavelen = values._p_.get_max_length(slave_path)
149                     self.validate_slave_length(masterlen, slavelen, slave.impl_getname(), opt)
150                 except ConfigError:  # pragma: optional cover
151                     pass
152         return value
153
154     def _getslave(self, values, opt, path, validate, force_permissive,
155                   trusted_cached_properties, validate_properties, setting_properties,
156                   self_properties, index):
157         """
158         if master has length 0:
159             return []
160         if master has length bigger than 0:
161             if default owner:
162                 if has callback:
163                     if return a list:
164                         list same length as master: return list
165                         list is smaller than master: return list + None
166                         list is greater than master: raise SlaveError
167                 if has default value:
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_multi value:
172                     return default_multi * master's length
173             if has value:
174                 list same length as master: return list
175                 list is smaller than master: return list + None
176                 list is greater than master: raise SlaveError
177         """
178         master = self.getmaster(opt)
179         context = values._getcontext()
180         masterp = master.impl_getpath(context)
181         masterlen = self.get_length(values, opt, validate, undefined,
182                                     undefined, force_permissive,
183                                     master=master)
184         master_is_meta = values._is_meta(master, masterp)
185         multi = values._get_multi(opt, path)
186         if masterlen == 0:
187             if validate_properties:
188                 context.cfgimpl_get_settings().validate_properties(opt, False,
189                                                                    False,
190                                                                    value=multi,
191                                                                    path=path,
192                                                                    force_permissive=force_permissive,
193                                                                    setting_properties=setting_properties)
194         else:
195             one_has_value = False
196             if index is None:
197                 indexes = range(0, masterlen)
198             else:
199                 indexes = [index]
200             for idx in indexes:
201                 try:
202                     value = values._get_cached_value(opt, path, validate,
203                                                      force_permissive,
204                                                      trusted_cached_properties,
205                                                      validate_properties,
206                                                      with_meta=master_is_meta,
207                                                      index=idx,
208                                                      # not self_properties,
209                                                      # depends to index
210                                                      #self_properties=self_properties,
211                                                      masterlen=masterlen,
212                                                      from_masterslave=True)
213                     multi.append(value, setitem=False, force=True, validate=validate)
214                     one_has_value = True
215                 except PropertiesOptionError, err:
216                     multi.append_properties_error(err)
217             if not one_has_value:
218                 #raise last err
219                 raise err
220         return multi
221
222     def setitem(self, values, opt, value, path):
223         if self.is_master(opt):
224             masterlen = len(value)
225             #for regen slave path
226             base_path = '.'.join(path.split('.')[:-1]) + '.'
227             for slave in self.getslaves(opt):
228                 slave_path = base_path + slave.impl_getname()
229                 slavelen = values._p_.get_max_length(slave_path)
230                 self.validate_slave_length(masterlen, slavelen, slave.impl_getname(), opt)
231         else:
232             self.validate_slave_length(self.get_length(values, opt,
233                                                        slave_path=path), len(value),
234                                        opt.impl_getname(), opt, setitem=True)
235
236     def get_length(self, values, opt, validate=True, slave_path=undefined,
237                    slave_value=undefined, force_permissive=False, master=None,
238                    masterp=None):
239         """get master len with slave option"""
240         if master is None:
241             master = self.getmaster(opt)
242         if masterp is None:
243             masterp = master.impl_getpath(values._getcontext())
244         if slave_value is undefined:
245             slave_path = undefined
246         return len(self.getitem(values, master, masterp, validate,
247                                 force_permissive, None, True, slave_path,
248                                 slave_value))
249
250     def validate_slave_length(self, masterlen, valuelen, name, opt, setitem=False):
251         if valuelen > masterlen or (valuelen < masterlen and setitem):  # pragma: optional cover
252             log.debug('validate_slave_length: masterlen: {0}, valuelen: {1}, '
253                       'setitem: {2}'.format(masterlen, valuelen, setitem))
254             raise SlaveError(_("invalid len for the slave: {0}"
255                                " which has {1} as master").format(
256                                    name, self.getmaster(opt).impl_getname()))