pluggy.py 29 KB

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