Debian Codegraph @

_pytest/vendored_packages/pluggy.py

raw symbols SCIP
1 """
2 PluginManager, basic initialization and tracing.
3
4 pluggy is the cristallized core of plugin management as used
5 by some 150 plugins for pytest.
6
7 Pluggy uses semantic versioning. Breaking changes are only foreseen for
8 Major releases (incremented X in "X.Y.Z"). If you want to use pluggy in
9 your project you should thus use a dependency restriction like
10 "pluggy>=0.1.0,<1.0" to avoid surprises.
11
12 pluggy is concerned with hook specification, hook implementations and hook
13 calling. For any given hook specification a hook call invokes up to N implementations.
14 A hook implementation can influence its position and type of execution:
15 if attributed "tryfirst" or "trylast" it will be tried to execute
16 first or last. However, if attributed "hookwrapper" an implementation
17 can wrap all calls to non-hookwrapper implementations. A hookwrapper
18 can thus execute some code ahead and after the execution of other hooks.
19
20 Hook specification is done by way of a regular python function where
21 both the function name and the names of all its arguments are significant.
22 Each hook implementation function is verified against the original specification
23 function, including the names of all its arguments. To allow for hook specifications
24 to evolve over the livetime of a project, hook implementations can
25 accept less arguments. One can thus add new arguments and semantics to
26 a hook specification by adding another argument typically without breaking
27 existing hook implementations.
28
29 The chosen approach is meant to let a hook designer think carefuly about
30 which objects are needed by an extension writer. By contrast, subclass-based
31 extension mechanisms often expose a lot more state and behaviour than needed,
32 thus restricting future developments.
33
34 Pluggy currently consists of functionality for:
35
36 - a way to register new hook specifications. Without a hook
37 specification no hook calling can be performed.
38
39 - a registry of plugins which contain hook implementation functions. It
40 is possible to register plugins for which a hook specification is not yet
41 known and validate all hooks when the system is in a more referentially
42 consistent state. Setting an "optionalhook" attribution to a hook
43 implementation will avoid PluginValidationError's if a specification
44 is missing. This allows to have optional integration between plugins.
45
46 - a "hook" relay object from which you can launch 1:N calls to
47 registered hook implementation functions
48
49 - a mechanism for ordering hook implementation functions
50
51 - mechanisms for two different type of 1:N calls: "firstresult" for when
52 the call should stop when the first implementation returns a non-None result.
53 And the other (default) way of guaranteeing that all hook implementations
54 will be called and their non-None result collected.
55
56 - mechanisms for "historic" extension points such that all newly
57 registered functions will receive all hook calls that happened
58 before their registration.
59
60 - a mechanism for discovering plugin objects which are based on
61 setuptools based entry points.
62
63 - a simple tracing mechanism, including tracing of plugin calls and
64 their arguments.
65
66 """
67 import sys
68 import inspect
69
70 __version__ = '0.3.1'
71 __all__ = ["PluginManager", "PluginValidationError",
72 "HookspecMarker", "HookimplMarker"]
73
74 _py3 = sys.version_info > (3, 0)
75
76
77 class HookspecMarker:
78 """ Decorator helper class for marking functions as hook specifications.
79
80 You can instantiate it with a project_name to get a decorator.
81 Calling PluginManager.add_hookspecs later will discover all marked functions
82 if the PluginManager uses the same project_name.
83 """
84
85 def __init__(self, project_name):
86 self.project_name = project_name
87
88 def __call__(self, function=None, firstresult=False, historic=False):
89 """ if passed a function, directly sets attributes on the function
90 which will make it discoverable to add_hookspecs(). If passed no
91 function, returns a decorator which can be applied to a function
92 later using the attributes supplied.
93
94 If firstresult is True the 1:N hook call (N being the number of registered
95 hook implementation functions) will stop at I<=N when the I'th function
96 returns a non-None result.
97
98 If historic is True calls to a hook will be memorized and replayed
99 on later registered plugins.
100
101 """
102 def setattr_hookspec_opts(func):
103 if historic and firstresult:
104 raise ValueError("cannot have a historic firstresult hook")
105 setattr(func, self.project_name + "_spec",
106 dict(firstresult=firstresult, historic=historic))
107 return func
108
109 if function is not None:
110 return setattr_hookspec_opts(function)
111 else:
112 return setattr_hookspec_opts
113
114
115 class HookimplMarker:
116 """ Decorator helper class for marking functions as hook implementations.
117
118 You can instantiate with a project_name to get a decorator.
119 Calling PluginManager.register later will discover all marked functions
120 if the PluginManager uses the same project_name.
121 """
122 def __init__(self, project_name):
123 self.project_name = project_name
124
125 def __call__(self, function=None, hookwrapper=False, optionalhook=False,
126 tryfirst=False, trylast=False):
127
128 """ if passed a function, directly sets attributes on the function
129 which will make it discoverable to register(). If passed no function,
130 returns a decorator which can be applied to a function later using
131 the attributes supplied.
132
133 If optionalhook is True a missing matching hook specification will not result
134 in an error (by default it is an error if no matching spec is found).
135
136 If tryfirst is True this hook implementation will run as early as possible
137 in the chain of N hook implementations for a specfication.
138
139 If trylast is True this hook implementation will run as late as possible
140 in the chain of N hook implementations.
141
142 If hookwrapper is True the hook implementations needs to execute exactly
143 one "yield". The code before the yield is run early before any non-hookwrapper
144 function is run. The code after the yield is run after all non-hookwrapper
145 function have run. The yield receives an ``_CallOutcome`` object representing
146 the exception or result outcome of the inner calls (including other hookwrapper
147 calls).
148
149 """
150 def setattr_hookimpl_opts(func):
151 setattr(func, self.project_name + "_impl",
152 dict(hookwrapper=hookwrapper, optionalhook=optionalhook,
153 tryfirst=tryfirst, trylast=trylast))
154 return func
155
156 if function is None:
157 return setattr_hookimpl_opts
158 else:
159 return setattr_hookimpl_opts(function)
160
161
162 def normalize_hookimpl_opts(opts):
163 opts.setdefault("tryfirst", False)
164 opts.setdefault("trylast", False)
165 opts.setdefault("hookwrapper", False)
166 opts.setdefault("optionalhook", False)
167
168
169 class _TagTracer:
170 def __init__(self):
171 self._tag2proc = {}
172 self.writer = None
173 self.indent = 0
174
175 def get(self, name):
176 return _TagTracerSub(self, (name,))
177
178 def format_message(self, tags, args):
179 if isinstance(args[-1], dict):
180 extra = args[-1]
181 args = args[:-1]
182 else:
183 extra = {}
184
185 content = " ".join(map(str, args))
186 indent = " " * self.indent
187
188 lines = [
189 "%s%s [%s]\n" % (indent, content, ":".join(tags))
190 ]
191
192 for name, value in extra.items():
193 lines.append("%s %s: %s\n" % (indent, name, value))
194 return lines
195
196 def processmessage(self, tags, args):
197 if self.writer is not None and args:
198 lines = self.format_message(tags, args)
199 self.writer(''.join(lines))
200 try:
201 self._tag2proc[tags](tags, args)
202 except KeyError:
203 pass
204
205 def setwriter(self, writer):
206 self.writer = writer
207
208 def setprocessor(self, tags, processor):
209 if isinstance(tags, str):
210 tags = tuple(tags.split(":"))
211 else:
212 assert isinstance(tags, tuple)
213 self._tag2proc[tags] = processor
214
215
216 class _TagTracerSub:
217 def __init__(self, root, tags):
218 self.root = root
219 self.tags = tags
220
221 def __call__(self, *args):
222 self.root.processmessage(self.tags, args)
223
224 def setmyprocessor(self, processor):
225 self.root.setprocessor(self.tags, processor)
226
227 def get(self, name):
228 return self.__class__(self.root, self.tags + (name,))
229
230
231 def _raise_wrapfail(wrap_controller, msg):
232 co = wrap_controller.gi_code
233 raise RuntimeError("wrap_controller at %r %s:%d %s" %
234 (co.co_name, co.co_filename, co.co_firstlineno, msg))
235
236
237 def _wrapped_call(wrap_controller, func):
238 """ Wrap calling to a function with a generator which needs to yield
239 exactly once. The yield point will trigger calling the wrapped function
240 and return its _CallOutcome to the yield point. The generator then needs
241 to finish (raise StopIteration) in order for the wrapped call to complete.
242 """
243 try:
244 next(wrap_controller) # first yield
245 except StopIteration:
246 _raise_wrapfail(wrap_controller, "did not yield")
247 call_outcome = _CallOutcome(func)
248 try:
249 wrap_controller.send(call_outcome)
250 _raise_wrapfail(wrap_controller, "has second yield")
251 except StopIteration:
252 pass
253 return call_outcome.get_result()
254
255
256 class _CallOutcome:
257 """ Outcome of a function call, either an exception or a proper result.
258 Calling the ``get_result`` method will return the result or reraise
259 the exception raised when the function was called. """
260 excinfo = None
261
262 def __init__(self, func):
263 try:
264 self.result = func()
265 except BaseException:
266 self.excinfo = sys.exc_info()
267
268 def force_result(self, result):
269 self.result = result
270 self.excinfo = None
271
272 def get_result(self):
273 if self.excinfo is None:
274 return self.result
275 else:
276 ex = self.excinfo
277 if _py3:
278 raise ex[1].with_traceback(ex[2])
279 _reraise(*ex) # noqa
280
281 if not _py3:
282 exec("""
283 def _reraise(cls, val, tb):
284 raise cls, val, tb
285 """)
286
287
288 class _TracedHookExecution:
289 def __init__(self, pluginmanager, before, after):
290 self.pluginmanager = pluginmanager
291 self.before = before
292 self.after = after
293 self.oldcall = pluginmanager._inner_hookexec
294 assert not isinstance(self.oldcall, _TracedHookExecution)
295 self.pluginmanager._inner_hookexec = self
296
297 def __call__(self, hook, hook_impls, kwargs):
298 self.before(hook.name, hook_impls, kwargs)
299 outcome = _CallOutcome(lambda: self.oldcall(hook, hook_impls, kwargs))
300 self.after(outcome, hook.name, hook_impls, kwargs)
301 return outcome.get_result()
302
303 def undo(self):
304 self.pluginmanager._inner_hookexec = self.oldcall
305
306
307 class PluginManager(object):
308 """ Core Pluginmanager class which manages registration
309 of plugin objects and 1:N hook calling.
310
311 You can register new hooks by calling ``addhooks(module_or_class)``.
312 You can register plugin objects (which contain hooks) by calling
313 ``register(plugin)``. The Pluginmanager is initialized with a
314 prefix that is searched for in the names of the dict of registered
315 plugin objects. An optional excludefunc allows to blacklist names which
316 are not considered as hooks despite a matching prefix.
317
318 For debugging purposes you can call ``enable_tracing()``
319 which will subsequently send debug information to the trace helper.
320 """
321
322 def __init__(self, project_name, implprefix=None):
323 """ if implprefix is given implementation functions
324 will be recognized if their name matches the implprefix. """
325 self.project_name = project_name
326 self._name2plugin = {}
327 self._plugin2hookcallers = {}
328 self._plugin_distinfo = []
329 self.trace = _TagTracer().get("pluginmanage")
330 self.hook = _HookRelay(self.trace.root.get("hook"))
331 self._implprefix = implprefix
332 self._inner_hookexec = lambda hook, methods, kwargs: \
333 _MultiCall(methods, kwargs, hook.spec_opts).execute()
334
335 def _hookexec(self, hook, methods, kwargs):
336 # called from all hookcaller instances.
337 # enable_tracing will set its own wrapping function at self._inner_hookexec
338 return self._inner_hookexec(hook, methods, kwargs)
339
340 def register(self, plugin, name=None):
341 """ Register a plugin and return its canonical name or None if the name
342 is blocked from registering. Raise a ValueError if the plugin is already
343 registered. """
344 plugin_name = name or self.get_canonical_name(plugin)
345
346 if plugin_name in self._name2plugin or plugin in self._plugin2hookcallers:
347 if self._name2plugin.get(plugin_name, -1) is None:
348 return # blocked plugin, return None to indicate no registration
349 raise ValueError("Plugin already registered: %s=%s\n%s" %
350 (plugin_name, plugin, self._name2plugin))
351
352 # XXX if an error happens we should make sure no state has been
353 # changed at point of return
354 self._name2plugin[plugin_name] = plugin
355
356 # register matching hook implementations of the plugin
357 self._plugin2hookcallers[plugin] = hookcallers = []
358 for name in dir(plugin):
359 hookimpl_opts = self.parse_hookimpl_opts(plugin, name)
360 if hookimpl_opts is not None:
361 normalize_hookimpl_opts(hookimpl_opts)
362 method = getattr(plugin, name)
363 hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts)
364 hook = getattr(self.hook, name, None)
365 if hook is None:
366 hook = _HookCaller(name, self._hookexec)
367 setattr(self.hook, name, hook)
368 elif hook.has_spec():
369 self._verify_hook(hook, hookimpl)
370 hook._maybe_apply_history(hookimpl)
371 hook._add_hookimpl(hookimpl)
372 hookcallers.append(hook)
373 return plugin_name
374
375 def parse_hookimpl_opts(self, plugin, name):
376 method = getattr(plugin, name)
377 res = getattr(method, self.project_name + "_impl", None)
378 if res is not None and not isinstance(res, dict):
379 # false positive
380 res = None
381 elif res is None and self._implprefix and name.startswith(self._implprefix):
382 res = {}
383 return res
384
385 def unregister(self, plugin=None, name=None):
386 """ unregister a plugin object and all its contained hook implementations
387 from internal data structures. """
388 if name is None:
389 assert plugin is not None, "one of name or plugin needs to be specified"
390 name = self.get_name(plugin)
391
392 if plugin is None:
393 plugin = self.get_plugin(name)
394
395 # if self._name2plugin[name] == None registration was blocked: ignore
396 if self._name2plugin.get(name):
397 del self._name2plugin[name]
398
399 for hookcaller in self._plugin2hookcallers.pop(plugin, []):
400 hookcaller._remove_plugin(plugin)
401
402 return plugin
403
404 def set_blocked(self, name):
405 """ block registrations of the given name, unregister if already registered. """
406 self.unregister(name=name)
407 self._name2plugin[name] = None
408
409 def is_blocked(self, name):
410 """ return True if the name blogs registering plugins of that name. """
411 return name in self._name2plugin and self._name2plugin[name] is None
412
413 def add_hookspecs(self, module_or_class):
414 """ add new hook specifications defined in the given module_or_class.
415 Functions are recognized if they have been decorated accordingly. """
416 names = []
417 for name in dir(module_or_class):
418 spec_opts = self.parse_hookspec_opts(module_or_class, name)
419 if spec_opts is not None:
420 hc = getattr(self.hook, name, None)
421 if hc is None:
422 hc = _HookCaller(name, self._hookexec, module_or_class, spec_opts)
423 setattr(self.hook, name, hc)
424 else:
425 # plugins registered this hook without knowing the spec
426 hc.set_specification(module_or_class, spec_opts)
427 for hookfunction in (hc._wrappers + hc._nonwrappers):
428 self._verify_hook(hc, hookfunction)
429 names.append(name)
430
431 if not names:
432 raise ValueError("did not find any %r hooks in %r" %
433 (self.project_name, module_or_class))
434
435 def parse_hookspec_opts(self, module_or_class, name):
436 method = getattr(module_or_class, name)
437 return getattr(method, self.project_name + "_spec", None)
438
439 def get_plugins(self):
440 """ return the set of registered plugins. """
441 return set(self._plugin2hookcallers)
442
443 def is_registered(self, plugin):
444 """ Return True if the plugin is already registered. """
445 return plugin in self._plugin2hookcallers
446
447 def get_canonical_name(self, plugin):
448 """ Return canonical name for a plugin object. Note that a plugin
449 may be registered under a different name which was specified
450 by the caller of register(plugin, name). To obtain the name
451 of an registered plugin use ``get_name(plugin)`` instead."""
452 return getattr(plugin, "__name__", None) or str(id(plugin))
453
454 def get_plugin(self, name):
455 """ Return a plugin or None for the given name. """
456 return self._name2plugin.get(name)
457
458 def get_name(self, plugin):
459 """ Return name for registered plugin or None if not registered. """
460 for name, val in self._name2plugin.items():
461 if plugin == val:
462 return name
463
464 def _verify_hook(self, hook, hookimpl):
465 if hook.is_historic() and hookimpl.hookwrapper:
466 raise PluginValidationError(
467 "Plugin %r\nhook %r\nhistoric incompatible to hookwrapper" %
468 (hookimpl.plugin_name, hook.name))
469
470 for arg in hookimpl.argnames:
471 if arg not in hook.argnames:
472 raise PluginValidationError(
473 "Plugin %r\nhook %r\nargument %r not available\n"
474 "plugin definition: %s\n"
475 "available hookargs: %s" %
476 (hookimpl.plugin_name, hook.name, arg,
477 _formatdef(hookimpl.function), ", ".join(hook.argnames)))
478
479 def check_pending(self):
480 """ Verify that all hooks which have not been verified against
481 a hook specification are optional, otherwise raise PluginValidationError"""
482 for name in self.hook.__dict__:
483 if name[0] != "_":
484 hook = getattr(self.hook, name)
485 if not hook.has_spec():
486 for hookimpl in (hook._wrappers + hook._nonwrappers):
487 if not hookimpl.optionalhook:
488 raise PluginValidationError(
489 "unknown hook %r in plugin %r" %
490 (name, hookimpl.plugin))
491
492 def load_setuptools_entrypoints(self, entrypoint_name):
493 """ Load modules from querying the specified setuptools entrypoint name.
494 Return the number of loaded plugins. """
495 from pkg_resources import iter_entry_points, DistributionNotFound
496 for ep in iter_entry_points(entrypoint_name):
497 # is the plugin registered or blocked?
498 if self.get_plugin(ep.name) or self.is_blocked(ep.name):
499 continue
500 try:
501 plugin = ep.load()
502 except DistributionNotFound:
503 continue
504 self.register(plugin, name=ep.name)
505 self._plugin_distinfo.append((plugin, ep.dist))
506 return len(self._plugin_distinfo)
507
508 def list_plugin_distinfo(self):
509 """ return list of distinfo/plugin tuples for all setuptools registered
510 plugins. """
511 return list(self._plugin_distinfo)
512
513 def list_name_plugin(self):
514 """ return list of name/plugin pairs. """
515 return list(self._name2plugin.items())
516
517 def get_hookcallers(self, plugin):
518 """ get all hook callers for the specified plugin. """
519 return self._plugin2hookcallers.get(plugin)
520
521 def add_hookcall_monitoring(self, before, after):
522 """ add before/after tracing functions for all hooks
523 and return an undo function which, when called,
524 will remove the added tracers.
525
526 ``before(hook_name, hook_impls, kwargs)`` will be called ahead
527 of all hook calls and receive a hookcaller instance, a list
528 of HookImpl instances and the keyword arguments for the hook call.
529
530 ``after(outcome, hook_name, hook_impls, kwargs)`` receives the
531 same arguments as ``before`` but also a :py:class:`_CallOutcome`` object
532 which represents the result of the overall hook call.
533 """
534 return _TracedHookExecution(self, before, after).undo
535
536 def enable_tracing(self):
537 """ enable tracing of hook calls and return an undo function. """
538 hooktrace = self.hook._trace
539
540 def before(hook_name, methods, kwargs):
541 hooktrace.root.indent += 1
542 hooktrace(hook_name, kwargs)
543
544 def after(outcome, hook_name, methods, kwargs):
545 if outcome.excinfo is None:
546 hooktrace("finish", hook_name, "-->", outcome.result)
547 hooktrace.root.indent -= 1
548
549 return self.add_hookcall_monitoring(before, after)
550
551 def subset_hook_caller(self, name, remove_plugins):
552 """ Return a new _HookCaller instance for the named method
553 which manages calls to all registered plugins except the
554 ones from remove_plugins. """
555 orig = getattr(self.hook, name)
556 plugins_to_remove = [plug for plug in remove_plugins if hasattr(plug, name)]
557 if plugins_to_remove:
558 hc = _HookCaller(orig.name, orig._hookexec, orig._specmodule_or_class,
559 orig.spec_opts)
560 for hookimpl in (orig._wrappers + orig._nonwrappers):
561 plugin = hookimpl.plugin
562 if plugin not in plugins_to_remove:
563 hc._add_hookimpl(hookimpl)
564 # we also keep track of this hook caller so it
565 # gets properly removed on plugin unregistration
566 self._plugin2hookcallers.setdefault(plugin, []).append(hc)
567 return hc
568 return orig
569
570
571 class _MultiCall:
572 """ execute a call into multiple python functions/methods. """
573
574 # XXX note that the __multicall__ argument is supported only
575 # for pytest compatibility reasons. It was never officially
576 # supported there and is explicitly deprecated since 2.8
577 # so we can remove it soon, allowing to avoid the below recursion
578 # in execute() and simplify/speed up the execute loop.
579
580 def __init__(self, hook_impls, kwargs, specopts={}):
581 self.hook_impls = hook_impls
582 self.kwargs = kwargs
583 self.kwargs["__multicall__"] = self
584 self.specopts = specopts
585
586 def execute(self):
587 all_kwargs = self.kwargs
588 self.results = results = []
589 firstresult = self.specopts.get("firstresult")
590
591 while self.hook_impls:
592 hook_impl = self.hook_impls.pop()
593 args = [all_kwargs[argname] for argname in hook_impl.argnames]
594 if hook_impl.hookwrapper:
595 return _wrapped_call(hook_impl.function(*args), self.execute)
596 res = hook_impl.function(*args)
597 if res is not None:
598 if firstresult:
599 return res
600 results.append(res)
601
602 if not firstresult:
603 return results
604
605 def __repr__(self):
606 status = "%d meths" % (len(self.hook_impls),)
607 if hasattr(self, "results"):
608 status = ("%d results, " % len(self.results)) + status
609 return "<_MultiCall %s, kwargs=%r>" % (status, self.kwargs)
610
611
612 def varnames(func, startindex=None):
613 """ return argument name tuple for a function, method, class or callable.
614
615 In case of a class, its "__init__" method is considered.
616 For methods the "self" parameter is not included unless you are passing
617 an unbound method with Python3 (which has no supports for unbound methods)
618 """
619 cache = getattr(func, "__dict__", {})
620 try:
621 return cache["_varnames"]
622 except KeyError:
623 pass
624 if inspect.isclass(func):
625 try:
626 func = func.__init__
627 except AttributeError:
628 return ()
629 startindex = 1
630 else:
631 if not inspect.isfunction(func) and not inspect.ismethod(func):
632 func = getattr(func, '__call__', func)
633 if startindex is None:
634 startindex = int(inspect.ismethod(func))
635
636 try:
637 rawcode = func.__code__
638 except AttributeError:
639 return ()
640 try:
641 x = rawcode.co_varnames[startindex:rawcode.co_argcount]
642 except AttributeError:
643 x = ()
644 else:
645 defaults = func.__defaults__
646 if defaults:
647 x = x[:-len(defaults)]
648 try:
649 cache["_varnames"] = x
650 except TypeError:
651 pass
652 return x
653
654
655 class _HookRelay:
656 """ hook holder object for performing 1:N hook calls where N is the number
657 of registered plugins.
658
659 """
660
661 def __init__(self, trace):
662 self._trace = trace
663
664
665 class _HookCaller(object):
666 def __init__(self, name, hook_execute, specmodule_or_class=None, spec_opts=None):
667 self.name = name
668 self._wrappers = []
669 self._nonwrappers = []
670 self._hookexec = hook_execute
671 if specmodule_or_class is not None:
672 assert spec_opts is not None
673 self.set_specification(specmodule_or_class, spec_opts)
674
675 def has_spec(self):
676 return hasattr(self, "_specmodule_or_class")
677
678 def set_specification(self, specmodule_or_class, spec_opts):
679 assert not self.has_spec()
680 self._specmodule_or_class = specmodule_or_class
681 specfunc = getattr(specmodule_or_class, self.name)
682 argnames = varnames(specfunc, startindex=inspect.isclass(specmodule_or_class))
683 assert "self" not in argnames # sanity check
684 self.argnames = ["__multicall__"] + list(argnames)
685 self.spec_opts = spec_opts
686 if spec_opts.get("historic"):
687 self._call_history = []
688
689 def is_historic(self):
690 return hasattr(self, "_call_history")
691
692 def _remove_plugin(self, plugin):
693 def remove(wrappers):
694 for i, method in enumerate(wrappers):
695 if method.plugin == plugin:
696 del wrappers[i]
697 return True
698 if remove(self._wrappers) is None:
699 if remove(self._nonwrappers) is None:
700 raise ValueError("plugin %r not found" % (plugin,))
701
702 def _add_hookimpl(self, hookimpl):
703 if hookimpl.hookwrapper:
704 methods = self._wrappers
705 else:
706 methods = self._nonwrappers
707
708 if hookimpl.trylast:
709 methods.insert(0, hookimpl)
710 elif hookimpl.tryfirst:
711 methods.append(hookimpl)
712 else:
713 # find last non-tryfirst method
714 i = len(methods) - 1
715 while i >= 0 and methods[i].tryfirst:
716 i -= 1
717 methods.insert(i + 1, hookimpl)
718
719 def __repr__(self):
720 return "<_HookCaller %r>" % (self.name,)
721
722 def __call__(self, **kwargs):
723 assert not self.is_historic()
724 return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
725
726 def call_historic(self, proc=None, kwargs=None):
727 self._call_history.append((kwargs or {}, proc))
728 # historizing hooks don't return results
729 self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
730
731 def call_extra(self, methods, kwargs):
732 """ Call the hook with some additional temporarily participating
733 methods using the specified kwargs as call parameters. """
734 old = list(self._nonwrappers), list(self._wrappers)
735 for method in methods:
736 opts = dict(hookwrapper=False, trylast=False, tryfirst=False)
737 hookimpl = HookImpl(None, "<temp>", method, opts)
738 self._add_hookimpl(hookimpl)
739 try:
740 return self(**kwargs)
741 finally:
742 self._nonwrappers, self._wrappers = old
743
744 def _maybe_apply_history(self, method):
745 if self.is_historic():
746 for kwargs, proc in self._call_history:
747 res = self._hookexec(self, [method], kwargs)
748 if res and proc is not None:
749 proc(res[0])
750
751
752 class HookImpl:
753 def __init__(self, plugin, plugin_name, function, hook_impl_opts):
754 self.function = function
755 self.argnames = varnames(self.function)
756 self.plugin = plugin
757 self.opts = hook_impl_opts
758 self.plugin_name = plugin_name
759 self.__dict__.update(hook_impl_opts)
760
761
762 class PluginValidationError(Exception):
763 """ plugin failed validation. """
764
765
766 if hasattr(inspect, 'signature'):
767 def _formatdef(func):
768 return "%s%s" % (
769 func.__name__,
770 str(inspect.signature(func))
771 )
772 else:
773 def _formatdef(func):
774 return "%s%s" % (
775 func.__name__,
776 inspect.formatargspec(*inspect.getargspec(func))
777 )