simplug 0.5.3__tar.gz → 0.5.5__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.
|
@@ -8,7 +8,7 @@ install_requires = \
|
|
|
8
8
|
|
|
9
9
|
setup_kwargs = {
|
|
10
10
|
'name': 'simplug',
|
|
11
|
-
'version': '0.5.
|
|
11
|
+
'version': '0.5.5',
|
|
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',
|
|
@@ -9,20 +9,64 @@ from collections import namedtuple
|
|
|
9
9
|
from contextlib import nullcontext
|
|
10
10
|
from enum import Enum
|
|
11
11
|
from importlib import import_module, metadata
|
|
12
|
-
from typing import Any, Callable, Dict, Iterable, List, Tuple
|
|
12
|
+
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union, Optional
|
|
13
13
|
|
|
14
14
|
from diot import OrderedDiot
|
|
15
15
|
|
|
16
|
-
__version__ = "0.5.
|
|
16
|
+
__version__ = "0.5.5"
|
|
17
17
|
|
|
18
|
-
SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"])
|
|
19
|
-
SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation.
|
|
20
18
|
|
|
21
|
-
|
|
19
|
+
class SimplugImpl:
|
|
20
|
+
"""A namedtuple wrapper for hook implementation.
|
|
21
|
+
|
|
22
|
+
This is used to mark the method/function to be an implementation of a hook.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
impl: The hook implementation
|
|
26
|
+
has_self: Whether the first argument is `self`
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
__slots__ = ("impl", "has_self")
|
|
30
|
+
|
|
31
|
+
def __init__(self, impl: Callable, has_self: bool):
|
|
32
|
+
self.impl = impl
|
|
33
|
+
self.has_self = has_self
|
|
34
|
+
|
|
35
|
+
def __call__(self, *args: Any, **kwds: Any) -> Any:
|
|
36
|
+
return self.impl(*args, **kwds)
|
|
37
|
+
|
|
38
|
+
def __get__(self, obj: Any, objtype: type | None = None) -> "SimplugImpl":
|
|
39
|
+
"""Descriptor protocol to make this work as a bound method when accessed
|
|
40
|
+
on an instance."""
|
|
41
|
+
if obj is None:
|
|
42
|
+
# When accessed on the class, return the SimplugImpl itself
|
|
43
|
+
return self
|
|
44
|
+
if self.has_self:
|
|
45
|
+
# Return a bound method-like callable that auto-passes the instance
|
|
46
|
+
# but still appears as a SimplugImpl
|
|
47
|
+
class BoundSimplugImpl(SimplugImpl):
|
|
48
|
+
def __init__(self, original_impl: "SimplugImpl", instance: Any) -> None:
|
|
49
|
+
super().__init__(original_impl.impl, original_impl.has_self)
|
|
50
|
+
self.instance = instance
|
|
51
|
+
|
|
52
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
53
|
+
return self.impl(self.instance, *args, **kwargs)
|
|
54
|
+
|
|
55
|
+
def __get__(
|
|
56
|
+
self, obj: Any, objtype: type | None = None
|
|
57
|
+
) -> "SimplugImpl": # pragma: no cover
|
|
58
|
+
# Handle super() calls - when accessed on another instance
|
|
59
|
+
if obj is None:
|
|
60
|
+
return self
|
|
61
|
+
# For super() calls, we want to call with the new instance
|
|
62
|
+
# Create a new bound method for the new instance
|
|
63
|
+
return BoundSimplugImpl(SimplugImpl(self.impl, self.has_self), obj)
|
|
64
|
+
|
|
65
|
+
return BoundSimplugImpl(self, obj)
|
|
66
|
+
else:
|
|
67
|
+
# For non-self methods, still return the original SimplugImpl
|
|
68
|
+
return self
|
|
22
69
|
|
|
23
|
-
Args:
|
|
24
|
-
impl: The hook implementation
|
|
25
|
-
"""
|
|
26
70
|
|
|
27
71
|
SimplugImplCall = namedtuple(
|
|
28
72
|
"SimplugImplCall",
|
|
@@ -90,22 +134,27 @@ class MultipleImplsForSingleResultHookWarning(Warning):
|
|
|
90
134
|
"""When multiple implementations for a single-result hook"""
|
|
91
135
|
|
|
92
136
|
|
|
137
|
+
class ImplMightNeedInstanceWarning(Warning):
|
|
138
|
+
"""When an implementation might need an instance (self) but not defined as such"""
|
|
139
|
+
|
|
140
|
+
|
|
93
141
|
class SimplugResult(Enum):
|
|
94
142
|
"""Way to get the results from the hooks
|
|
95
143
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
144
|
+
Available result types:
|
|
145
|
+
- ALL: Execute all implementations for the hook
|
|
146
|
+
- ALL_AVAILS: Get non-`None` results
|
|
147
|
+
- FIRST: Get the first result, ordered by priority
|
|
148
|
+
Don't execute the other implementations
|
|
149
|
+
- LAST: Get the last result, ordered by priority
|
|
150
|
+
Don't execute the other implementations
|
|
151
|
+
- ALL_FIRST: Get the first result from each implementation and
|
|
152
|
+
execute the other implementations
|
|
153
|
+
- ALL_LAST: Get the last result from each implementation and
|
|
154
|
+
execute the other implementations
|
|
155
|
+
- TRY_*: Return `None` instead of raising `ResultUnavailableError` when
|
|
107
156
|
no result is available
|
|
108
|
-
SINGLE
|
|
157
|
+
- SINGLE: Get the result from a single implementation
|
|
109
158
|
"""
|
|
110
159
|
|
|
111
160
|
# 0b 1 1 1 1111
|
|
@@ -132,11 +181,12 @@ class SimplugResult(Enum):
|
|
|
132
181
|
TRY_SINGLE = 0b100_1010 # 146
|
|
133
182
|
|
|
134
183
|
|
|
135
|
-
def makecall(call: SimplugImplCall, async_hook: bool = False):
|
|
184
|
+
def makecall(call: SimplugImplCall, async_hook: bool = False) -> Any:
|
|
136
185
|
"""Make a call to an implementation and arguments
|
|
137
186
|
|
|
138
187
|
Args:
|
|
139
188
|
call: 3-element tuple of (implementation, args, kwargs)
|
|
189
|
+
async_hook: Whether this is being called from an async hook
|
|
140
190
|
|
|
141
191
|
Returns:
|
|
142
192
|
The result of the call
|
|
@@ -198,7 +248,12 @@ class SimplugWrapper:
|
|
|
198
248
|
imported as a module
|
|
199
249
|
"""
|
|
200
250
|
|
|
201
|
-
|
|
251
|
+
plugin: Any
|
|
252
|
+
_name: Optional[str]
|
|
253
|
+
priority: Tuple[int, int]
|
|
254
|
+
enabled: bool
|
|
255
|
+
|
|
256
|
+
def __init__(self, plugin: Any, batch_index: int, index: int) -> None:
|
|
202
257
|
self.plugin = self._name = None
|
|
203
258
|
if isinstance(plugin, str):
|
|
204
259
|
try:
|
|
@@ -222,7 +277,7 @@ class SimplugWrapper:
|
|
|
222
277
|
self.enabled = True # type: bool
|
|
223
278
|
|
|
224
279
|
@property
|
|
225
|
-
def version(self) -> str
|
|
280
|
+
def version(self) -> Optional[str]:
|
|
226
281
|
"""Try to get the version of the plugin.
|
|
227
282
|
|
|
228
283
|
If the attribute `version` is definied, use it. Otherwise, try to check
|
|
@@ -274,15 +329,24 @@ class SimplugWrapper:
|
|
|
274
329
|
|
|
275
330
|
raise NoPluginNameDefined(str(self.plugin)) # pragma: no cover
|
|
276
331
|
|
|
332
|
+
@property
|
|
333
|
+
def is_class(self) -> bool:
|
|
334
|
+
"""Whether the plugin is a class
|
|
335
|
+
|
|
336
|
+
Returns:
|
|
337
|
+
True if the plugin is a class, False otherwise
|
|
338
|
+
"""
|
|
339
|
+
return inspect.isclass(self.plugin)
|
|
340
|
+
|
|
277
341
|
def enable(self) -> None:
|
|
278
342
|
"""Enable this plugin"""
|
|
279
343
|
self.enabled = True
|
|
280
344
|
|
|
281
|
-
def disable(self):
|
|
345
|
+
def disable(self) -> None:
|
|
282
346
|
"""Disable this plugin"""
|
|
283
347
|
self.enabled = False
|
|
284
348
|
|
|
285
|
-
def hook(self, name: str) -> SimplugImpl
|
|
349
|
+
def hook(self, name: str) -> Optional[SimplugImpl]:
|
|
286
350
|
"""Get the hook implementation of this plugin by name
|
|
287
351
|
|
|
288
352
|
Args:
|
|
@@ -296,6 +360,7 @@ class SimplugWrapper:
|
|
|
296
360
|
ret = getattr(self.plugin, name, None)
|
|
297
361
|
if not isinstance(ret, SimplugImpl):
|
|
298
362
|
return None
|
|
363
|
+
|
|
299
364
|
return ret
|
|
300
365
|
|
|
301
366
|
def __eq__(self, other: Any) -> bool:
|
|
@@ -322,18 +387,27 @@ class SimplugHook:
|
|
|
322
387
|
spec: The specification of the hook
|
|
323
388
|
required: Whether this hook is required to be implemented
|
|
324
389
|
result: Way to collect the results from the hook
|
|
325
|
-
|
|
326
|
-
|
|
390
|
+
debug: Whether to print debug messages
|
|
391
|
+
warn_sync_impl_on_async: Whether to warn about sync implementations
|
|
392
|
+
on async hooks
|
|
327
393
|
"""
|
|
328
394
|
|
|
395
|
+
simplug_hooks: "SimplugHooks"
|
|
396
|
+
spec: Callable[..., Any]
|
|
397
|
+
name: str
|
|
398
|
+
required: bool
|
|
399
|
+
result: Union[SimplugResult, Callable]
|
|
400
|
+
debug: bool
|
|
401
|
+
warn_sync_impl_on_async: bool
|
|
402
|
+
|
|
329
403
|
def __init__(
|
|
330
404
|
self,
|
|
331
|
-
simplug_hooks: SimplugHooks,
|
|
332
|
-
spec: Callable,
|
|
405
|
+
simplug_hooks: "SimplugHooks",
|
|
406
|
+
spec: Callable[..., Any],
|
|
333
407
|
required: bool,
|
|
334
|
-
result: SimplugResult
|
|
408
|
+
result: Union[SimplugResult, Callable],
|
|
335
409
|
warn_sync_impl_on_async: bool = False,
|
|
336
|
-
):
|
|
410
|
+
) -> None:
|
|
337
411
|
self.simplug_hooks = simplug_hooks
|
|
338
412
|
self.spec = spec
|
|
339
413
|
self.name = spec.__name__
|
|
@@ -342,11 +416,49 @@ class SimplugHook:
|
|
|
342
416
|
self.debug = False
|
|
343
417
|
self.warn_sync_impl_on_async = warn_sync_impl_on_async
|
|
344
418
|
|
|
419
|
+
def _prepare_plugin_args(
|
|
420
|
+
self, plugin: SimplugWrapper, hook: SimplugImpl, args: Tuple[Any, ...]
|
|
421
|
+
) -> Tuple[Any, ...]:
|
|
422
|
+
"""Prepare arguments for calling a plugin hook implementation.
|
|
423
|
+
|
|
424
|
+
Args:
|
|
425
|
+
plugin: The plugin wrapper
|
|
426
|
+
hook: The hook implementation (SimplugImpl)
|
|
427
|
+
args: The original arguments to the hook
|
|
428
|
+
|
|
429
|
+
Returns:
|
|
430
|
+
Tuple of prepared arguments for the hook implementation
|
|
431
|
+
"""
|
|
432
|
+
if not hook.has_self:
|
|
433
|
+
return args
|
|
434
|
+
|
|
435
|
+
self_obj = plugin.plugin
|
|
436
|
+
if inspect.isclass(self_obj):
|
|
437
|
+
# Try to instantiate the class if it has no required parameters
|
|
438
|
+
try:
|
|
439
|
+
sig = inspect.signature(self_obj)
|
|
440
|
+
required_params = [
|
|
441
|
+
p for p in sig.parameters.values()
|
|
442
|
+
if (p.kind in (
|
|
443
|
+
inspect.Parameter.POSITIONAL_ONLY,
|
|
444
|
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
|
445
|
+
) and p.default is inspect.Parameter.empty
|
|
446
|
+
and p.name != "self")
|
|
447
|
+
]
|
|
448
|
+
if not required_params:
|
|
449
|
+
self_obj = self_obj()
|
|
450
|
+
except (TypeError, ValueError): # pragma: no cover
|
|
451
|
+
# More specific exception handling
|
|
452
|
+
# Fallback to passing the class if instantiation fails
|
|
453
|
+
pass
|
|
454
|
+
|
|
455
|
+
return (self_obj, *args)
|
|
456
|
+
|
|
345
457
|
def _get_results(
|
|
346
458
|
self,
|
|
347
459
|
calls: List[SimplugImplCall],
|
|
348
|
-
plugin: str,
|
|
349
|
-
result: SimplugResult
|
|
460
|
+
plugin: Optional[str],
|
|
461
|
+
result: Optional[Union[SimplugResult, Callable, int]] = None,
|
|
350
462
|
) -> Any:
|
|
351
463
|
"""Get the results according to self.result"""
|
|
352
464
|
result = self.result if result is None else result
|
|
@@ -458,7 +570,7 @@ class SimplugHook:
|
|
|
458
570
|
)
|
|
459
571
|
return makecall(calls[-1])
|
|
460
572
|
|
|
461
|
-
def __call__(self, *args, **kwargs):
|
|
573
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
462
574
|
"""Call the hook in your system
|
|
463
575
|
|
|
464
576
|
Args:
|
|
@@ -499,7 +611,7 @@ class SimplugHook:
|
|
|
499
611
|
hook = plugin.hook(self.name)
|
|
500
612
|
|
|
501
613
|
if hook is not None:
|
|
502
|
-
plugin_args = (plugin
|
|
614
|
+
plugin_args = self._prepare_plugin_args(plugin, hook, args)
|
|
503
615
|
if self.debug:
|
|
504
616
|
print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
|
|
505
617
|
|
|
@@ -516,8 +628,8 @@ class SimplugHookAsync(SimplugHook):
|
|
|
516
628
|
async def _get_results(
|
|
517
629
|
self,
|
|
518
630
|
calls: List[SimplugImplCall],
|
|
519
|
-
plugin: str,
|
|
520
|
-
result: SimplugResult
|
|
631
|
+
plugin: Optional[str],
|
|
632
|
+
result: Optional[Union[SimplugResult, Callable, int]] = None,
|
|
521
633
|
) -> Any:
|
|
522
634
|
"""Get the results according to self.result"""
|
|
523
635
|
result = self.result if result is None else result
|
|
@@ -635,7 +747,7 @@ class SimplugHookAsync(SimplugHook):
|
|
|
635
747
|
)
|
|
636
748
|
return await makecall(calls[-1], True)
|
|
637
749
|
|
|
638
|
-
async def __call__(self, *args, **kwargs):
|
|
750
|
+
async def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
639
751
|
"""Call the hook in your system asynchronously
|
|
640
752
|
|
|
641
753
|
Args:
|
|
@@ -677,7 +789,7 @@ class SimplugHookAsync(SimplugHook):
|
|
|
677
789
|
if hook is None: # pragma: no cover
|
|
678
790
|
continue
|
|
679
791
|
|
|
680
|
-
plugin_args = (plugin
|
|
792
|
+
plugin_args = self._prepare_plugin_args(plugin, hook, args)
|
|
681
793
|
if self.debug:
|
|
682
794
|
print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
|
|
683
795
|
calls.append(SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs))
|
|
@@ -700,10 +812,14 @@ class SimplugHooks:
|
|
|
700
812
|
_registry_sorted: Whether the plugin registry has been sorted already
|
|
701
813
|
"""
|
|
702
814
|
|
|
703
|
-
|
|
815
|
+
_registry: OrderedDiot
|
|
816
|
+
_specs: Dict[str, Union["SimplugHook", "SimplugHookAsync"]]
|
|
817
|
+
_registry_sorted: bool
|
|
818
|
+
|
|
819
|
+
def __init__(self) -> None:
|
|
704
820
|
|
|
705
821
|
self._registry = OrderedDiot()
|
|
706
|
-
self._specs = {}
|
|
822
|
+
self._specs: Dict[str, Union[SimplugHook, SimplugHookAsync]] = {}
|
|
707
823
|
self._registry_sorted = False
|
|
708
824
|
|
|
709
825
|
def _register(self, plugin: SimplugWrapper) -> None:
|
|
@@ -723,6 +839,7 @@ class SimplugHooks:
|
|
|
723
839
|
)
|
|
724
840
|
# check if required hooks implemented
|
|
725
841
|
# and signature
|
|
842
|
+
has_self_warned: bool = False
|
|
726
843
|
for specname, spec in self._specs.items():
|
|
727
844
|
hook = plugin.hook(specname)
|
|
728
845
|
if spec.required and hook is None:
|
|
@@ -768,6 +885,16 @@ class SimplugHooks:
|
|
|
768
885
|
f"found for plugin '{plugin.name}'"
|
|
769
886
|
)
|
|
770
887
|
|
|
888
|
+
if hook.has_self and plugin.is_class and not has_self_warned:
|
|
889
|
+
warnings.warn(
|
|
890
|
+
f"The implementation '{hook.impl.__name__}' of hook "
|
|
891
|
+
f"'{specname}' in plugin '{plugin.name}' might need an "
|
|
892
|
+
"instance (self), but the plugin is a class. "
|
|
893
|
+
"Please register your plugin as an instance of the class.",
|
|
894
|
+
ImplMightNeedInstanceWarning,
|
|
895
|
+
)
|
|
896
|
+
has_self_warned = True
|
|
897
|
+
|
|
771
898
|
self._registry[plugin.name] = plugin
|
|
772
899
|
|
|
773
900
|
def _sort_registry(self) -> None:
|
|
@@ -780,7 +907,7 @@ class SimplugHooks:
|
|
|
780
907
|
)
|
|
781
908
|
self._registry_sorted = True
|
|
782
909
|
|
|
783
|
-
def __getattr__(self, name: str) -> "SimplugHook":
|
|
910
|
+
def __getattr__(self, name: str) -> Union["SimplugHook", "SimplugHookAsync"]:
|
|
784
911
|
"""Get the hook by name
|
|
785
912
|
|
|
786
913
|
Args:
|
|
@@ -801,7 +928,13 @@ class SimplugHooks:
|
|
|
801
928
|
class SimplugContext:
|
|
802
929
|
"""The context manager for enabling or disabling a set of plugins"""
|
|
803
930
|
|
|
804
|
-
|
|
931
|
+
only: bool
|
|
932
|
+
plugins: Iterable[Any]
|
|
933
|
+
simplug: "Simplug"
|
|
934
|
+
orig_registry: OrderedDiot
|
|
935
|
+
orig_status: Dict[str, bool]
|
|
936
|
+
|
|
937
|
+
def __init__(self, simplug: "Simplug", plugins: Iterable[Any]) -> None:
|
|
805
938
|
self.only = self._check_plugins(plugins)
|
|
806
939
|
self.plugins = plugins
|
|
807
940
|
self.simplug = simplug
|
|
@@ -825,12 +958,12 @@ class SimplugContext:
|
|
|
825
958
|
)
|
|
826
959
|
return False
|
|
827
960
|
|
|
828
|
-
def _raise(self, exc: Exception):
|
|
961
|
+
def _raise(self, exc: Exception) -> None:
|
|
829
962
|
"""Raise the exception and restore the original status"""
|
|
830
963
|
self.__exit__(*sys.exc_info())
|
|
831
964
|
raise exc
|
|
832
965
|
|
|
833
|
-
def __enter__(self):
|
|
966
|
+
def __enter__(self) -> None:
|
|
834
967
|
if self.only:
|
|
835
968
|
for plugin in self.orig_registry.values():
|
|
836
969
|
plugin.disable()
|
|
@@ -856,7 +989,7 @@ class SimplugContext:
|
|
|
856
989
|
self._raise(NoSuchPlugin(plugin))
|
|
857
990
|
self.orig_registry[plugin].enable()
|
|
858
991
|
|
|
859
|
-
def __exit__(self, *exc):
|
|
992
|
+
def __exit__(self, *exc: Any) -> None:
|
|
860
993
|
self.simplug.hooks._registry = self.orig_registry
|
|
861
994
|
for name, status in self.orig_status.items():
|
|
862
995
|
self.simplug.hooks._registry[name].enabled = status
|
|
@@ -878,6 +1011,11 @@ class Simplug:
|
|
|
878
1011
|
|
|
879
1012
|
PROJECTS: Dict[str, "Simplug"] = {}
|
|
880
1013
|
|
|
1014
|
+
_batch_index: int
|
|
1015
|
+
hooks: SimplugHooks
|
|
1016
|
+
project: str
|
|
1017
|
+
_inited: bool
|
|
1018
|
+
|
|
881
1019
|
def __new__(cls, project: str) -> "Simplug":
|
|
882
1020
|
if project not in cls.PROJECTS:
|
|
883
1021
|
obj = super().__new__(cls)
|
|
@@ -886,7 +1024,7 @@ class Simplug:
|
|
|
886
1024
|
|
|
887
1025
|
return cls.PROJECTS[project]
|
|
888
1026
|
|
|
889
|
-
def __init__(self, project: str):
|
|
1027
|
+
def __init__(self, project: str) -> None:
|
|
890
1028
|
if getattr(self, "_inited", None):
|
|
891
1029
|
return
|
|
892
1030
|
self._batch_index = 0
|
|
@@ -896,8 +1034,8 @@ class Simplug:
|
|
|
896
1034
|
|
|
897
1035
|
def load_entrypoints(
|
|
898
1036
|
self,
|
|
899
|
-
group: str
|
|
900
|
-
only: str
|
|
1037
|
+
group: Optional[str] = None,
|
|
1038
|
+
only: Union[str, Iterable[str]] = (),
|
|
901
1039
|
) -> None:
|
|
902
1040
|
"""Load plugins from setuptools entry_points
|
|
903
1041
|
|
|
@@ -943,7 +1081,7 @@ class Simplug:
|
|
|
943
1081
|
# allow to use as a decorator
|
|
944
1082
|
return plugins[0]
|
|
945
1083
|
|
|
946
|
-
def get_plugin(self, name: str, raw: bool = False) ->
|
|
1084
|
+
def get_plugin(self, name: str, raw: bool = False) -> Union[SimplugWrapper, Any]:
|
|
947
1085
|
"""Get the plugin wrapper or the raw plugin object
|
|
948
1086
|
|
|
949
1087
|
Args:
|
|
@@ -963,7 +1101,7 @@ class Simplug:
|
|
|
963
1101
|
wrapper = self.hooks._registry[name]
|
|
964
1102
|
return wrapper.plugin if raw else wrapper
|
|
965
1103
|
|
|
966
|
-
def get_all_plugins(self, raw: bool = False) -> Dict[str,
|
|
1104
|
+
def get_all_plugins(self, raw: bool = False) -> Dict[str, Any]:
|
|
967
1105
|
"""Get a mapping of all plugins
|
|
968
1106
|
|
|
969
1107
|
Args:
|
|
@@ -981,7 +1119,7 @@ class Simplug:
|
|
|
981
1119
|
[(name, plugin.plugin) for name, plugin in self.hooks._registry.items()]
|
|
982
1120
|
)
|
|
983
1121
|
|
|
984
|
-
def get_enabled_plugins(self, raw: bool = False) -> Dict[str,
|
|
1122
|
+
def get_enabled_plugins(self, raw: bool = False) -> Dict[str, Any]:
|
|
985
1123
|
"""Get a mapping of all enabled plugins
|
|
986
1124
|
|
|
987
1125
|
Args:
|
|
@@ -1018,8 +1156,8 @@ class Simplug:
|
|
|
1018
1156
|
return [name for name, plugin in self.hooks._registry.items() if plugin.enabled]
|
|
1019
1157
|
|
|
1020
1158
|
def plugins_context(
|
|
1021
|
-
self, plugins: Iterable[Any]
|
|
1022
|
-
) -> SimplugContext
|
|
1159
|
+
self, plugins: Optional[Iterable[Any]]
|
|
1160
|
+
) -> Union[SimplugContext, nullcontext]:
|
|
1023
1161
|
"""A context manager with given plugins enabled or disabled
|
|
1024
1162
|
|
|
1025
1163
|
Args:
|
|
@@ -1080,11 +1218,11 @@ class Simplug:
|
|
|
1080
1218
|
|
|
1081
1219
|
def spec(
|
|
1082
1220
|
self,
|
|
1083
|
-
hook: Callable
|
|
1221
|
+
hook: Optional[Callable[..., Any]] = None,
|
|
1084
1222
|
required: bool = False,
|
|
1085
|
-
result: SimplugResult
|
|
1223
|
+
result: Union[SimplugResult, Callable] = SimplugResult.ALL_AVAILS,
|
|
1086
1224
|
warn_sync_impl_on_async: bool = True,
|
|
1087
|
-
) -> Callable:
|
|
1225
|
+
) -> Callable[..., Any]:
|
|
1088
1226
|
"""A decorator to define the specification of a hook
|
|
1089
1227
|
|
|
1090
1228
|
Args:
|
|
@@ -1133,7 +1271,7 @@ class Simplug:
|
|
|
1133
1271
|
|
|
1134
1272
|
return hook
|
|
1135
1273
|
|
|
1136
|
-
def impl(self, hook: Callable):
|
|
1274
|
+
def impl(self, hook: Callable[..., Any]) -> SimplugImpl:
|
|
1137
1275
|
"""A decorator for the implementation of a hook
|
|
1138
1276
|
|
|
1139
1277
|
Args:
|
|
File without changes
|
|
File without changes
|