author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Tue, 17 Feb 2009 12:47:07 +0100 | |
branch | tls-sprint |
changeset 652 | 603c782dc092 |
parent 646 | 8a9551089912 |
child 660 | 5233a9457f6b |
permissions | -rw-r--r-- |
0 | 1 |
""" |
2 |
* the vregistry handle various type of objects interacting |
|
3 |
together. The vregistry handle registration of dynamically loaded |
|
4 |
objects and provide a convenient api access to those objects |
|
5 |
according to a context |
|
6 |
||
7 |
* to interact with the vregistry, object should inherit from the |
|
8 |
VObject abstract class |
|
9 |
|
|
10 |
* the registration procedure is delegated to a registerer. Each |
|
11 |
registerable vobject must defines its registerer class using the |
|
12 |
__registerer__ attribute. A registerer is instantianted at |
|
13 |
registration time after what the instance is lost |
|
14 |
|
|
15 |
* the selection procedure has been generalized by delegating to a |
|
16 |
selector, which is responsible to score the vobject according to the |
|
17 |
current state (req, rset, row, col). At the end of the selection, if |
|
18 |
a vobject class has been found, an instance of this class is |
|
19 |
returned. The selector is instantiated at vobject registration |
|
20 |
||
21 |
||
22 |
:organization: Logilab |
|
615
38bc11ac845b
don't use chainall when it's not necessary
sylvain.thenault@logilab.fr
parents:
355
diff
changeset
|
23 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
0 | 24 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
25 |
""" |
|
26 |
__docformat__ = "restructuredtext en" |
|
27 |
||
28 |
import sys |
|
29 |
from os import listdir, stat |
|
30 |
from os.path import dirname, join, realpath, split, isdir |
|
31 |
from logging import getLogger |
|
32 |
||
33 |
from cubicweb import CW_SOFTWARE_ROOT, set_log_methods |
|
34 |
from cubicweb import RegistryNotFound, ObjectNotFound, NoSelectableObject |
|
35 |
||
36 |
||
37 |
class vobject_helper(object): |
|
38 |
"""object instantiated at registration time to help a wrapped |
|
39 |
VObject subclass |
|
40 |
""" |
|
41 |
||
42 |
def __init__(self, registry, vobject): |
|
43 |
self.registry = registry |
|
44 |
self.vobject = vobject |
|
45 |
self.config = registry.config |
|
46 |
self.schema = registry.schema |
|
47 |
||
48 |
||
49 |
class registerer(vobject_helper): |
|
50 |
"""do whatever is needed at registration time for the wrapped |
|
51 |
class, according to current application schema and already |
|
52 |
registered objects of the same kind (i.e. same registry name and |
|
53 |
same id). |
|
54 |
||
55 |
The wrapped class may be skipped, some previously selected object |
|
56 |
may be kicked out... After whatever works needed, if the object or |
|
57 |
a transformed object is returned, it will be added to previously |
|
58 |
registered objects. |
|
59 |
""" |
|
60 |
||
61 |
def __init__(self, registry, vobject): |
|
62 |
super(registerer, self).__init__(registry, vobject) |
|
63 |
self.kicked = set() |
|
64 |
||
65 |
def do_it_yourself(self, registered): |
|
66 |
raise NotImplementedError(str(self.vobject)) |
|
67 |
||
68 |
def kick(self, registered, kicked): |
|
355
89ad20af9e4c
oops, these were committed unintentionnally
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
354
diff
changeset
|
69 |
self.debug('kicking vobject %s', kicked) |
0 | 70 |
registered.remove(kicked) |
71 |
self.kicked.add(kicked.classid()) |
|
72 |
||
73 |
def skip(self): |
|
74 |
self.debug('no schema compat, skipping %s', self.vobject) |
|
75 |
||
76 |
||
77 |
def selector(cls, *args, **kwargs): |
|
78 |
"""selector is called to help choosing the correct object for a |
|
79 |
particular request and result set by returning a score. |
|
80 |
||
81 |
it must implement a .score_method taking a request, a result set and |
|
82 |
optionaly row and col arguments which return an int telling how well |
|
83 |
the wrapped class apply to the given request and result set. 0 score |
|
84 |
means that it doesn't apply. |
|
85 |
|
|
86 |
rset may be None. If not, row and col arguments may be optionally |
|
87 |
given if the registry is scoring a given row or a given cell of |
|
88 |
the result set (both row and col are int if provided). |
|
89 |
""" |
|
90 |
raise NotImplementedError(cls) |
|
91 |
||
92 |
||
93 |
class autoselectors(type): |
|
94 |
"""implements __selectors__ / __select__ compatibility layer so that: |
|
95 |
||
96 |
__select__ = chainall(classmethod(A, B, C)) |
|
97 |
||
98 |
can be replaced by something like: |
|
99 |
|
|
100 |
__selectors__ = (A, B, C) |
|
101 |
""" |
|
102 |
def __new__(mcs, name, bases, classdict): |
|
103 |
if '__select__' in classdict and '__selectors__' in classdict: |
|
104 |
raise TypeError("__select__ and __selectors__ " |
|
105 |
"can't be used together") |
|
106 |
if '__select__' not in classdict and '__selectors__' in classdict: |
|
107 |
selectors = classdict['__selectors__'] |
|
615
38bc11ac845b
don't use chainall when it's not necessary
sylvain.thenault@logilab.fr
parents:
355
diff
changeset
|
108 |
if len(selectors) > 1: |
38bc11ac845b
don't use chainall when it's not necessary
sylvain.thenault@logilab.fr
parents:
355
diff
changeset
|
109 |
classdict['__select__'] = classmethod(chainall(*selectors)) |
38bc11ac845b
don't use chainall when it's not necessary
sylvain.thenault@logilab.fr
parents:
355
diff
changeset
|
110 |
else: |
38bc11ac845b
don't use chainall when it's not necessary
sylvain.thenault@logilab.fr
parents:
355
diff
changeset
|
111 |
classdict['__select__'] = classmethod(selectors[0]) |
0 | 112 |
return super(autoselectors, mcs).__new__(mcs, name, bases, classdict) |
113 |
||
114 |
def __setattr__(self, attr, value): |
|
115 |
if attr == '__selectors__': |
|
116 |
self.__select__ = classmethod(chainall(*value)) |
|
117 |
super(autoselectors, self).__setattr__(attr, value) |
|
118 |
||
119 |
||
120 |
class VObject(object): |
|
121 |
"""visual object, use to be handled somehow by the visual components |
|
122 |
registry. |
|
123 |
||
124 |
The following attributes should be set on concret vobject subclasses: |
|
125 |
|
|
126 |
:__registry__: |
|
127 |
name of the registry for this object (string like 'views', |
|
128 |
'templates'...) |
|
129 |
:id: |
|
130 |
object's identifier in the registry (string like 'main', |
|
131 |
'primary', 'folder_box') |
|
132 |
:__registerer__: |
|
133 |
registration helper class |
|
134 |
:__select__: |
|
135 |
selection helper function |
|
136 |
:__selectors__: |
|
137 |
tuple of selectors to be chained |
|
138 |
(__select__ and __selectors__ are mutually exclusive) |
|
139 |
|
|
140 |
Moreover, the `__abstract__` attribute may be set to True to indicate |
|
141 |
that a vobject is abstract and should not be registered |
|
142 |
""" |
|
143 |
__metaclass__ = autoselectors |
|
144 |
# necessary attributes to interact with the registry |
|
145 |
id = None |
|
146 |
__registry__ = None |
|
147 |
__registerer__ = None |
|
148 |
__select__ = None |
|
149 |
||
150 |
@classmethod |
|
151 |
def registered(cls, registry): |
|
152 |
"""called by the registry when the vobject has been registered. |
|
153 |
||
154 |
It must return the object that will be actually registered (this |
|
155 |
may be the right hook to create an instance for example). By |
|
156 |
default the vobject is returned without any transformation. |
|
157 |
""" |
|
158 |
return cls |
|
159 |
||
160 |
@classmethod |
|
161 |
def selected(cls, *args, **kwargs): |
|
162 |
"""called by the registry when the vobject has been selected. |
|
163 |
|
|
164 |
It must return the object that will be actually returned by the |
|
165 |
.select method (this may be the right hook to create an |
|
166 |
instance for example). By default the selected object is |
|
167 |
returned without any transformation. |
|
168 |
""" |
|
169 |
return cls |
|
170 |
||
171 |
@classmethod |
|
172 |
def classid(cls): |
|
173 |
"""returns a unique identifier for the vobject""" |
|
174 |
return '%s.%s' % (cls.__module__, cls.__name__) |
|
175 |
||
176 |
||
177 |
class VRegistry(object): |
|
178 |
"""class responsible to register, propose and select the various |
|
179 |
elements used to build the web interface. Currently, we have templates, |
|
180 |
views, actions and components. |
|
181 |
""" |
|
182 |
||
183 |
def __init__(self, config):#, cache_size=1000): |
|
184 |
self.config = config |
|
185 |
# dictionnary of registry (themself dictionnary) by name |
|
186 |
self._registries = {} |
|
187 |
self._lastmodifs = {} |
|
188 |
||
189 |
def reset(self): |
|
190 |
self._registries = {} |
|
191 |
self._lastmodifs = {} |
|
192 |
||
193 |
def __getitem__(self, key): |
|
194 |
return self._registries[key] |
|
195 |
||
196 |
def get(self, key, default=None): |
|
197 |
return self._registries.get(key, default) |
|
198 |
||
199 |
def items(self): |
|
200 |
return self._registries.items() |
|
201 |
||
202 |
def values(self): |
|
203 |
return self._registries.values() |
|
204 |
||
205 |
def __contains__(self, key): |
|
206 |
return key in self._registries |
|
207 |
||
208 |
def register_vobject_class(self, cls, _kicked=set()): |
|
209 |
"""handle vobject class registration |
|
210 |
|
|
211 |
vobject class with __abstract__ == True in their local dictionnary or |
|
212 |
with a name starting starting by an underscore are not registered. |
|
213 |
Also a vobject class needs to have __registry__ and id attributes set |
|
214 |
to a non empty string to be registered. |
|
215 |
||
216 |
Registration is actually handled by vobject's registerer. |
|
217 |
""" |
|
218 |
if (cls.__dict__.get('__abstract__') or cls.__name__[0] == '_' |
|
219 |
or not cls.__registry__ or not cls.id): |
|
220 |
return |
|
221 |
# while reloading a module : |
|
222 |
# if cls was previously kicked, it means that there is a more specific |
|
223 |
# vobject defined elsewhere re-registering cls would kick it out |
|
224 |
if cls.classid() in _kicked: |
|
225 |
self.debug('not re-registering %s because it was previously kicked', |
|
226 |
cls.classid()) |
|
227 |
else: |
|
228 |
regname = cls.__registry__ |
|
229 |
if cls.id in self.config['disable-%s' % regname]: |
|
230 |
return |
|
231 |
registry = self._registries.setdefault(regname, {}) |
|
232 |
vobjects = registry.setdefault(cls.id, []) |
|
233 |
registerer = cls.__registerer__(self, cls) |
|
234 |
cls = registerer.do_it_yourself(vobjects) |
|
235 |
#_kicked |= registerer.kicked |
|
236 |
if cls: |
|
652
603c782dc092
various SyntaxErrors / missing import fixes + reorganization of the `registered` classmethod
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
646
diff
changeset
|
237 |
# registered() is technically a classmethod but is not declared |
603c782dc092
various SyntaxErrors / missing import fixes + reorganization of the `registered` classmethod
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
646
diff
changeset
|
238 |
# as such because we need to compose registered in some cases |
603c782dc092
various SyntaxErrors / missing import fixes + reorganization of the `registered` classmethod
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
646
diff
changeset
|
239 |
vobject = cls.registered.im_func(cls, self) |
0 | 240 |
try: |
241 |
vname = vobject.__name__ |
|
242 |
except AttributeError: |
|
243 |
vname = vobject.__class__.__name__ |
|
244 |
self.debug('registered vobject %s in registry %s with id %s', |
|
245 |
vname, cls.__registry__, cls.id) |
|
246 |
vobjects.append(vobject) |
|
247 |
||
248 |
def unregister_module_vobjects(self, modname): |
|
249 |
"""removes registered objects coming from a given module |
|
250 |
||
251 |
returns a dictionnary classid/class of all classes that will need |
|
252 |
to be updated after reload (i.e. vobjects referencing classes defined |
|
253 |
in the <modname> module) |
|
254 |
""" |
|
255 |
unregistered = {} |
|
256 |
# browse each registered object |
|
257 |
for registry, objdict in self.items(): |
|
258 |
for oid, objects in objdict.items(): |
|
259 |
for obj in objects[:]: |
|
260 |
objname = obj.classid() |
|
261 |
# if the vobject is defined in this module, remove it |
|
262 |
if objname.startswith(modname): |
|
263 |
unregistered[objname] = obj |
|
264 |
objects.remove(obj) |
|
265 |
self.debug('unregistering %s in %s registry', |
|
266 |
objname, registry) |
|
267 |
# if not, check if the vobject can be found in baseclasses |
|
268 |
# (because we also want subclasses to be updated) |
|
269 |
else: |
|
270 |
if not isinstance(obj, type): |
|
271 |
obj = obj.__class__ |
|
272 |
for baseclass in obj.__bases__: |
|
273 |
if hasattr(baseclass, 'classid'): |
|
274 |
baseclassid = baseclass.classid() |
|
275 |
if baseclassid.startswith(modname): |
|
276 |
unregistered[baseclassid] = baseclass |
|
277 |
# update oid entry |
|
278 |
if objects: |
|
279 |
objdict[oid] = objects |
|
280 |
else: |
|
281 |
del objdict[oid] |
|
282 |
return unregistered |
|
283 |
||
284 |
||
285 |
def update_registered_subclasses(self, oldnew_mapping): |
|
286 |
"""updates subclasses of re-registered vobjects |
|
287 |
||
288 |
if baseviews.PrimaryView is changed, baseviews.py will be reloaded |
|
289 |
automatically and the new version of PrimaryView will be registered. |
|
290 |
But all existing subclasses must also be notified of this change, and |
|
291 |
that's what this method does |
|
292 |
||
293 |
:param oldnew_mapping: a dict mapping old version of a class to |
|
294 |
the new version |
|
295 |
""" |
|
296 |
# browse each registered object |
|
297 |
for objdict in self.values(): |
|
298 |
for objects in objdict.values(): |
|
299 |
for obj in objects: |
|
300 |
if not isinstance(obj, type): |
|
301 |
obj = obj.__class__ |
|
302 |
# build new baseclasses tuple |
|
303 |
newbases = tuple(oldnew_mapping.get(baseclass, baseclass) |
|
304 |
for baseclass in obj.__bases__) |
|
305 |
# update obj's baseclasses tuple (__bases__) if needed |
|
306 |
if newbases != obj.__bases__: |
|
307 |
self.debug('updating %s.%s base classes', |
|
308 |
obj.__module__, obj.__name__) |
|
309 |
obj.__bases__ = newbases |
|
310 |
||
311 |
def registry(self, name): |
|
312 |
"""return the registry (dictionary of class objects) associated to |
|
313 |
this name |
|
314 |
""" |
|
315 |
try: |
|
316 |
return self._registries[name] |
|
317 |
except KeyError: |
|
318 |
raise RegistryNotFound(name), None, sys.exc_info()[-1] |
|
319 |
||
320 |
def registry_objects(self, name, oid=None): |
|
321 |
"""returns objects registered with the given oid in the given registry. |
|
322 |
If no oid is given, return all objects in this registry |
|
323 |
""" |
|
324 |
registry = self.registry(name) |
|
325 |
if oid: |
|
326 |
try: |
|
327 |
return registry[oid] |
|
328 |
except KeyError: |
|
329 |
raise ObjectNotFound(oid), None, sys.exc_info()[-1] |
|
330 |
else: |
|
331 |
result = [] |
|
332 |
for objs in registry.values(): |
|
333 |
result += objs |
|
334 |
return result |
|
335 |
||
336 |
def select(self, vobjects, *args, **kwargs): |
|
337 |
"""return an instance of the most specific object according |
|
338 |
to parameters |
|
339 |
||
340 |
raise NoSelectableObject if not object apply |
|
341 |
""" |
|
177
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
342 |
score, winners = 0, [] |
0 | 343 |
for vobject in vobjects: |
344 |
vobjectscore = vobject.__select__(*args, **kwargs) |
|
345 |
if vobjectscore > score: |
|
177
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
346 |
score, winners = vobjectscore, [vobject] |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
347 |
elif vobjectscore > 0 and vobjectscore == score: |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
348 |
winners.append(vobject) |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
349 |
if not winners: |
0 | 350 |
raise NoSelectableObject('args: %s\nkwargs: %s %s' |
351 |
% (args, kwargs.keys(), [repr(v) for v in vobjects])) |
|
177
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
352 |
if len(winners) > 1: |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
353 |
if self.config.mode == 'installed': |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
354 |
self.error('select ambiguity, args: %s\nkwargs: %s %s', |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
355 |
args, kwargs.keys(), [repr(v) for v in winners]) |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
356 |
else: |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
357 |
raise Exception('select ambiguity, args: %s\nkwargs: %s %s' |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
358 |
% (args, kwargs.keys(), [repr(v) for v in winners])) |
73aa03734425
check we don't get selection ambiguity: if yes, log error in production env, raise in other modes
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
359 |
winner = winners[0] |
0 | 360 |
# return the result of the .selected method of the vobject |
361 |
return winner.selected(*args, **kwargs) |
|
362 |
||
363 |
def possible_objects(self, registry, *args, **kwargs): |
|
364 |
"""return an iterator on possible objects in a registry for this result set |
|
365 |
||
366 |
actions returned are classes, not instances |
|
367 |
""" |
|
368 |
for vobjects in self.registry(registry).values(): |
|
369 |
try: |
|
370 |
yield self.select(vobjects, *args, **kwargs) |
|
371 |
except NoSelectableObject: |
|
372 |
continue |
|
373 |
||
374 |
def select_object(self, registry, cid, *args, **kwargs): |
|
375 |
"""return the most specific component according to the resultset""" |
|
376 |
return self.select(self.registry_objects(registry, cid), *args, **kwargs) |
|
377 |
||
378 |
def object_by_id(self, registry, cid, *args, **kwargs): |
|
379 |
"""return the most specific component according to the resultset""" |
|
380 |
objects = self[registry][cid] |
|
381 |
assert len(objects) == 1, objects |
|
382 |
return objects[0].selected(*args, **kwargs) |
|
383 |
||
384 |
# intialization methods ################################################### |
|
385 |
||
386 |
||
387 |
def register_objects(self, path, force_reload=None): |
|
388 |
if force_reload is None: |
|
389 |
force_reload = self.config.mode == 'dev' |
|
390 |
elif not force_reload: |
|
391 |
# force_reload == False usually mean modules have been reloaded |
|
392 |
# by another connection, so we want to update the registry |
|
393 |
# content even if there has been no module content modification |
|
394 |
self.reset() |
|
395 |
# need to clean sys.path this to avoid import confusion pb (i.e. |
|
396 |
# having the same module loaded as 'cubicweb.web.views' subpackage and |
|
397 |
# as views' or 'web.views' subpackage |
|
398 |
# this is mainly for testing purpose, we should'nt need this in |
|
399 |
# production environment |
|
400 |
for webdir in (join(dirname(realpath(__file__)), 'web'), |
|
401 |
join(dirname(__file__), 'web')): |
|
402 |
if webdir in sys.path: |
|
403 |
sys.path.remove(webdir) |
|
404 |
if CW_SOFTWARE_ROOT in sys.path: |
|
405 |
sys.path.remove(CW_SOFTWARE_ROOT) |
|
406 |
# load views from each directory in the application's path |
|
407 |
change = False |
|
408 |
for fileordirectory in path: |
|
409 |
if isdir(fileordirectory): |
|
410 |
if self.read_directory(fileordirectory, force_reload): |
|
411 |
change = True |
|
412 |
else: |
|
413 |
directory, filename = split(fileordirectory) |
|
414 |
if self.load_file(directory, filename, force_reload): |
|
415 |
change = True |
|
416 |
if change: |
|
417 |
for registry, objects in self.items(): |
|
418 |
self.debug('available in registry %s: %s', registry, |
|
419 |
sorted(objects)) |
|
420 |
return change |
|
421 |
||
422 |
def read_directory(self, directory, force_reload=False): |
|
423 |
"""read a directory and register available views""" |
|
424 |
modified_on = stat(realpath(directory))[-2] |
|
425 |
# only read directory if it was modified |
|
426 |
_lastmodifs = self._lastmodifs |
|
427 |
if directory in _lastmodifs and modified_on <= _lastmodifs[directory]: |
|
428 |
return False |
|
429 |
self.info('loading directory %s', directory) |
|
430 |
for filename in listdir(directory): |
|
431 |
if filename[-3:] == '.py': |
|
432 |
try: |
|
433 |
self.load_file(directory, filename, force_reload) |
|
434 |
except OSError: |
|
435 |
# this typically happens on emacs backup files (.#foo.py) |
|
436 |
self.warning('Unable to load file %s. It is likely to be a backup file', |
|
437 |
filename) |
|
438 |
except Exception, ex: |
|
439 |
if self.config.mode in ('dev', 'test'): |
|
440 |
raise |
|
441 |
self.exception('%r while loading file %s', ex, filename) |
|
442 |
_lastmodifs[directory] = modified_on |
|
443 |
return True |
|
444 |
||
445 |
def load_file(self, directory, filename, force_reload=False): |
|
446 |
"""load visual objects from a python file""" |
|
447 |
from logilab.common.modutils import load_module_from_modpath, modpath_from_file |
|
448 |
filepath = join(directory, filename) |
|
449 |
modified_on = stat(filepath)[-2] |
|
450 |
modpath = modpath_from_file(join(directory, filename)) |
|
451 |
modname = '.'.join(modpath) |
|
452 |
unregistered = {} |
|
453 |
_lastmodifs = self._lastmodifs |
|
454 |
if filepath in _lastmodifs: |
|
455 |
# only load file if it was modified |
|
456 |
if modified_on <= _lastmodifs[filepath]: |
|
457 |
return |
|
458 |
else: |
|
459 |
# if it was modified, unregister all exisiting objects |
|
460 |
# from this module, and keep track of what was unregistered |
|
461 |
unregistered = self.unregister_module_vobjects(modname) |
|
462 |
# load the module |
|
463 |
module = load_module_from_modpath(modpath, use_sys=not force_reload) |
|
464 |
registered = self.load_module(module) |
|
465 |
# if something was unregistered, we need to update places where it was |
|
466 |
# referenced |
|
467 |
if unregistered: |
|
468 |
# oldnew_mapping = {} |
|
469 |
oldnew_mapping = dict((unregistered[name], registered[name]) |
|
470 |
for name in unregistered if name in registered) |
|
471 |
self.update_registered_subclasses(oldnew_mapping) |
|
472 |
_lastmodifs[filepath] = modified_on |
|
473 |
return True |
|
474 |
||
475 |
def load_module(self, module): |
|
476 |
registered = {} |
|
477 |
self.info('loading %s', module) |
|
478 |
for objname, obj in vars(module).items(): |
|
479 |
if objname.startswith('_'): |
|
480 |
continue |
|
481 |
self.load_ancestors_then_object(module.__name__, registered, obj) |
|
482 |
return registered |
|
483 |
||
484 |
def load_ancestors_then_object(self, modname, registered, obj): |
|
485 |
# skip imported classes |
|
486 |
if getattr(obj, '__module__', None) != modname: |
|
487 |
return |
|
488 |
# skip non registerable object |
|
489 |
try: |
|
490 |
if not issubclass(obj, VObject): |
|
491 |
return |
|
492 |
except TypeError: |
|
493 |
return |
|
494 |
objname = '%s.%s' % (modname, obj.__name__) |
|
495 |
if objname in registered: |
|
496 |
return |
|
497 |
registered[objname] = obj |
|
498 |
for parent in obj.__bases__: |
|
499 |
self.load_ancestors_then_object(modname, registered, parent) |
|
500 |
self.load_object(obj) |
|
501 |
||
502 |
def load_object(self, obj): |
|
503 |
try: |
|
504 |
self.register_vobject_class(obj) |
|
505 |
except Exception, ex: |
|
506 |
if self.config.mode in ('test', 'dev'): |
|
507 |
raise |
|
508 |
self.exception('vobject %s registration failed: %s', obj, ex) |
|
509 |
||
510 |
# init logging |
|
511 |
set_log_methods(VObject, getLogger('cubicweb')) |
|
512 |
set_log_methods(VRegistry, getLogger('cubicweb.registry')) |
|
513 |
set_log_methods(registerer, getLogger('cubicweb.registration')) |
|
514 |
||
515 |
||
516 |
# advanced selector building functions ######################################## |
|
517 |
||
623
9dc7b3fa59f1
chainfirst / chainall can be given a name argument to use as inner function's name
sylvain.thenault@logilab.fr
parents:
615
diff
changeset
|
518 |
def chainall(*selectors, **kwargs): |
0 | 519 |
"""return a selector chaining given selectors. If one of |
520 |
the selectors fail, selection will fail, else the returned score |
|
521 |
will be the sum of each selector'score |
|
522 |
""" |
|
523 |
assert selectors |
|
524 |
def selector(cls, *args, **kwargs): |
|
525 |
score = 0 |
|
526 |
for selector in selectors: |
|
527 |
partscore = selector(cls, *args, **kwargs) |
|
528 |
if not partscore: |
|
529 |
return 0 |
|
530 |
score += partscore |
|
531 |
return score |
|
623
9dc7b3fa59f1
chainfirst / chainall can be given a name argument to use as inner function's name
sylvain.thenault@logilab.fr
parents:
615
diff
changeset
|
532 |
if 'name' in kwargs: |
9dc7b3fa59f1
chainfirst / chainall can be given a name argument to use as inner function's name
sylvain.thenault@logilab.fr
parents:
615
diff
changeset
|
533 |
selector.__name__ = kwargs['name'] |
0 | 534 |
return selector |
535 |
||
623
9dc7b3fa59f1
chainfirst / chainall can be given a name argument to use as inner function's name
sylvain.thenault@logilab.fr
parents:
615
diff
changeset
|
536 |
def chainfirst(*selectors, **kwargs): |
0 | 537 |
"""return a selector chaining given selectors. If all |
538 |
the selectors fail, selection will fail, else the returned score |
|
539 |
will be the first non-zero selector score |
|
540 |
""" |
|
541 |
assert selectors |
|
542 |
def selector(cls, *args, **kwargs): |
|
543 |
for selector in selectors: |
|
544 |
partscore = selector(cls, *args, **kwargs) |
|
545 |
if partscore: |
|
546 |
return partscore |
|
547 |
return 0 |
|
623
9dc7b3fa59f1
chainfirst / chainall can be given a name argument to use as inner function's name
sylvain.thenault@logilab.fr
parents:
615
diff
changeset
|
548 |
if 'name' in kwargs: |
9dc7b3fa59f1
chainfirst / chainall can be given a name argument to use as inner function's name
sylvain.thenault@logilab.fr
parents:
615
diff
changeset
|
549 |
selector.__name__ = kwargs['name'] |
0 | 550 |
return selector |
551 |
||
630
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
552 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
553 |
# selector base classes and operations ######################################## |
631
99f5852f8604
major selector refactoring (mostly to avoid looking for select parameters on the target class), start accept / interface unification)
sylvain.thenault@logilab.fr
parents:
630
diff
changeset
|
554 |
|
630
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
555 |
class Selector(object): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
556 |
"""base class for selector classes providing implementation |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
557 |
for operators ``&`` and ``|`` |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
558 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
559 |
This class is only here to give access to binary operators, the |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
560 |
selector logic itself should be implemented in the __call__ method |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
561 |
""" |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
562 |
def __init__(self, *selectors): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
563 |
self.selectors = self.merge_selectors(selectors) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
564 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
565 |
@classmethod |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
566 |
def merge_selectors(cls, selectors): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
567 |
"""merge selectors when possible : |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
568 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
569 |
AndSelector(AndSelector(sel1, sel2), AndSelector(sel3, sel4)) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
570 |
==> AndSelector(sel1, sel2, sel3, sel4) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
571 |
""" |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
572 |
merged_selectors = [] |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
573 |
for selector in selectors: |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
574 |
if isinstance(selector, cls): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
575 |
merged_selectors += selector.selectors |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
576 |
else: |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
577 |
merged_selectors.append(selector) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
578 |
return merged_selectors |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
579 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
580 |
def __and__(self, other): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
581 |
return AndSelector(self, other) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
582 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
583 |
def __or__(self, other): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
584 |
return OrSelector(self, other) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
585 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
586 |
__ror__ = __or__ # for cases like (function | selector) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
587 |
__rand__ = __and__ # for cases like (function & selector) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
588 |
# XXX (function | function) or (function & function) not managed yet |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
589 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
590 |
def __call__(self, cls, *args, **kwargs): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
591 |
return NotImplementedError("selector %s must implement its logic " |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
592 |
"in its __call__ method" % self.__class__.__name__) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
593 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
594 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
595 |
class AndSelector(Selector): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
596 |
"""and-chained selectors (formerly known as chainall)""" |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
597 |
def __call__(self, cls, *args, **kwargs): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
598 |
score = 0 |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
599 |
for selector in self.selectors: |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
600 |
partscore = selector(cls, *args, **kwargs) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
601 |
if not partscore: |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
602 |
return 0 |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
603 |
score += partscore |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
604 |
return score |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
605 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
606 |
|
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
607 |
class OrSelector(Selector): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
608 |
"""or-chained selectors (formerly known as chainfirst)""" |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
609 |
def __call__(self, cls, *args, **kwargs): |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
610 |
for selector in self.selectors: |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
611 |
partscore = selector(cls, *args, **kwargs) |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
612 |
if partscore: |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
613 |
return partscore |
66ff0b2f7d03
simple test implementation for binary operators on selectors
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
615
diff
changeset
|
614 |
return 0 |