Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# copyright 2015 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr -- mailto:contact@logilab.fr
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
"""cubicweb-compound specific hooks and operations"""
from cubicweb.predicates import objectify_predicate
from cubicweb.server import hook
@objectify_predicate
def match_clone_rtype(cls, req, *args, **kwargs):
"""Return 1 if `rtype` found in context matches with the `rtype` attribute
of a registered IClonable adapter bound to any of the entities
corresponding to `eidfrom` or `eidto` eids found in context.
"""
rtype = kwargs.get('rtype')
if rtype is None:
return 0
for eidrole in ('eidfrom', 'eidto'):
entity = req.entity_from_eid(kwargs[eidrole])
adapted = entity.cw_adapt_to('IClonable')
if adapted and adapted.rtype == rtype:
return 1
return 0
class CloneEntityHook(hook.Hook):
"""Trigger cloning of an entity upon addition of a <clone_of> relation.
"""
__regid__ = 'compound.clone_entity_hook'
__select__ = hook.Hook.__select__ & match_clone_rtype()
events = ('after_add_relation', )
def __call__(self):
for eid in (self.eidfrom, self.eidto):
original = self._cw.entity_from_eid(eid)
adapted = original.cw_adapt_to('IClonable')
if adapted:
clone = adapted.clone
if clone:
break
else:
raise AssertionError(
'{} unexpectedly selected'.format(self.__regid__))
adapted.clone_into(clone)