7a9057f72c61cf52f092fbfbc0e81d8269414216
[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 tiramisu.i18n import _
23 from tiramisu.setting import log
24 from tiramisu.error import SlaveError, ConfigError
25 from .baseoption import SymLinkOption, Option
26
27
28 class MasterSlaves(object):
29     __slots__ = ('master', 'slaves')
30
31     def __init__(self, name, childs):
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):
38                 raise ValueError(_("master group {0} shall not have "
39                                    "a symlinkoption").format(name))
40             if not isinstance(child, Option):
41                 raise ValueError(_("master group {0} shall not have "
42                                    "a subgroup").format(name))
43             if not child.impl_is_multi():
44                 raise ValueError(_("not allowed option {0} "
45                                    "in group {1}"
46                                    ": this option is not a multi"
47                                    "").format(child._name, name))
48             if child._name == name:
49                 self.master = child
50             else:
51                 slaves.append(child)
52         if self.master is None:
53             raise ValueError(_('master group with wrong'
54                                ' master name for {0}'
55                                ).format(name))
56         callback, callback_params = self.master.impl_get_callback()
57         if callback is not None and callback_params is not None:
58             for key, callbacks in callback_params.items():
59                 for callbk in callbacks:
60                     if isinstance(callbk, tuple):
61                         if callbk[0] in slaves:
62                             raise ValueError(_("callback of master's option shall "
63                                                "not refered a slave's ones"))
64         #everything is ok, store references
65         self.slaves = tuple(slaves)
66         for child in childs:
67             child._master_slaves = self
68
69     def is_master(self, opt):
70         return opt == self.master
71
72     def in_same_group(self, opt):
73         return opt == self.master or opt in self.slaves
74
75     def reset(self, values):
76         for slave in self.slaves:
77             values.reset(slave)
78
79     def pop(self, values, index):
80         #FIXME pas test de meta ...
81         for slave in self.slaves:
82             if not values.is_default_owner(slave, validate_properties=False,
83                                            validate_meta=False):
84                 values._get_cached_item(slave, validate=False,
85                                         validate_properties=False
86                                         ).pop(index, force=True)
87         pass
88
89     def getitem(self, values, opt, path, validate, force_permissive,
90                 force_properties, validate_properties):
91         if opt == self.master:
92             return self._getmaster(values, opt, path, validate,
93                                    force_permissive, force_properties,
94                                    validate_properties)
95         else:
96             return self._getslave(values, opt, path, validate,
97                                   force_permissive, force_properties,
98                                   validate_properties)
99
100     def _getmaster(self, values, opt, path, validate, force_permissive,
101                    force_properties, validate_properties):
102         value = values._get_validated_value(opt, path, validate,
103                                             force_permissive,
104                                             force_properties,
105                                             validate_properties)
106         if validate is True:
107             masterlen = len(value)
108             for slave in self.slaves:
109                 try:
110                     slave_path = values._get_opt_path(slave)
111                     slave_value = values._get_validated_value(slave,
112                                                               slave_path,
113                                                               False,
114                                                               False,
115                                                               None, False,
116                                                               None)  # not undefined
117                     slavelen = len(slave_value)
118                     self.validate_slave_length(masterlen, slavelen, slave._name)
119                 except ConfigError:
120                     pass
121         return value
122
123     def _getslave(self, values, opt, path, validate, force_permissive,
124                   force_properties, validate_properties):
125         value = values._get_validated_value(opt, path, validate,
126                                             force_permissive,
127                                             force_properties,
128                                             validate_properties,
129                                             None)  # not undefined
130         return self.get_slave_value(values, opt, value, validate, validate_properties)
131
132     def setitem(self, values, opt, value, path):
133         if opt == self.master:
134             masterlen = len(value)
135             for slave in self.slaves:
136                 slave_path = values._get_opt_path(slave)
137                 slave_value = values._get_validated_value(slave,
138                                                           slave_path,
139                                                           False,
140                                                           False,
141                                                           None, False,
142                                                           None)  # not undefined
143                 slavelen = len(slave_value)
144                 self.validate_slave_length(masterlen, slavelen, slave._name)
145         else:
146             self.validate_slave_length(self.get_length(values), len(value),
147                                        opt._name, setitem=True)
148
149     def get_length(self, values, validate=True):
150         masterp = values._get_opt_path(self.master)
151         return len(self.getitem(values, self.master, masterp, validate, False,
152                                 None, True))
153
154     def validate_slave_length(self, masterlen, valuelen, name, setitem=False):
155         if valuelen > masterlen or (valuelen < masterlen and setitem):
156             log.debug('validate_slave_length: masterlen: {0}, valuelen: {1}, '
157                       'setitem: {2}'.format(masterlen, valuelen, setitem))
158             raise SlaveError(_("invalid len for the slave: {0}"
159                                " which has {1} as master").format(
160                                    name, self.master._name))
161
162     def get_slave_value(self, values, opt, value, validate=True,
163                         validate_properties=True):
164         """
165         if master has length 0:
166             return []
167         if master has length bigger than 0:
168             if default owner:
169                 if has callback:
170                     if return a list:
171                         list same length as master: return list
172                         list is smaller than master: return list + None
173                         list is greater than master: raise SlaveError
174                 if has default value:
175                     list same length as master: return list
176                     list is smaller than master: return list + None
177                     list is greater than master: raise SlaveError
178                 if has default_multi value:
179                     return default_multi * master's length
180             if has value:
181                 list same length as master: return list
182                 list is smaller than master: return list + None
183                 list is greater than master: raise SlaveError
184         """
185         #if slave, had values until master's one
186         masterlen = self.get_length(values, validate)
187         valuelen = len(value)
188         if validate:
189             self.validate_slave_length(masterlen, valuelen, opt._name)
190         path = values._get_opt_path(opt)
191         if valuelen < masterlen:
192             for num in range(0, masterlen - valuelen):
193                 index = valuelen + num
194                 value.append(values._get_validated_value(opt, path, True,
195                                                          False, None,
196                                                          validate_properties,
197                                                          index=index),
198                              setitem=False,
199                              force=True)
200         return value