2010-11-06 06:37:31 +08:00
|
|
|
"""
|
2015-04-22 19:31:46 +08:00
|
|
|
PluginManager, basic initialization and tracing.
|
2010-11-06 06:37:31 +08:00
|
|
|
"""
|
2013-10-02 20:32:40 +08:00
|
|
|
import sys
|
2015-04-25 19:38:30 +08:00
|
|
|
from inspect import isfunction, ismethod, isclass, formatargspec, getargspec
|
2010-10-12 18:54:32 +08:00
|
|
|
import py
|
2010-10-13 03:59:15 +08:00
|
|
|
|
2014-10-08 17:27:14 +08:00
|
|
|
py3 = sys.version_info > (3,0)
|
|
|
|
|
2015-04-25 17:29:11 +08:00
|
|
|
def hookspec_opts(firstresult=False, historic=False):
|
2015-04-25 17:29:11 +08:00
|
|
|
""" returns a decorator which will define a function as a hook specfication.
|
|
|
|
|
|
|
|
If firstresult is True the 1:N hook call (N being the number of registered
|
|
|
|
hook implementation functions) will stop at I<=N when the I'th function
|
|
|
|
returns a non-None result.
|
2015-04-25 17:29:11 +08:00
|
|
|
|
|
|
|
If historic is True calls to a hook will be memorized and replayed
|
|
|
|
on later registered plugins.
|
2015-04-25 17:29:11 +08:00
|
|
|
"""
|
|
|
|
def setattr_hookspec_opts(func):
|
2015-04-25 17:29:11 +08:00
|
|
|
if historic and firstresult:
|
|
|
|
raise ValueError("cannot have a historic firstresult hook")
|
2015-04-25 17:29:11 +08:00
|
|
|
if firstresult:
|
|
|
|
func.firstresult = firstresult
|
2015-04-25 17:29:11 +08:00
|
|
|
if historic:
|
|
|
|
func.historic = historic
|
2015-04-25 17:29:11 +08:00
|
|
|
return func
|
|
|
|
return setattr_hookspec_opts
|
|
|
|
|
|
|
|
|
|
|
|
def hookimpl_opts(hookwrapper=False, optionalhook=False,
|
|
|
|
tryfirst=False, trylast=False):
|
|
|
|
""" Return a decorator which marks a function as a hook implementation.
|
|
|
|
|
|
|
|
If optionalhook is True a missing matching hook specification will not result
|
|
|
|
in an error (by default it is an error if no matching spec is found).
|
|
|
|
|
|
|
|
If tryfirst is True this hook implementation will run as early as possible
|
|
|
|
in the chain of N hook implementations for a specfication.
|
|
|
|
|
|
|
|
If trylast is True this hook implementation will run as late as possible
|
|
|
|
in the chain of N hook implementations.
|
|
|
|
|
|
|
|
If hookwrapper is True the hook implementations needs to execute exactly
|
|
|
|
one "yield". The code before the yield is run early before any non-hookwrapper
|
|
|
|
function is run. The code after the yield is run after all non-hookwrapper
|
|
|
|
function have run. The yield receives an ``CallOutcome`` object representing
|
|
|
|
the exception or result outcome of the inner calls (including other hookwrapper
|
|
|
|
calls).
|
|
|
|
"""
|
|
|
|
def setattr_hookimpl_opts(func):
|
|
|
|
if hookwrapper:
|
|
|
|
func.hookwrapper = True
|
|
|
|
if optionalhook:
|
|
|
|
func.optionalhook = True
|
|
|
|
if tryfirst:
|
|
|
|
func.tryfirst = True
|
|
|
|
if trylast:
|
|
|
|
func.trylast = True
|
|
|
|
return func
|
|
|
|
return setattr_hookimpl_opts
|
|
|
|
|
2015-04-26 00:15:39 +08:00
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
class TagTracer:
|
2011-07-15 01:11:50 +08:00
|
|
|
def __init__(self):
|
2010-11-06 06:37:31 +08:00
|
|
|
self._tag2proc = {}
|
|
|
|
self.writer = None
|
2010-11-06 16:05:17 +08:00
|
|
|
self.indent = 0
|
2010-11-06 06:37:31 +08:00
|
|
|
|
|
|
|
def get(self, name):
|
|
|
|
return TagTracerSub(self, (name,))
|
|
|
|
|
2012-11-29 17:04:39 +08:00
|
|
|
def format_message(self, tags, args):
|
|
|
|
if isinstance(args[-1], dict):
|
|
|
|
extra = args[-1]
|
|
|
|
args = args[:-1]
|
|
|
|
else:
|
|
|
|
extra = {}
|
|
|
|
|
|
|
|
content = " ".join(map(str, args))
|
|
|
|
indent = " " * self.indent
|
2013-02-04 23:07:51 +08:00
|
|
|
|
2012-11-29 17:04:39 +08:00
|
|
|
lines = [
|
|
|
|
"%s%s [%s]\n" %(indent, content, ":".join(tags))
|
|
|
|
]
|
|
|
|
|
|
|
|
for name, value in extra.items():
|
|
|
|
lines.append("%s %s: %s\n" % (indent, name, value))
|
|
|
|
return lines
|
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
def processmessage(self, tags, args):
|
2012-11-29 17:04:39 +08:00
|
|
|
if self.writer is not None and args:
|
|
|
|
lines = self.format_message(tags, args)
|
|
|
|
self.writer(''.join(lines))
|
2010-11-06 06:37:31 +08:00
|
|
|
try:
|
|
|
|
self._tag2proc[tags](tags, args)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def setwriter(self, writer):
|
|
|
|
self.writer = writer
|
|
|
|
|
|
|
|
def setprocessor(self, tags, processor):
|
|
|
|
if isinstance(tags, str):
|
|
|
|
tags = tuple(tags.split(":"))
|
|
|
|
else:
|
|
|
|
assert isinstance(tags, tuple)
|
|
|
|
self._tag2proc[tags] = processor
|
|
|
|
|
2015-04-26 00:15:39 +08:00
|
|
|
|
2010-11-06 06:37:31 +08:00
|
|
|
class TagTracerSub:
|
|
|
|
def __init__(self, root, tags):
|
|
|
|
self.root = root
|
|
|
|
self.tags = tags
|
|
|
|
def __call__(self, *args):
|
|
|
|
self.root.processmessage(self.tags, args)
|
|
|
|
def setmyprocessor(self, processor):
|
|
|
|
self.root.setprocessor(self.tags, processor)
|
|
|
|
def get(self, name):
|
|
|
|
return self.__class__(self.root, self.tags + (name,))
|
|
|
|
|
2014-10-07 22:16:47 +08:00
|
|
|
|
2014-10-09 18:21:01 +08:00
|
|
|
def raise_wrapfail(wrap_controller, msg):
|
|
|
|
co = wrap_controller.gi_code
|
|
|
|
raise RuntimeError("wrap_controller at %r %s:%d %s" %
|
|
|
|
(co.co_name, co.co_filename, co.co_firstlineno, msg))
|
2014-10-04 21:49:31 +08:00
|
|
|
|
2014-10-08 17:27:14 +08:00
|
|
|
def wrapped_call(wrap_controller, func):
|
2014-10-09 18:21:01 +08:00
|
|
|
""" Wrap calling to a function with a generator which needs to yield
|
|
|
|
exactly once. The yield point will trigger calling the wrapped function
|
|
|
|
and return its CallOutcome to the yield point. The generator then needs
|
|
|
|
to finish (raise StopIteration) in order for the wrapped call to complete.
|
2014-10-08 17:27:14 +08:00
|
|
|
"""
|
2014-10-09 02:23:40 +08:00
|
|
|
try:
|
|
|
|
next(wrap_controller) # first yield
|
|
|
|
except StopIteration:
|
2014-10-09 18:21:01 +08:00
|
|
|
raise_wrapfail(wrap_controller, "did not yield")
|
2014-10-08 17:27:14 +08:00
|
|
|
call_outcome = CallOutcome(func)
|
|
|
|
try:
|
|
|
|
wrap_controller.send(call_outcome)
|
2014-10-09 18:21:01 +08:00
|
|
|
raise_wrapfail(wrap_controller, "has second yield")
|
2014-10-08 17:27:14 +08:00
|
|
|
except StopIteration:
|
|
|
|
pass
|
2014-10-09 02:23:40 +08:00
|
|
|
return call_outcome.get_result()
|
2014-10-08 17:27:14 +08:00
|
|
|
|
|
|
|
|
|
|
|
class CallOutcome:
|
2014-10-09 18:21:01 +08:00
|
|
|
""" Outcome of a function call, either an exception or a proper result.
|
|
|
|
Calling the ``get_result`` method will return the result or reraise
|
|
|
|
the exception raised when the function was called. """
|
2014-10-08 17:27:14 +08:00
|
|
|
excinfo = None
|
|
|
|
def __init__(self, func):
|
|
|
|
try:
|
|
|
|
self.result = func()
|
2015-04-17 17:47:29 +08:00
|
|
|
except BaseException:
|
2014-10-08 17:27:14 +08:00
|
|
|
self.excinfo = sys.exc_info()
|
|
|
|
|
|
|
|
def force_result(self, result):
|
|
|
|
self.result = result
|
|
|
|
self.excinfo = None
|
|
|
|
|
2014-10-09 02:23:40 +08:00
|
|
|
def get_result(self):
|
|
|
|
if self.excinfo is None:
|
|
|
|
return self.result
|
|
|
|
else:
|
|
|
|
ex = self.excinfo
|
|
|
|
if py3:
|
|
|
|
raise ex[1].with_traceback(ex[2])
|
|
|
|
py.builtin._reraise(*ex)
|
|
|
|
|
2014-10-08 17:27:14 +08:00
|
|
|
|
2015-04-26 00:15:39 +08:00
|
|
|
class TracedHookExecution:
|
|
|
|
def __init__(self, pluginmanager, before, after):
|
|
|
|
self.pluginmanager = pluginmanager
|
|
|
|
self.before = before
|
|
|
|
self.after = after
|
|
|
|
self.oldcall = pluginmanager._inner_hookexec
|
|
|
|
assert not isinstance(self.oldcall, TracedHookExecution)
|
|
|
|
self.pluginmanager._inner_hookexec = self
|
|
|
|
|
|
|
|
def __call__(self, hook, methods, kwargs):
|
|
|
|
self.before(hook, methods, kwargs)
|
|
|
|
outcome = CallOutcome(lambda: self.oldcall(hook, methods, kwargs))
|
|
|
|
self.after(outcome, hook, methods, kwargs)
|
|
|
|
return outcome.get_result()
|
|
|
|
|
|
|
|
def undo(self):
|
|
|
|
self.pluginmanager._inner_hookexec = self.oldcall
|
|
|
|
|
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
class PluginManager(object):
|
2015-04-22 22:33:20 +08:00
|
|
|
""" Core Pluginmanager class which manages registration
|
|
|
|
of plugin objects and 1:N hook calling.
|
|
|
|
|
|
|
|
You can register new hooks by calling ``addhooks(module_or_class)``.
|
|
|
|
You can register plugin objects (which contain hooks) by calling
|
|
|
|
``register(plugin)``. The Pluginmanager is initialized with a
|
|
|
|
prefix that is searched for in the names of the dict of registered
|
|
|
|
plugin objects. An optional excludefunc allows to blacklist names which
|
|
|
|
are not considered as hooks despite a matching prefix.
|
|
|
|
|
|
|
|
For debugging purposes you can call ``set_tracing(writer)``
|
|
|
|
which will subsequently send debug information to the specified
|
|
|
|
write function.
|
|
|
|
"""
|
|
|
|
|
2015-04-22 19:31:46 +08:00
|
|
|
def __init__(self, prefix, excludefunc=None):
|
|
|
|
self._prefix = prefix
|
|
|
|
self._excludefunc = excludefunc
|
2010-10-12 18:54:32 +08:00
|
|
|
self._name2plugin = {}
|
2010-10-13 17:12:27 +08:00
|
|
|
self._plugins = []
|
2014-10-09 16:47:32 +08:00
|
|
|
self._plugin2hookcallers = {}
|
2010-11-06 16:05:17 +08:00
|
|
|
self.trace = TagTracer().get("pluginmanage")
|
2015-04-26 00:15:39 +08:00
|
|
|
self.hook = HookRelay(self.trace.root.get("hook"))
|
|
|
|
self._inner_hookexec = lambda hook, methods, kwargs: \
|
|
|
|
MultiCall(methods, kwargs, hook.firstresult).execute()
|
2013-09-30 19:14:14 +08:00
|
|
|
|
2015-04-26 00:15:39 +08:00
|
|
|
def _hookexec(self, hook, methods, kwargs):
|
|
|
|
return self._inner_hookexec(hook, methods, kwargs)
|
2014-10-04 21:49:31 +08:00
|
|
|
|
2015-04-26 00:15:39 +08:00
|
|
|
def enable_tracing(self):
|
|
|
|
""" enable tracing of hook calls and return an undo function. """
|
|
|
|
hooktrace = self.hook._trace
|
2015-04-24 19:02:49 +08:00
|
|
|
|
2015-04-26 00:15:39 +08:00
|
|
|
def before(hook, methods, kwargs):
|
2015-04-24 19:02:49 +08:00
|
|
|
hooktrace.root.indent += 1
|
2015-04-26 00:15:39 +08:00
|
|
|
hooktrace(hook.name, kwargs)
|
|
|
|
|
|
|
|
def after(outcome, hook, methods, kwargs):
|
|
|
|
if outcome.excinfo is None:
|
|
|
|
hooktrace("finish", hook.name, "-->", outcome.result)
|
2015-04-24 19:02:49 +08:00
|
|
|
hooktrace.root.indent -= 1
|
2014-10-04 21:49:31 +08:00
|
|
|
|
2015-04-26 00:15:39 +08:00
|
|
|
return TracedHookExecution(self, before, after).undo
|
2013-10-04 17:36:45 +08:00
|
|
|
|
2015-04-22 19:31:46 +08:00
|
|
|
def make_hook_caller(self, name, plugins):
|
|
|
|
caller = getattr(self.hook, name)
|
2015-04-26 00:15:39 +08:00
|
|
|
hc = HookCaller(caller.name, self._hookexec, caller._specmodule_or_class)
|
2015-04-26 00:14:39 +08:00
|
|
|
for plugin in plugins:
|
|
|
|
if hasattr(plugin, name):
|
|
|
|
hc._add_plugin(plugin)
|
|
|
|
# we also keep track of this hook caller so it
|
|
|
|
# gets properly removed on plugin unregistration
|
|
|
|
self._plugin2hookcallers.setdefault(plugin, []).append(hc)
|
|
|
|
return hc
|
2015-04-22 19:31:46 +08:00
|
|
|
|
2015-04-22 19:33:01 +08:00
|
|
|
def register(self, plugin, name=None):
|
2015-04-22 22:42:41 +08:00
|
|
|
""" Register a plugin with the given name and ensure that all its
|
|
|
|
hook implementations are integrated. If the name is not specified
|
|
|
|
we use the ``__name__`` attribute of the plugin object or, if that
|
|
|
|
doesn't exist, the id of the plugin. This method will raise a
|
|
|
|
ValueError if the eventual name is already registered. """
|
2015-04-22 20:54:28 +08:00
|
|
|
name = name or self._get_canonical_name(plugin)
|
2012-06-17 03:29:04 +08:00
|
|
|
if self._name2plugin.get(name, None) == -1:
|
|
|
|
return
|
2015-04-22 20:54:28 +08:00
|
|
|
if self.hasplugin(name):
|
2013-09-30 19:14:14 +08:00
|
|
|
raise ValueError("Plugin already registered: %s=%s\n%s" %(
|
|
|
|
name, plugin, self._name2plugin))
|
2014-10-01 18:20:11 +08:00
|
|
|
self._name2plugin[name] = plugin
|
2015-04-22 19:33:01 +08:00
|
|
|
self._plugins.append(plugin)
|
2015-04-26 00:15:42 +08:00
|
|
|
|
|
|
|
# register prefix-matching hooks of the plugin
|
|
|
|
self._plugin2hookcallers[plugin] = hookcallers = []
|
|
|
|
for name in dir(plugin):
|
|
|
|
if name.startswith(self._prefix):
|
|
|
|
hook = getattr(self.hook, name, None)
|
|
|
|
if hook is None:
|
|
|
|
if self._excludefunc is not None and self._excludefunc(name):
|
|
|
|
continue
|
|
|
|
hook = HookCaller(name, self._hookexec)
|
|
|
|
setattr(self.hook, name, hook)
|
|
|
|
elif hook.has_spec():
|
|
|
|
self._verify_hook(hook, plugin)
|
|
|
|
hook._maybe_apply_history(getattr(plugin, name))
|
|
|
|
hookcallers.append(hook)
|
|
|
|
hook._add_plugin(plugin)
|
2010-10-12 18:54:32 +08:00
|
|
|
return True
|
|
|
|
|
2014-10-09 16:47:32 +08:00
|
|
|
def unregister(self, plugin):
|
2015-04-22 22:42:41 +08:00
|
|
|
""" unregister the plugin object and all its contained hook implementations
|
|
|
|
from internal data structures. """
|
2015-04-22 19:33:01 +08:00
|
|
|
self._plugins.remove(plugin)
|
2010-10-12 18:54:32 +08:00
|
|
|
for name, value in list(self._name2plugin.items()):
|
|
|
|
if value == plugin:
|
|
|
|
del self._name2plugin[name]
|
2015-04-26 00:14:39 +08:00
|
|
|
for hookcaller in self._plugin2hookcallers.pop(plugin):
|
|
|
|
hookcaller._remove_plugin(plugin)
|
2010-10-12 18:54:32 +08:00
|
|
|
|
2015-04-22 19:31:46 +08:00
|
|
|
def addhooks(self, module_or_class):
|
2015-04-22 22:42:41 +08:00
|
|
|
""" add new hook definitions from the given module_or_class using
|
|
|
|
the prefix/excludefunc with which the PluginManager was initialized. """
|
2015-04-22 19:31:46 +08:00
|
|
|
names = []
|
|
|
|
for name in dir(module_or_class):
|
|
|
|
if name.startswith(self._prefix):
|
2015-04-25 17:29:11 +08:00
|
|
|
hc = getattr(self.hook, name, None)
|
|
|
|
if hc is None:
|
2015-04-26 00:15:39 +08:00
|
|
|
hc = HookCaller(name, self._hookexec, module_or_class)
|
2015-04-25 17:29:11 +08:00
|
|
|
setattr(self.hook, name, hc)
|
|
|
|
else:
|
|
|
|
# plugins registered this hook without knowing the spec
|
2015-04-26 00:14:39 +08:00
|
|
|
hc.set_specification(module_or_class)
|
2015-04-25 19:38:29 +08:00
|
|
|
for plugin in hc._plugins:
|
|
|
|
self._verify_hook(hc, plugin)
|
2015-04-22 19:31:46 +08:00
|
|
|
names.append(name)
|
|
|
|
if not names:
|
|
|
|
raise ValueError("did not find new %r hooks in %r"
|
|
|
|
%(self._prefix, module_or_class))
|
2010-10-12 18:54:32 +08:00
|
|
|
|
|
|
|
def getplugins(self):
|
2015-04-22 22:42:41 +08:00
|
|
|
""" return the complete list of registered plugins. NOTE that
|
|
|
|
you will get the internal list and need to make a copy if you
|
|
|
|
modify the list."""
|
2015-04-22 19:33:01 +08:00
|
|
|
return self._plugins
|
2010-10-12 18:54:32 +08:00
|
|
|
|
2015-04-22 20:54:28 +08:00
|
|
|
def isregistered(self, plugin):
|
2015-04-22 22:42:41 +08:00
|
|
|
""" Return True if the plugin is already registered under its
|
|
|
|
canonical name. """
|
2015-04-22 20:54:28 +08:00
|
|
|
return self.hasplugin(self._get_canonical_name(plugin)) or \
|
|
|
|
plugin in self._plugins
|
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
def hasplugin(self, name):
|
2015-04-22 22:42:41 +08:00
|
|
|
""" Return True if there is a registered with the given name. """
|
2015-04-22 20:54:28 +08:00
|
|
|
return name in self._name2plugin
|
2008-08-16 23:26:59 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
def getplugin(self, name):
|
2015-04-22 22:42:41 +08:00
|
|
|
""" Return a plugin or None for the given name. """
|
2015-04-22 19:31:46 +08:00
|
|
|
return self._name2plugin.get(name)
|
2010-10-12 18:54:32 +08:00
|
|
|
|
2015-04-25 19:38:29 +08:00
|
|
|
def _verify_hook(self, hook, plugin):
|
|
|
|
method = getattr(plugin, hook.name)
|
2015-04-26 00:15:42 +08:00
|
|
|
pluginname = self._get_canonical_name(plugin)
|
|
|
|
if hook.is_historic() and hasattr(method, "hookwrapper"):
|
|
|
|
raise PluginValidationError(
|
|
|
|
"Plugin %r\nhook %r\nhistoric incompatible to hookwrapper" %(
|
|
|
|
pluginname, hook.name))
|
|
|
|
|
2015-04-25 17:29:11 +08:00
|
|
|
for arg in varnames(method):
|
|
|
|
if arg not in hook.argnames:
|
|
|
|
raise PluginValidationError(
|
|
|
|
"Plugin %r\nhook %r\nargument %r not available\n"
|
|
|
|
"plugin definition: %s\n"
|
|
|
|
"available hookargs: %s" %(
|
|
|
|
pluginname, hook.name, arg, formatdef(method),
|
|
|
|
", ".join(hook.argnames)))
|
|
|
|
|
|
|
|
def check_pending(self):
|
|
|
|
for name in self.hook.__dict__:
|
|
|
|
if name.startswith(self._prefix):
|
|
|
|
hook = getattr(self.hook, name)
|
2015-04-25 19:38:29 +08:00
|
|
|
if not hook.has_spec():
|
|
|
|
for plugin in hook._plugins:
|
2015-04-25 17:29:11 +08:00
|
|
|
method = getattr(plugin, hook.name)
|
|
|
|
if not getattr(method, "optionalhook", False):
|
|
|
|
raise PluginValidationError(
|
|
|
|
"unknown hook %r in plugin %r" %(name, plugin))
|
2015-04-22 22:42:41 +08:00
|
|
|
|
|
|
|
def _get_canonical_name(self, plugin):
|
|
|
|
return getattr(plugin, "__name__", None) or str(id(plugin))
|
|
|
|
|
|
|
|
|
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
class MultiCall:
|
2010-10-13 17:12:27 +08:00
|
|
|
""" execute a call into multiple python functions/methods. """
|
2014-03-14 19:49:35 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
def __init__(self, methods, kwargs, firstresult=False):
|
2015-04-25 17:29:11 +08:00
|
|
|
self.methods = methods
|
2010-10-13 17:12:27 +08:00
|
|
|
self.kwargs = kwargs
|
2014-10-01 20:55:54 +08:00
|
|
|
self.kwargs["__multicall__"] = self
|
2010-10-12 18:54:32 +08:00
|
|
|
self.firstresult = firstresult
|
|
|
|
|
|
|
|
def execute(self):
|
2014-10-08 17:27:14 +08:00
|
|
|
all_kwargs = self.kwargs
|
2015-04-26 00:15:39 +08:00
|
|
|
self.results = results = []
|
2015-04-26 00:15:42 +08:00
|
|
|
firstresult = self.firstresult
|
|
|
|
|
2014-10-08 17:27:14 +08:00
|
|
|
while self.methods:
|
|
|
|
method = self.methods.pop()
|
|
|
|
args = [all_kwargs[argname] for argname in varnames(method)]
|
|
|
|
if hasattr(method, "hookwrapper"):
|
|
|
|
return wrapped_call(method(*args), self.execute)
|
|
|
|
res = method(*args)
|
|
|
|
if res is not None:
|
2015-04-26 00:15:42 +08:00
|
|
|
if firstresult:
|
2014-10-08 17:27:14 +08:00
|
|
|
return res
|
2015-04-26 00:15:39 +08:00
|
|
|
results.append(res)
|
2015-04-26 00:15:42 +08:00
|
|
|
|
|
|
|
if not firstresult:
|
2015-04-26 00:15:39 +08:00
|
|
|
return results
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
status = "%d meths" % (len(self.methods),)
|
|
|
|
if hasattr(self, "results"):
|
|
|
|
status = ("%d results, " % len(self.results)) + status
|
|
|
|
return "<MultiCall %s, kwargs=%r>" %(status, self.kwargs)
|
|
|
|
|
2014-03-14 19:49:35 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
|
2014-10-02 21:25:42 +08:00
|
|
|
def varnames(func, startindex=None):
|
2013-11-19 22:33:52 +08:00
|
|
|
""" return argument name tuple for a function, method, class or callable.
|
|
|
|
|
|
|
|
In case of a class, its "__init__" method is considered.
|
|
|
|
For methods the "self" parameter is not included unless you are passing
|
|
|
|
an unbound method with Python3 (which has no supports for unbound methods)
|
|
|
|
"""
|
|
|
|
cache = getattr(func, "__dict__", {})
|
2011-03-08 01:28:45 +08:00
|
|
|
try:
|
2013-11-19 22:33:52 +08:00
|
|
|
return cache["_varnames"]
|
|
|
|
except KeyError:
|
2011-03-08 01:28:45 +08:00
|
|
|
pass
|
2015-04-25 19:38:30 +08:00
|
|
|
if isclass(func):
|
2013-11-19 22:33:52 +08:00
|
|
|
try:
|
|
|
|
func = func.__init__
|
|
|
|
except AttributeError:
|
|
|
|
return ()
|
2014-10-02 21:25:42 +08:00
|
|
|
startindex = 1
|
2013-11-19 22:33:52 +08:00
|
|
|
else:
|
2015-04-25 19:38:30 +08:00
|
|
|
if not isfunction(func) and not ismethod(func):
|
2013-11-19 22:33:52 +08:00
|
|
|
func = getattr(func, '__call__', func)
|
2014-10-02 21:25:42 +08:00
|
|
|
if startindex is None:
|
2015-04-25 19:38:30 +08:00
|
|
|
startindex = int(ismethod(func))
|
2014-10-02 21:25:42 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
rawcode = py.code.getrawcode(func)
|
|
|
|
try:
|
2014-10-02 21:25:42 +08:00
|
|
|
x = rawcode.co_varnames[startindex:rawcode.co_argcount]
|
2010-10-12 18:54:32 +08:00
|
|
|
except AttributeError:
|
2011-03-08 01:28:45 +08:00
|
|
|
x = ()
|
2014-10-01 20:55:54 +08:00
|
|
|
else:
|
|
|
|
defaults = func.__defaults__
|
|
|
|
if defaults:
|
|
|
|
x = x[:-len(defaults)]
|
2013-11-19 22:33:52 +08:00
|
|
|
try:
|
|
|
|
cache["_varnames"] = x
|
|
|
|
except TypeError:
|
|
|
|
pass
|
2011-03-08 01:28:45 +08:00
|
|
|
return x
|
2010-10-12 18:54:32 +08:00
|
|
|
|
2014-10-01 20:55:54 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
class HookRelay:
|
2015-04-26 00:15:39 +08:00
|
|
|
def __init__(self, trace):
|
|
|
|
self._trace = trace
|
2014-10-01 18:19:11 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
|
2015-04-25 17:29:11 +08:00
|
|
|
class HookCaller(object):
|
2015-04-26 00:15:39 +08:00
|
|
|
def __init__(self, name, hook_execute, specmodule_or_class=None):
|
2010-10-12 18:54:32 +08:00
|
|
|
self.name = name
|
2015-04-25 19:38:29 +08:00
|
|
|
self._plugins = []
|
|
|
|
self._wrappers = []
|
|
|
|
self._nonwrappers = []
|
2015-04-26 00:15:39 +08:00
|
|
|
self._hookexec = hook_execute
|
2015-04-25 19:38:29 +08:00
|
|
|
if specmodule_or_class is not None:
|
2015-04-26 00:14:39 +08:00
|
|
|
self.set_specification(specmodule_or_class)
|
2015-04-25 19:38:29 +08:00
|
|
|
|
|
|
|
def has_spec(self):
|
|
|
|
return hasattr(self, "_specmodule_or_class")
|
2015-04-25 17:29:11 +08:00
|
|
|
|
2015-04-26 00:14:39 +08:00
|
|
|
def set_specification(self, specmodule_or_class):
|
2015-04-25 19:38:29 +08:00
|
|
|
assert not self.has_spec()
|
|
|
|
self._specmodule_or_class = specmodule_or_class
|
|
|
|
specfunc = getattr(specmodule_or_class, self.name)
|
2015-04-25 19:38:30 +08:00
|
|
|
argnames = varnames(specfunc, startindex=isclass(specmodule_or_class))
|
|
|
|
assert "self" not in argnames # sanity check
|
|
|
|
self.argnames = ["__multicall__"] + list(argnames)
|
2015-04-25 19:38:29 +08:00
|
|
|
self.firstresult = getattr(specfunc, 'firstresult', False)
|
|
|
|
if hasattr(specfunc, "historic"):
|
|
|
|
self._call_history = []
|
2015-04-25 17:29:11 +08:00
|
|
|
|
2015-04-25 19:38:29 +08:00
|
|
|
def is_historic(self):
|
|
|
|
return hasattr(self, "_call_history")
|
2014-10-01 18:20:11 +08:00
|
|
|
|
2015-04-26 00:14:39 +08:00
|
|
|
def _remove_plugin(self, plugin):
|
2015-04-25 19:38:29 +08:00
|
|
|
self._plugins.remove(plugin)
|
2015-04-25 17:29:11 +08:00
|
|
|
meth = getattr(plugin, self.name)
|
|
|
|
try:
|
2015-04-25 19:38:29 +08:00
|
|
|
self._nonwrappers.remove(meth)
|
2015-04-25 17:29:11 +08:00
|
|
|
except ValueError:
|
2015-04-25 19:38:29 +08:00
|
|
|
self._wrappers.remove(meth)
|
|
|
|
|
2015-04-26 00:14:39 +08:00
|
|
|
def _add_plugin(self, plugin):
|
2015-04-25 19:38:29 +08:00
|
|
|
self._plugins.append(plugin)
|
2015-04-26 00:14:39 +08:00
|
|
|
self._add_method(getattr(plugin, self.name))
|
2015-04-25 17:29:11 +08:00
|
|
|
|
2015-04-26 00:14:39 +08:00
|
|
|
def _add_method(self, meth):
|
2015-04-25 17:29:11 +08:00
|
|
|
if hasattr(meth, 'hookwrapper'):
|
2015-04-25 19:38:29 +08:00
|
|
|
self._wrappers.append(meth)
|
2015-04-25 17:29:11 +08:00
|
|
|
elif hasattr(meth, 'trylast'):
|
2015-04-25 19:38:29 +08:00
|
|
|
self._nonwrappers.insert(0, meth)
|
2015-04-25 17:29:11 +08:00
|
|
|
elif hasattr(meth, 'tryfirst'):
|
2015-04-25 19:38:29 +08:00
|
|
|
self._nonwrappers.append(meth)
|
2015-04-25 17:29:11 +08:00
|
|
|
else:
|
2015-04-26 00:15:42 +08:00
|
|
|
# find the last nonwrapper which is not tryfirst marked
|
2015-04-25 19:38:29 +08:00
|
|
|
nonwrappers = self._nonwrappers
|
2015-04-26 00:15:42 +08:00
|
|
|
i = len(nonwrappers) - 1
|
|
|
|
while i >= 0 and hasattr(nonwrappers[i], "tryfirst"):
|
|
|
|
i -= 1
|
|
|
|
# and insert right in front of the tryfirst ones
|
|
|
|
nonwrappers.insert(i+1, meth)
|
2015-04-25 17:29:11 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "<HookCaller %r>" %(self.name,)
|
2009-03-06 05:10:18 +08:00
|
|
|
|
2010-10-12 18:54:32 +08:00
|
|
|
def __call__(self, **kwargs):
|
2015-04-25 19:38:29 +08:00
|
|
|
assert not self.is_historic()
|
2015-04-26 00:15:39 +08:00
|
|
|
return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
|
|
|
|
|
|
|
|
def call_historic(self, proc=None, kwargs=None):
|
|
|
|
self._call_history.append((kwargs or {}, proc))
|
|
|
|
# historizing hooks don't return results
|
|
|
|
self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
|
2010-10-07 17:51:58 +08:00
|
|
|
|
2015-04-25 19:38:30 +08:00
|
|
|
def call_extra(self, methods, kwargs):
|
2015-04-26 00:14:39 +08:00
|
|
|
""" Call the hook with some additional temporarily participating
|
|
|
|
methods using the specified kwargs as call parameters. """
|
|
|
|
old = list(self._nonwrappers), list(self._wrappers)
|
2015-04-25 17:29:11 +08:00
|
|
|
for method in methods:
|
2015-04-26 00:14:39 +08:00
|
|
|
self._add_method(method)
|
|
|
|
try:
|
|
|
|
return self(**kwargs)
|
|
|
|
finally:
|
|
|
|
self._nonwrappers, self._wrappers = old
|
2014-10-01 18:20:11 +08:00
|
|
|
|
2015-04-26 00:15:42 +08:00
|
|
|
def _maybe_apply_history(self, method):
|
2015-04-25 19:38:29 +08:00
|
|
|
if self.is_historic():
|
2015-04-25 17:29:11 +08:00
|
|
|
for kwargs, proc in self._call_history:
|
2015-04-26 00:15:39 +08:00
|
|
|
res = self._hookexec(self, [method], kwargs)
|
2015-04-25 19:38:30 +08:00
|
|
|
if res and proc is not None:
|
|
|
|
proc(res[0])
|
|
|
|
|
2014-10-01 18:20:11 +08:00
|
|
|
|
|
|
|
class PluginValidationError(Exception):
|
|
|
|
""" plugin failed validation. """
|
|
|
|
|
|
|
|
|
|
|
|
def formatdef(func):
|
|
|
|
return "%s%s" % (
|
|
|
|
func.__name__,
|
2015-04-25 19:38:30 +08:00
|
|
|
formatargspec(*getargspec(func))
|
2014-10-01 18:20:11 +08:00
|
|
|
)
|