simplug 0.5.1__tar.gz → 0.5.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "simplug"
|
|
3
|
-
version = "0.5.
|
|
3
|
+
version = "0.5.3"
|
|
4
4
|
description = "A simple plugin system for python with async hooks supported"
|
|
5
5
|
authors = ["pwwang <pwwang@pwwang.com>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -15,7 +15,7 @@ diot = "^0.3"
|
|
|
15
15
|
[tool.poetry.build]
|
|
16
16
|
generate-setup-file = true
|
|
17
17
|
|
|
18
|
-
[tool.poetry.dev
|
|
18
|
+
[tool.poetry.group.dev.dependencies]
|
|
19
19
|
pytest = "^8"
|
|
20
20
|
pytest-cov = "^5"
|
|
21
21
|
setuptools = "^68"
|
|
@@ -38,3 +38,8 @@ filterwarnings = [
|
|
|
38
38
|
[build-system]
|
|
39
39
|
requires = ["poetry>=1.0"]
|
|
40
40
|
build-backend = "poetry.masonry.api"
|
|
41
|
+
|
|
42
|
+
[tool.black]
|
|
43
|
+
line-length = 88
|
|
44
|
+
target-version = ['py39', 'py310', 'py311', 'py312']
|
|
45
|
+
include = '\.pyi?$'
|
|
@@ -8,7 +8,7 @@ install_requires = \
|
|
|
8
8
|
|
|
9
9
|
setup_kwargs = {
|
|
10
10
|
'name': 'simplug',
|
|
11
|
-
'version': '0.5.
|
|
11
|
+
'version': '0.5.3',
|
|
12
12
|
'description': 'A simple plugin system for python with async hooks supported',
|
|
13
13
|
'long_description': '# simplug\n\nA simple plugin system for python with async hooks supported\n\n## Installation\n\n```shell\npip install -U simplug\n```\n\n## Examples\n\n### A toy example\n\n```python\nfrom simplug import Simplug\n\nsimplug = Simplug(\'project\')\n\nclass MySpec:\n """A hook specification namespace."""\n\n @simplug.spec\n def myhook(self, arg1, arg2):\n """My special little hook that you can customize."""\n\nclass Plugin_1:\n """A hook implementation namespace."""\n\n @simplug.impl\n def myhook(self, arg1, arg2):\n print("inside Plugin_1.myhook()")\n return arg1 + arg2\n\nclass Plugin_2:\n """A 2nd hook implementation namespace."""\n\n @simplug.impl\n def myhook(self, arg1, arg2):\n print("inside Plugin_2.myhook()")\n return arg1 - arg2\n\nsimplug.register(Plugin_1, Plugin_2)\nresults = simplug.hooks.myhook(arg1=1, arg2=2)\nprint(results)\n```\n\n```shell\ninside Plugin_1.myhook()\ninside Plugin_2.myhook()\n[3, -1]\n```\n\nNote that the hooks are executed in the order the plugins are registered. This is different from `pluggy`.\n\n### A complete example\n\nSee `examples/complete/`.\n\nRunning `python -m examples.complete` gets us:\n\n```shell\nYour food. Enjoy some egg, egg, egg, salt, pepper, egg, egg\nSome condiments? We have pickled walnuts, steak sauce, mushy peas, mint sauce\n```\n\nAfter install the plugin:\n\n```shell\n> pip install --editable examples.complete.plugin\n> python -m examples.complete # run again\n```\n\n```shell\nYour food. Enjoy some egg, egg, egg, salt, pepper, egg, egg, lovely spam, wonderous spam\nSome condiments? We have pickled walnuts, mushy peas, mint sauce, spam sauce\nNow this is what I call a condiments tray!\n```\n\n## Usage\n\n### Definition of hooks\n\nHooks are specified and implemented by decorating the functions with `simplug.spec` and `simplug.impl` respectively.\n\n`simplug` is initialized by:\n\n```python\nsimplug = Simplug(\'project\')\n```\n\nThe `\'project\'` is a unique name to mark the project, which makes sure `Simplug(\'project\')` get the same instance each time.\n\nNote that if `simplug` is initialized without `project`, then a name is generated automatically as such `project-0`, `project-1`, etc.\n\nHook specification is marked by `simplug.spec`:\n\n```python\nsimplug = Simplug(\'project\')\n\n@simplug.spec\ndef setup(args):\n ...\n```\n\n`simplug.spec` can take some arguments:\n\n- `required`: Whether this hook is required to be implemented in plugins\n- `result`: An enumerator to specify the way to collec the results.\n - `SimplugResult.ALL`: Collect all results from all plugins\n - `SimplugResult.ALL_AVAILS`: Get all the results from the hook, as a list, not including `None`s\n - `SimplugResult.ALL_FIRST`: Executing all implementations and get the first result\n - `SimplugResult.ALL_LAST`: Executing all implementations and get the last result\n - `SimplugResult.TRY_ALL_FIRST`: Executing all implementations and get the first result, if no result is returned, return `None`\n - `SimplugResult.TRY_ALL_LAST`: Executing all implementations and get the last result, if no result is returned, return `None`\n - `SimplugResult.ALL_FIRST_AVAIL`: Executing all implementations and get the first non-`None` result\n - `SimplugResult.ALL_LAST_AVAIL`: Executing all implementations and get the last non-`None` result\n - `SimplugResult.TRY_ALL_FIRST_AVAIL`: Executing all implementations and get the first non-`None` result, if no result is returned, return `None`\n - `SimplugResult.TRY_ALL_LAST_AVAIL`: Executing all implementations and get the last non-`None` result, if no result is returned, return `None`\n - `SimplugResult.FIRST`: Get the first result, don\'t execute other implementations\n - `SimplugResult.LAST`: Get the last result, don\'t execute other implementations\n - `SimplugResult.TRY_FIRST`: Get the first result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.TRY_LAST`: Get the last result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.FIRST_AVAIL`: Get the first non-`None` result, don\'t execute other implementations\n - `SimplugResult.LAST_AVAIL`: Get the last non-`None` result, don\'t execute other implementations\n - `SimplugResult.TRY_FIRST_AVAIL`: Get the first non-`None` result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.TRY_LAST_AVAIL`: Get the last non-`None` result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.SINGLE`: Get the result from a single implementation\n - `SimplugResult.TRY_SINGLE`: Get the result from a single implementation, if no result is returned, return `None`\n - A callable to collect the result, take `calls` as the argument, a 3-element tuple with first element as the implementation, second element as the positional arguments, and third element as the keyword arguments.\n\nHook implementation is marked by `simplug.impl`, which takes no additional arguments.\n\nThe name of the function has to match the name of the function by `simplug.spec`. And the signatures of the specification function and the implementation function have to be the same in terms of names. This means you can specify default values in the specification function, but you don\'t have to write the default values in the implementation function.\n\nNote that default values in implementation functions will be ignored.\n\nAlso note if a hook specification is under a namespace, it can take `self` as argument. However, this argument will be ignored while the hook is being called (`self` will be `None`, and you still have to specify it in the function definition).\n\n### Loading plugins from setuptools entrypoint\n\nYou have to call `simplug.load_entrypoints(group)` after the hook specifications are defined to load the plugins registered by setuptools entrypoint. If `group` is not given, the project name will be used.\n\n### The plugin registry\n\nThe plugins are registered by `simplug.register(*plugins)`. Each plugin of `plugins` can be either a python object or a str denoting a module that can be imported by `importlib.import_module`.\n\nThe python object must have an attribute `name`, `__name__` or `__class.__name__` for `simplug` to determine the name of the plugin. If the plugin name is determined from `__name__` or `__class__.__name__`, it will be lowercased.\n\nIf a plugin is loaded from setuptools entrypoint, then the entrypoint name will be used (no matter what name is defined inside the plugin)\n\nYou can enable or disable a plugin temporarily after registration by:\n\n```python\nsimplug.disable(\'plugin_name\')\nsimplug.enable(\'plugin_name\')\n```\n\nYou can use following methods to inspect the plugin registry:\n\n- `simplug.get_plugin`: Get the plugin by name\n- `simplug.get_all_plugins`: Get a dictionary of name-plugin mappings of all plugins\n- `simplug.get_all_plugin_names`: Get the names of all plugins, in the order it will be executed.\n- `simplug.get_enabled_plugins`: Get a dictionary of name-plugin mappings of all enabled plugins\n- `simplug.get_enabled_plugin_names`: Get the names of all enabled plugins, in the order it will be executed.\n\n### Calling hooks\n\nHooks are call by `simplug.hooks.<hook_name>(<arguments>)` and results are collected based on the `result` argument passed in `simplug.spec` when defining hooks.\n\n### Async hooks\n\nIt makes no big difference to define an async hook:\n\n```python\n@simplug.spec\nasync def async_hook(arg):\n ...\n\n# to supress warnings for sync implementation\n@simplug.spec(warn_sync_impl_on_async=False)\nasync def async_hook(arg):\n ...\n```\n\nOne can implement this hook in either an async or a sync way. However, when implementing it in a sync way, a warning will be raised. To suppress the warning, one can pass a `False` value of argument `warn_sync_impl_on_async` to `simplug.spec`.\n\nTo call the async hooks (`simplug.hooks.async_hook(arg)`), you will just need to call it like any other async functions (using `asyncio.run`, for example)\n\n## API\n\nhttps://pwwang.github.io/simplug/\n',
|
|
14
14
|
'author': 'pwwang',
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"""A simple entrypoint-free plugin system for python"""
|
|
2
|
+
|
|
2
3
|
from __future__ import annotations
|
|
3
4
|
|
|
4
5
|
import sys
|
|
@@ -12,7 +13,7 @@ from typing import Any, Callable, Dict, Iterable, List, Tuple
|
|
|
12
13
|
|
|
13
14
|
from diot import OrderedDiot
|
|
14
15
|
|
|
15
|
-
__version__ = "0.5.
|
|
16
|
+
__version__ = "0.5.3"
|
|
16
17
|
|
|
17
18
|
SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"])
|
|
18
19
|
SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation.
|
|
@@ -77,6 +78,10 @@ class HookSpecExists(SimplugException):
|
|
|
77
78
|
"""When a hook has already been defined"""
|
|
78
79
|
|
|
79
80
|
|
|
81
|
+
class AsyncImplOnSyncSpecError(SimplugException):
|
|
82
|
+
"""When an async implementation on a sync hook"""
|
|
83
|
+
|
|
84
|
+
|
|
80
85
|
class SyncImplOnAsyncSpecWarning(Warning):
|
|
81
86
|
"""When a sync implementation on an async hook"""
|
|
82
87
|
|
|
@@ -136,23 +141,34 @@ def makecall(call: SimplugImplCall, async_hook: bool = False):
|
|
|
136
141
|
Returns:
|
|
137
142
|
The result of the call
|
|
138
143
|
"""
|
|
144
|
+
spec_prefix = "[async]" if async_hook else ""
|
|
145
|
+
err_msg = (
|
|
146
|
+
"Error while calling hook implementation, "
|
|
147
|
+
f"plugin={call.plugin}; spec={spec_prefix}{call.impl.__name__}"
|
|
148
|
+
)
|
|
149
|
+
if inspect.iscoroutinefunction(call.impl):
|
|
150
|
+
|
|
151
|
+
async def coro():
|
|
152
|
+
try:
|
|
153
|
+
return await call.impl(*call.args, **call.kwargs)
|
|
154
|
+
except Exception as exc:
|
|
155
|
+
raise ResultError(err_msg) from exc
|
|
156
|
+
|
|
157
|
+
return coro()
|
|
158
|
+
|
|
139
159
|
try:
|
|
140
160
|
out = call.impl(*call.args, **call.kwargs)
|
|
141
161
|
except Exception as exc:
|
|
142
|
-
raise ResultError(
|
|
143
|
-
f"Error while calling {call.plugin}.{call.impl.__name__}(...)"
|
|
144
|
-
) from exc
|
|
162
|
+
raise ResultError(err_msg) from exc
|
|
145
163
|
|
|
146
|
-
if
|
|
147
|
-
return out
|
|
164
|
+
if async_hook:
|
|
148
165
|
|
|
149
|
-
|
|
150
|
-
|
|
166
|
+
async def coro():
|
|
167
|
+
return out
|
|
151
168
|
|
|
152
|
-
|
|
153
|
-
return out
|
|
169
|
+
return coro()
|
|
154
170
|
|
|
155
|
-
return
|
|
171
|
+
return out
|
|
156
172
|
|
|
157
173
|
|
|
158
174
|
class SimplugWrapper:
|
|
@@ -188,9 +204,7 @@ class SimplugWrapper:
|
|
|
188
204
|
try:
|
|
189
205
|
self.plugin = import_module(plugin)
|
|
190
206
|
except ImportError as exc:
|
|
191
|
-
raise NoSuchPlugin(plugin).with_traceback(
|
|
192
|
-
exc.__traceback__
|
|
193
|
-
) from None
|
|
207
|
+
raise NoSuchPlugin(plugin).with_traceback(exc.__traceback__) from None
|
|
194
208
|
|
|
195
209
|
elif isinstance(plugin, tuple):
|
|
196
210
|
# plugin load from entrypoint
|
|
@@ -202,9 +216,7 @@ class SimplugWrapper:
|
|
|
202
216
|
|
|
203
217
|
priority = getattr(self.plugin, "priority", None)
|
|
204
218
|
self.priority: Tuple[int, int] = (
|
|
205
|
-
(batch_index, index)
|
|
206
|
-
if priority is None
|
|
207
|
-
else (priority, batch_index)
|
|
219
|
+
(batch_index, index) if priority is None else (priority, batch_index)
|
|
208
220
|
)
|
|
209
221
|
|
|
210
222
|
self.enabled = True # type: bool
|
|
@@ -327,6 +339,7 @@ class SimplugHook:
|
|
|
327
339
|
self.name = spec.__name__
|
|
328
340
|
self.required = required
|
|
329
341
|
self.result = result
|
|
342
|
+
self.debug = False
|
|
330
343
|
self.warn_sync_impl_on_async = warn_sync_impl_on_async
|
|
331
344
|
|
|
332
345
|
def _get_results(
|
|
@@ -339,6 +352,11 @@ class SimplugHook:
|
|
|
339
352
|
result = self.result if result is None else result
|
|
340
353
|
|
|
341
354
|
if callable(result):
|
|
355
|
+
if self.debug:
|
|
356
|
+
print(
|
|
357
|
+
"[simplug] - Gathering results using "
|
|
358
|
+
f"custom function {result.__name__}"
|
|
359
|
+
)
|
|
342
360
|
return result(calls)
|
|
343
361
|
|
|
344
362
|
if isinstance(result, SimplugResult):
|
|
@@ -355,44 +373,64 @@ class SimplugHook:
|
|
|
355
373
|
if result & 0b010_0000:
|
|
356
374
|
out = [makecall(call) for call in calls]
|
|
357
375
|
if result == SimplugResult.ALL.value:
|
|
376
|
+
if self.debug:
|
|
377
|
+
print("[simplug] - Returning all results")
|
|
358
378
|
return out
|
|
359
379
|
if result == SimplugResult.ALL_AVAILS.value:
|
|
380
|
+
if self.debug:
|
|
381
|
+
print("[simplug] - Returning all available (non-None) results")
|
|
360
382
|
return [x for x in out if x is not None]
|
|
361
383
|
if result == SimplugResult.ALL_FIRST.value:
|
|
362
384
|
if not out:
|
|
363
385
|
raise ResultUnavailableError
|
|
386
|
+
if self.debug:
|
|
387
|
+
print("[simplug] - Returning first result")
|
|
364
388
|
return out[0]
|
|
365
389
|
if result == SimplugResult.ALL_LAST.value:
|
|
366
390
|
if not out:
|
|
367
391
|
raise ResultUnavailableError
|
|
392
|
+
if self.debug:
|
|
393
|
+
print("[simplug] - Returning last result")
|
|
368
394
|
return out[-1]
|
|
369
395
|
if result == SimplugResult.ALL_FIRST_AVAIL.value:
|
|
370
396
|
if not out or all(x is None for x in out):
|
|
371
397
|
raise ResultUnavailableError
|
|
398
|
+
if self.debug:
|
|
399
|
+
print("[simplug] - Returning first available (non-None) result")
|
|
372
400
|
return next(x for x in out if x is not None)
|
|
373
401
|
if result == SimplugResult.ALL_LAST_AVAIL.value:
|
|
374
402
|
if not out or all(x is None for x in out):
|
|
375
403
|
raise ResultUnavailableError
|
|
404
|
+
if self.debug:
|
|
405
|
+
print("[simplug] - Returning last available (non-None) result")
|
|
376
406
|
return next(x for x in reversed(out) if x is not None)
|
|
377
407
|
|
|
378
408
|
if result == SimplugResult.FIRST.value:
|
|
379
409
|
if not calls:
|
|
380
410
|
raise ResultUnavailableError
|
|
411
|
+
if self.debug:
|
|
412
|
+
print("[simplug] - Returning first result")
|
|
381
413
|
return makecall(calls[0])
|
|
382
414
|
if result == SimplugResult.LAST.value:
|
|
383
415
|
if not calls:
|
|
384
416
|
raise ResultUnavailableError
|
|
417
|
+
if self.debug:
|
|
418
|
+
print("[simplug] - Returning last result")
|
|
385
419
|
return makecall(calls[-1])
|
|
386
420
|
if result == SimplugResult.FIRST_AVAIL.value:
|
|
387
421
|
for call in calls:
|
|
388
422
|
ret = makecall(call)
|
|
389
423
|
if ret is not None:
|
|
424
|
+
if self.debug:
|
|
425
|
+
print("[simplug] - Returning first available (non-None) result")
|
|
390
426
|
return ret
|
|
391
427
|
raise ResultUnavailableError
|
|
392
428
|
if result == SimplugResult.LAST_AVAIL.value:
|
|
393
429
|
for call in reversed(calls):
|
|
394
430
|
ret = makecall(call)
|
|
395
431
|
if ret is not None:
|
|
432
|
+
if self.debug:
|
|
433
|
+
print("[simplug] - Returning last available (non-None) result")
|
|
396
434
|
return ret
|
|
397
435
|
raise ResultUnavailableError
|
|
398
436
|
if result == SimplugResult.SINGLE.value:
|
|
@@ -400,6 +438,10 @@ class SimplugHook:
|
|
|
400
438
|
raise ResultUnavailableError
|
|
401
439
|
for call in calls:
|
|
402
440
|
if call.plugin == plugin:
|
|
441
|
+
if self.debug:
|
|
442
|
+
print(
|
|
443
|
+
f"[simplug] - Returning single result from plugin {plugin}"
|
|
444
|
+
)
|
|
403
445
|
return makecall(call)
|
|
404
446
|
if plugin is not None:
|
|
405
447
|
raise ResultUnavailableError
|
|
@@ -409,6 +451,11 @@ class SimplugHook:
|
|
|
409
451
|
"but a single result is expected. Using the last one.",
|
|
410
452
|
MultipleImplsForSingleResultHookWarning,
|
|
411
453
|
)
|
|
454
|
+
if self.debug:
|
|
455
|
+
print(
|
|
456
|
+
f"[simplug] - Returning single result from the last plugin "
|
|
457
|
+
f"{calls[-1].plugin}"
|
|
458
|
+
)
|
|
412
459
|
return makecall(calls[-1])
|
|
413
460
|
|
|
414
461
|
def __call__(self, *args, **kwargs):
|
|
@@ -438,6 +485,12 @@ class SimplugHook:
|
|
|
438
485
|
"Cannot use __plugin with non-SimplugResult.(TRY_)SINGLE hooks"
|
|
439
486
|
)
|
|
440
487
|
|
|
488
|
+
if self.debug:
|
|
489
|
+
print(
|
|
490
|
+
f"[simplug] Calling hook {self.name} with args={args}, kwargs={kwargs}, "
|
|
491
|
+
f"result={self.result}"
|
|
492
|
+
)
|
|
493
|
+
|
|
441
494
|
_plugin = kwargs.pop("__plugin", None)
|
|
442
495
|
calls = []
|
|
443
496
|
for plugin in self.simplug_hooks._registry.values():
|
|
@@ -447,10 +500,11 @@ class SimplugHook:
|
|
|
447
500
|
|
|
448
501
|
if hook is not None:
|
|
449
502
|
plugin_args = (plugin.plugin, *args) if hook.has_self else args
|
|
503
|
+
if self.debug:
|
|
504
|
+
print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
|
|
505
|
+
|
|
450
506
|
calls.append(
|
|
451
|
-
SimplugImplCall(
|
|
452
|
-
plugin.name, hook.impl, plugin_args, kwargs
|
|
453
|
-
)
|
|
507
|
+
SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs)
|
|
454
508
|
)
|
|
455
509
|
|
|
456
510
|
return self._get_results(calls, plugin=_plugin)
|
|
@@ -469,6 +523,11 @@ class SimplugHookAsync(SimplugHook):
|
|
|
469
523
|
result = self.result if result is None else result
|
|
470
524
|
|
|
471
525
|
if callable(result):
|
|
526
|
+
if self.debug:
|
|
527
|
+
print(
|
|
528
|
+
"[simplug] - Gathering results using "
|
|
529
|
+
f"custom async function {result.__name__}"
|
|
530
|
+
)
|
|
472
531
|
return await result(calls)
|
|
473
532
|
|
|
474
533
|
if isinstance(result, SimplugResult):
|
|
@@ -489,44 +548,66 @@ class SimplugHookAsync(SimplugHook):
|
|
|
489
548
|
if result & 0b010_0000:
|
|
490
549
|
out = [await makecall(call, True) for call in calls]
|
|
491
550
|
if result == SimplugResult.ALL.value:
|
|
551
|
+
if self.debug:
|
|
552
|
+
print("[simplug] - Returning all results")
|
|
492
553
|
return out
|
|
493
554
|
if result == SimplugResult.ALL_AVAILS.value:
|
|
555
|
+
if self.debug:
|
|
556
|
+
print("[simplug] - Returning all available (non-None) results")
|
|
494
557
|
return [x for x in out if x is not None]
|
|
495
558
|
if result == SimplugResult.ALL_FIRST.value:
|
|
496
559
|
if not out:
|
|
497
560
|
raise ResultUnavailableError
|
|
561
|
+
if self.debug:
|
|
562
|
+
print("[simplug] - Returning first result")
|
|
498
563
|
return out[0]
|
|
499
564
|
if result == SimplugResult.ALL_LAST.value:
|
|
500
565
|
if not out:
|
|
501
566
|
raise ResultUnavailableError
|
|
567
|
+
if self.debug:
|
|
568
|
+
print("[simplug] - Returning last result")
|
|
502
569
|
return out[-1]
|
|
503
570
|
if result == SimplugResult.ALL_FIRST_AVAIL.value:
|
|
504
571
|
if not out or all(x is None for x in out):
|
|
505
572
|
raise ResultUnavailableError
|
|
573
|
+
if self.debug:
|
|
574
|
+
print("[simplug] - Returning first available (non-None) result")
|
|
506
575
|
return next(x for x in out if x is not None)
|
|
507
576
|
if result == SimplugResult.ALL_LAST_AVAIL.value:
|
|
508
577
|
if not out or all(x is None for x in out):
|
|
509
578
|
raise ResultUnavailableError
|
|
579
|
+
if self.debug:
|
|
580
|
+
print("[simplug] - Returning last available (non-None) result")
|
|
510
581
|
return next(x for x in reversed(out) if x is not None)
|
|
511
582
|
|
|
512
583
|
if result == SimplugResult.FIRST.value:
|
|
513
584
|
if not calls:
|
|
514
585
|
raise ResultUnavailableError
|
|
586
|
+
if self.debug:
|
|
587
|
+
print("[simplug] - Returning first result")
|
|
515
588
|
return await makecall(calls[0], True)
|
|
516
589
|
if result == SimplugResult.LAST.value:
|
|
517
590
|
if not calls:
|
|
518
591
|
raise ResultUnavailableError
|
|
592
|
+
if self.debug:
|
|
593
|
+
print("[simplug] - Returning last result")
|
|
519
594
|
return await makecall(calls[-1], True)
|
|
520
595
|
if result == SimplugResult.FIRST_AVAIL.value:
|
|
521
596
|
for call in calls:
|
|
522
597
|
ret = await makecall(call, True)
|
|
523
598
|
if ret is not None:
|
|
599
|
+
if self.debug:
|
|
600
|
+
print(
|
|
601
|
+
"[simplug] - Returning first available (non-None) result"
|
|
602
|
+
)
|
|
524
603
|
return ret
|
|
525
604
|
raise ResultUnavailableError
|
|
526
605
|
if result == SimplugResult.LAST_AVAIL.value:
|
|
527
606
|
for call in reversed(calls):
|
|
528
607
|
ret = await makecall(call, True)
|
|
529
608
|
if ret is not None:
|
|
609
|
+
if self.debug:
|
|
610
|
+
print("[simplug] - Returning last available (non-None) result")
|
|
530
611
|
return ret
|
|
531
612
|
raise ResultUnavailableError
|
|
532
613
|
if result == SimplugResult.SINGLE.value:
|
|
@@ -534,6 +615,10 @@ class SimplugHookAsync(SimplugHook):
|
|
|
534
615
|
raise ResultUnavailableError
|
|
535
616
|
for call in calls:
|
|
536
617
|
if call.plugin == plugin:
|
|
618
|
+
if self.debug:
|
|
619
|
+
print(
|
|
620
|
+
f"[simplug] - Returning single result from plugin {plugin}"
|
|
621
|
+
)
|
|
537
622
|
return await makecall(call, True)
|
|
538
623
|
if plugin is not None:
|
|
539
624
|
raise ResultUnavailableError
|
|
@@ -543,6 +628,11 @@ class SimplugHookAsync(SimplugHook):
|
|
|
543
628
|
"but no plugin was specified. Using the last one.",
|
|
544
629
|
MultipleImplsForSingleResultHookWarning,
|
|
545
630
|
)
|
|
631
|
+
if self.debug:
|
|
632
|
+
print(
|
|
633
|
+
f"[simplug] - Returning single result from the last plugin "
|
|
634
|
+
f"{calls[-1].plugin}"
|
|
635
|
+
)
|
|
546
636
|
return await makecall(calls[-1], True)
|
|
547
637
|
|
|
548
638
|
async def __call__(self, *args, **kwargs):
|
|
@@ -572,6 +662,12 @@ class SimplugHookAsync(SimplugHook):
|
|
|
572
662
|
"Cannot use __plugin with non-SimplugResult.(TRY_)SINGLE hooks"
|
|
573
663
|
)
|
|
574
664
|
|
|
665
|
+
if self.debug:
|
|
666
|
+
print(
|
|
667
|
+
f"[simplug] Calling async hook {self.name} with args={args}, "
|
|
668
|
+
f"kwargs={kwargs}, result={self.result}"
|
|
669
|
+
)
|
|
670
|
+
|
|
575
671
|
_plugin = kwargs.pop("__plugin", None)
|
|
576
672
|
calls = []
|
|
577
673
|
for plugin in self.simplug_hooks._registry.values():
|
|
@@ -582,9 +678,9 @@ class SimplugHookAsync(SimplugHook):
|
|
|
582
678
|
continue
|
|
583
679
|
|
|
584
680
|
plugin_args = (plugin.plugin, *args) if hook.has_self else args
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
)
|
|
681
|
+
if self.debug:
|
|
682
|
+
print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
|
|
683
|
+
calls.append(SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs))
|
|
588
684
|
|
|
589
685
|
return await self._get_results(calls, plugin=_plugin)
|
|
590
686
|
|
|
@@ -621,13 +717,9 @@ class SimplugHooks:
|
|
|
621
717
|
HookSignatureDifferentFromSpec: When the arguments of a hook
|
|
622
718
|
implementation is different from its specification
|
|
623
719
|
"""
|
|
624
|
-
if
|
|
625
|
-
plugin.name in self._registry
|
|
626
|
-
and plugin != self._registry[plugin.name]
|
|
627
|
-
):
|
|
720
|
+
if plugin.name in self._registry and plugin != self._registry[plugin.name]:
|
|
628
721
|
raise PluginRegistered(
|
|
629
|
-
f"Another plugin named {plugin.name} "
|
|
630
|
-
"has already been registered."
|
|
722
|
+
f"Another plugin named {plugin.name} " "has already been registered."
|
|
631
723
|
)
|
|
632
724
|
# check if required hooks implemented
|
|
633
725
|
# and signature
|
|
@@ -635,8 +727,7 @@ class SimplugHooks:
|
|
|
635
727
|
hook = plugin.hook(specname)
|
|
636
728
|
if spec.required and hook is None:
|
|
637
729
|
raise HookRequired(
|
|
638
|
-
f"{specname}, but not implemented "
|
|
639
|
-
f"in plugin {plugin.name}"
|
|
730
|
+
f"{specname}, but not implemented " f"in plugin {plugin.name}"
|
|
640
731
|
)
|
|
641
732
|
if hook is None: # pragma: no cover
|
|
642
733
|
continue
|
|
@@ -667,6 +758,16 @@ class SimplugHooks:
|
|
|
667
758
|
SyncImplOnAsyncSpecWarning,
|
|
668
759
|
)
|
|
669
760
|
|
|
761
|
+
if not isinstance(spec, SimplugHookAsync) and inspect.iscoroutinefunction(
|
|
762
|
+
hook.impl
|
|
763
|
+
):
|
|
764
|
+
raise AsyncImplOnSyncSpecError(
|
|
765
|
+
f"Sync hook {specname!r} should be implemented by "
|
|
766
|
+
f"a sync function, async implementation "
|
|
767
|
+
f"'{hook.impl.__name__}' "
|
|
768
|
+
f"found for plugin '{plugin.name}'"
|
|
769
|
+
)
|
|
770
|
+
|
|
670
771
|
self._registry[plugin.name] = plugin
|
|
671
772
|
|
|
672
773
|
def _sort_registry(self) -> None:
|
|
@@ -694,9 +795,7 @@ class SimplugHooks:
|
|
|
694
795
|
try:
|
|
695
796
|
return self._specs[name]
|
|
696
797
|
except KeyError as exc:
|
|
697
|
-
raise NoSuchHookSpec(name).with_traceback(
|
|
698
|
-
exc.__traceback__
|
|
699
|
-
) from None
|
|
798
|
+
raise NoSuchHookSpec(name).with_traceback(exc.__traceback__) from None
|
|
700
799
|
|
|
701
800
|
|
|
702
801
|
class SimplugContext:
|
|
@@ -708,8 +807,7 @@ class SimplugContext:
|
|
|
708
807
|
self.simplug = simplug
|
|
709
808
|
self.orig_registry = simplug.hooks._registry.copy()
|
|
710
809
|
self.orig_status = {
|
|
711
|
-
name: plugin.enabled
|
|
712
|
-
for name, plugin in self.orig_registry.items()
|
|
810
|
+
name: plugin.enabled for name, plugin in self.orig_registry.items()
|
|
713
811
|
}
|
|
714
812
|
|
|
715
813
|
def _check_plugins(self, plugins: Iterable[Any]) -> bool:
|
|
@@ -880,15 +978,10 @@ class Simplug:
|
|
|
880
978
|
if not raw:
|
|
881
979
|
return self.hooks._registry
|
|
882
980
|
return OrderedDiot(
|
|
883
|
-
[
|
|
884
|
-
(name, plugin.plugin)
|
|
885
|
-
for name, plugin in self.hooks._registry.items()
|
|
886
|
-
]
|
|
981
|
+
[(name, plugin.plugin) for name, plugin in self.hooks._registry.items()]
|
|
887
982
|
)
|
|
888
983
|
|
|
889
|
-
def get_enabled_plugins(
|
|
890
|
-
self, raw: bool = False
|
|
891
|
-
) -> Dict[str, SimplugWrapper]:
|
|
984
|
+
def get_enabled_plugins(self, raw: bool = False) -> Dict[str, SimplugWrapper]:
|
|
892
985
|
"""Get a mapping of all enabled plugins
|
|
893
986
|
|
|
894
987
|
Args:
|
|
@@ -922,15 +1015,10 @@ class Simplug:
|
|
|
922
1015
|
Returns:
|
|
923
1016
|
The names of all enabled plugins
|
|
924
1017
|
"""
|
|
925
|
-
return [
|
|
926
|
-
name
|
|
927
|
-
for name, plugin in self.hooks._registry.items()
|
|
928
|
-
if plugin.enabled
|
|
929
|
-
]
|
|
1018
|
+
return [name for name, plugin in self.hooks._registry.items() if plugin.enabled]
|
|
930
1019
|
|
|
931
1020
|
def plugins_context(
|
|
932
|
-
self,
|
|
933
|
-
plugins: Iterable[Any] | None
|
|
1021
|
+
self, plugins: Iterable[Any] | None
|
|
934
1022
|
) -> SimplugContext | nullcontext:
|
|
935
1023
|
"""A context manager with given plugins enabled or disabled
|
|
936
1024
|
|
|
File without changes
|
|
File without changes
|