miaoli-plugin 0.1.0__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.
- miaoli_plugin-0.1.0/PKG-INFO +156 -0
- miaoli_plugin-0.1.0/README.md +140 -0
- miaoli_plugin-0.1.0/miaoli_plugin/__init__.py +30 -0
- miaoli_plugin-0.1.0/miaoli_plugin/core/__init__.py +17 -0
- miaoli_plugin-0.1.0/miaoli_plugin/core/load_plugin.py +12 -0
- miaoli_plugin-0.1.0/miaoli_plugin/core/prepare_plugin.py +49 -0
- miaoli_plugin-0.1.0/miaoli_plugin/core/unload_plugin.py +6 -0
- miaoli_plugin-0.1.0/miaoli_plugin/errors/__init__.py +19 -0
- miaoli_plugin-0.1.0/miaoli_plugin/errors/entry_point_not_found.py +11 -0
- miaoli_plugin-0.1.0/miaoli_plugin/errors/plugin_same_name.py +8 -0
- miaoli_plugin-0.1.0/miaoli_plugin/errors/topology_error/__init__.py +17 -0
- miaoli_plugin-0.1.0/miaoli_plugin/errors/topology_error/base.py +2 -0
- miaoli_plugin-0.1.0/miaoli_plugin/errors/topology_error/circular_error.py +14 -0
- miaoli_plugin-0.1.0/miaoli_plugin/errors/topology_error/missing_error.py +14 -0
- miaoli_plugin-0.1.0/miaoli_plugin/loader.py +99 -0
- miaoli_plugin-0.1.0/miaoli_plugin/models/__init__.py +25 -0
- miaoli_plugin-0.1.0/miaoli_plugin/models/plugin_context.py +12 -0
- miaoli_plugin-0.1.0/miaoli_plugin/models/plugin_dependence.py +10 -0
- miaoli_plugin-0.1.0/miaoli_plugin/models/plugin_entry.py +7 -0
- miaoli_plugin-0.1.0/miaoli_plugin/models/plugin_manifest.py +15 -0
- miaoli_plugin-0.1.0/miaoli_plugin/models/plugin_metadata.py +13 -0
- miaoli_plugin-0.1.0/miaoli_plugin/protocols/__init__.py +9 -0
- miaoli_plugin-0.1.0/miaoli_plugin/protocols/base_plugin.py +43 -0
- miaoli_plugin-0.1.0/miaoli_plugin/py.typed +0 -0
- miaoli_plugin-0.1.0/miaoli_plugin/runtimes/__init__.py +9 -0
- miaoli_plugin-0.1.0/miaoli_plugin/runtimes/plugin_record.py +10 -0
- miaoli_plugin-0.1.0/miaoli_plugin/utils/__init__.py +25 -0
- miaoli_plugin-0.1.0/miaoli_plugin/utils/missing_check.py +18 -0
- miaoli_plugin-0.1.0/miaoli_plugin/utils/read_manifest.py +22 -0
- miaoli_plugin-0.1.0/miaoli_plugin/utils/remove_package.py +12 -0
- miaoli_plugin-0.1.0/miaoli_plugin/utils/topology_once.py +26 -0
- miaoli_plugin-0.1.0/miaoli_plugin/utils/topology_sort.py +32 -0
- miaoli_plugin-0.1.0/miaoli_plugin.egg-info/PKG-INFO +156 -0
- miaoli_plugin-0.1.0/miaoli_plugin.egg-info/SOURCES.txt +37 -0
- miaoli_plugin-0.1.0/miaoli_plugin.egg-info/dependency_links.txt +1 -0
- miaoli_plugin-0.1.0/miaoli_plugin.egg-info/requires.txt +1 -0
- miaoli_plugin-0.1.0/miaoli_plugin.egg-info/top_level.txt +1 -0
- miaoli_plugin-0.1.0/pyproject.toml +33 -0
- miaoli_plugin-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: miaoli-plugin
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 喵璃的插件加载器:按 manifest.toml 发现、拓扑排序并加载目录式插件
|
|
5
|
+
Author: 超·乃依
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/lyt2011/miaoli_bot
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.12
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: pydantic>=2.0
|
|
16
|
+
|
|
17
|
+
# miaoli-plugin
|
|
18
|
+
|
|
19
|
+
喵璃的插件加载器:按 `manifest.toml` 发现、拓扑排序、加载和卸载**目录式插件**。
|
|
20
|
+
|
|
21
|
+
一个「插件」= 磁盘上一个含 `manifest.toml` 的目录,目录里放一个继承 `BasePlugin` 的类。
|
|
22
|
+
插件身份只由 `manifest.toml` 里的 `metadata.name` 决定,**目录名无所谓**。
|
|
23
|
+
|
|
24
|
+
## 安装
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install .
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## 用法
|
|
31
|
+
|
|
32
|
+
### 写一个插件
|
|
33
|
+
|
|
34
|
+
目录 `plugins/my_plugin/`,先写清单:
|
|
35
|
+
|
|
36
|
+
```toml
|
|
37
|
+
# manifest.toml
|
|
38
|
+
[metadata]
|
|
39
|
+
name = "my_plugin"
|
|
40
|
+
version = "1.0.0"
|
|
41
|
+
author = "超·乃依"
|
|
42
|
+
description = "示例插件"
|
|
43
|
+
|
|
44
|
+
[dependence]
|
|
45
|
+
pip = []
|
|
46
|
+
mpm = []
|
|
47
|
+
|
|
48
|
+
[entry]
|
|
49
|
+
entry_cls = "MyPlugin"
|
|
50
|
+
entry_module = "my_plugin"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
再写入口:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
# plugins/my_plugin/__init__.py
|
|
57
|
+
from miaoli_plugin import BasePlugin
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class MyPlugin(BasePlugin):
|
|
61
|
+
|
|
62
|
+
async def onload(self) -> None:
|
|
63
|
+
print(f"{self.manifest.metadata.name} 已加载")
|
|
64
|
+
|
|
65
|
+
async def unload(self) -> None:
|
|
66
|
+
print(f"{self.manifest.metadata.name} 已卸载")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`onload()` / `unload()` 里可以放心用 `self.ctx` 和 `self.manifest`,框架在调用前已经挂好了。
|
|
70
|
+
|
|
71
|
+
### 加载
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
import asyncio
|
|
75
|
+
|
|
76
|
+
from miaoli_plugin import PluginLoader
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
loader = PluginLoader()
|
|
80
|
+
|
|
81
|
+
asyncio.run(loader.load_all([
|
|
82
|
+
{"enabled": True, "path": "plugins/my_plugin", "config": {}},
|
|
83
|
+
]))
|
|
84
|
+
|
|
85
|
+
for instance in loader.instances:
|
|
86
|
+
print(type(instance).__name__)
|
|
87
|
+
|
|
88
|
+
asyncio.run(loader.unload_all())
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`load_all()` 收的是 `PluginContext` 的原始字典,字段:`enabled` / `path` / `config`。
|
|
92
|
+
`path` 必须是**存在的目录**,加载时用 pydantic 的 `DirectoryPath` 校验。
|
|
93
|
+
|
|
94
|
+
## 加载语义
|
|
95
|
+
|
|
96
|
+
| 行为 | 说明 |
|
|
97
|
+
| --- | --- |
|
|
98
|
+
| 顺序 | 按 `dependence.mpm` 拓扑排序,**依赖在前** |
|
|
99
|
+
| 失败 | 打日志 + 清理 `sys.modules` 残留 + **跳过该插件**,不回滚已加载的 |
|
|
100
|
+
| 连锁失败 | 依赖了失败插件的插件照样尝试加载,通常也会失败 |
|
|
101
|
+
| 卸载 | `unload_all()` 按**加载顺序的逆序**,也就是反向拓扑序 |
|
|
102
|
+
| `instances` | 只读元组,顺序即加载顺序 |
|
|
103
|
+
| 重名 | 两个目录声明了同一个 `name` 直接抛 `PluginSameNameError`,不覆盖 |
|
|
104
|
+
|
|
105
|
+
`dependence.pip` 目前只是清单字段,**加载器不会替你装**;`dependence.mpm` 才会参与拓扑排序。
|
|
106
|
+
|
|
107
|
+
## 内容
|
|
108
|
+
|
|
109
|
+
| 模块 | 导出 |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `loader` | `PluginLoader` |
|
|
112
|
+
| `core` | `prepare_plugin`, `load_plugin`, `unload_plugin` |
|
|
113
|
+
| `protocols` | `BasePlugin` |
|
|
114
|
+
| `models` | `PluginContext`, `PluginMetadata`, `PluginDependence`, `PluginEntry`, `PluginManifest` |
|
|
115
|
+
| `runtimes` | `PluginRecord` |
|
|
116
|
+
| `errors` | `TopologyError`, `TopologyCircularError`, `TopologyMissingError`, `EntryPointNotFound`, `PluginSameNameError` |
|
|
117
|
+
| `utils` | `topology_sort`, `topology_once`, `missing_check`, `read_manifest`, `remove_package` |
|
|
118
|
+
|
|
119
|
+
`core` 里是**单个插件**的三个原语,`loader` 是**编排层**:把这三个动作对一批插件跑一遍。
|
|
120
|
+
|
|
121
|
+
## 结构
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
miaoli_plugin/
|
|
125
|
+
├── loader.py PluginLoader
|
|
126
|
+
├── core/
|
|
127
|
+
│ ├── prepare_plugin.py prepare_plugin
|
|
128
|
+
│ ├── load_plugin.py load_plugin
|
|
129
|
+
│ └── unload_plugin.py unload_plugin
|
|
130
|
+
├── protocols/
|
|
131
|
+
│ └── base_plugin.py BasePlugin
|
|
132
|
+
├── models/
|
|
133
|
+
│ ├── plugin_manifest.py PluginManifest
|
|
134
|
+
│ ├── plugin_metadata.py PluginMetadata
|
|
135
|
+
│ ├── plugin_dependence.py PluginDependence
|
|
136
|
+
│ ├── plugin_entry.py PluginEntry
|
|
137
|
+
│ └── plugin_context.py PluginContext
|
|
138
|
+
├── runtimes/
|
|
139
|
+
│ └── plugin_record.py PluginRecord
|
|
140
|
+
├── errors/
|
|
141
|
+
│ ├── topology_error/ 拓扑错误三件套
|
|
142
|
+
│ ├── entry_point_not_found.py
|
|
143
|
+
│ └── plugin_same_name.py
|
|
144
|
+
└── utils/
|
|
145
|
+
├── read_manifest.py read_manifest
|
|
146
|
+
├── topology_sort.py topology_sort
|
|
147
|
+
├── topology_once.py topology_once
|
|
148
|
+
├── missing_check.py missing_check
|
|
149
|
+
└── remove_package.py remove_package
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## 注意
|
|
153
|
+
|
|
154
|
+
- `manifest.toml` 必须是 UTF-8、**不能带 BOM**。TOML 规范要求 UTF-8 无 BOM,`tomllib` 遇到 BOM 会直接 `TOMLDecodeError`。
|
|
155
|
+
- 插件名会被直接当成 `sys.modules` 里的**顶层包名**用,别跟标准库重名(否则会遮住真的标准库)。
|
|
156
|
+
- 卸载时 `remove_package()` 会**无条件**清掉该名字在 `sys.modules` 里的所有条目,包括插件自己 import 的子模块。
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# miaoli-plugin
|
|
2
|
+
|
|
3
|
+
喵璃的插件加载器:按 `manifest.toml` 发现、拓扑排序、加载和卸载**目录式插件**。
|
|
4
|
+
|
|
5
|
+
一个「插件」= 磁盘上一个含 `manifest.toml` 的目录,目录里放一个继承 `BasePlugin` 的类。
|
|
6
|
+
插件身份只由 `manifest.toml` 里的 `metadata.name` 决定,**目录名无所谓**。
|
|
7
|
+
|
|
8
|
+
## 安装
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install .
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## 用法
|
|
15
|
+
|
|
16
|
+
### 写一个插件
|
|
17
|
+
|
|
18
|
+
目录 `plugins/my_plugin/`,先写清单:
|
|
19
|
+
|
|
20
|
+
```toml
|
|
21
|
+
# manifest.toml
|
|
22
|
+
[metadata]
|
|
23
|
+
name = "my_plugin"
|
|
24
|
+
version = "1.0.0"
|
|
25
|
+
author = "超·乃依"
|
|
26
|
+
description = "示例插件"
|
|
27
|
+
|
|
28
|
+
[dependence]
|
|
29
|
+
pip = []
|
|
30
|
+
mpm = []
|
|
31
|
+
|
|
32
|
+
[entry]
|
|
33
|
+
entry_cls = "MyPlugin"
|
|
34
|
+
entry_module = "my_plugin"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
再写入口:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
# plugins/my_plugin/__init__.py
|
|
41
|
+
from miaoli_plugin import BasePlugin
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class MyPlugin(BasePlugin):
|
|
45
|
+
|
|
46
|
+
async def onload(self) -> None:
|
|
47
|
+
print(f"{self.manifest.metadata.name} 已加载")
|
|
48
|
+
|
|
49
|
+
async def unload(self) -> None:
|
|
50
|
+
print(f"{self.manifest.metadata.name} 已卸载")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`onload()` / `unload()` 里可以放心用 `self.ctx` 和 `self.manifest`,框架在调用前已经挂好了。
|
|
54
|
+
|
|
55
|
+
### 加载
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import asyncio
|
|
59
|
+
|
|
60
|
+
from miaoli_plugin import PluginLoader
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
loader = PluginLoader()
|
|
64
|
+
|
|
65
|
+
asyncio.run(loader.load_all([
|
|
66
|
+
{"enabled": True, "path": "plugins/my_plugin", "config": {}},
|
|
67
|
+
]))
|
|
68
|
+
|
|
69
|
+
for instance in loader.instances:
|
|
70
|
+
print(type(instance).__name__)
|
|
71
|
+
|
|
72
|
+
asyncio.run(loader.unload_all())
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`load_all()` 收的是 `PluginContext` 的原始字典,字段:`enabled` / `path` / `config`。
|
|
76
|
+
`path` 必须是**存在的目录**,加载时用 pydantic 的 `DirectoryPath` 校验。
|
|
77
|
+
|
|
78
|
+
## 加载语义
|
|
79
|
+
|
|
80
|
+
| 行为 | 说明 |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| 顺序 | 按 `dependence.mpm` 拓扑排序,**依赖在前** |
|
|
83
|
+
| 失败 | 打日志 + 清理 `sys.modules` 残留 + **跳过该插件**,不回滚已加载的 |
|
|
84
|
+
| 连锁失败 | 依赖了失败插件的插件照样尝试加载,通常也会失败 |
|
|
85
|
+
| 卸载 | `unload_all()` 按**加载顺序的逆序**,也就是反向拓扑序 |
|
|
86
|
+
| `instances` | 只读元组,顺序即加载顺序 |
|
|
87
|
+
| 重名 | 两个目录声明了同一个 `name` 直接抛 `PluginSameNameError`,不覆盖 |
|
|
88
|
+
|
|
89
|
+
`dependence.pip` 目前只是清单字段,**加载器不会替你装**;`dependence.mpm` 才会参与拓扑排序。
|
|
90
|
+
|
|
91
|
+
## 内容
|
|
92
|
+
|
|
93
|
+
| 模块 | 导出 |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `loader` | `PluginLoader` |
|
|
96
|
+
| `core` | `prepare_plugin`, `load_plugin`, `unload_plugin` |
|
|
97
|
+
| `protocols` | `BasePlugin` |
|
|
98
|
+
| `models` | `PluginContext`, `PluginMetadata`, `PluginDependence`, `PluginEntry`, `PluginManifest` |
|
|
99
|
+
| `runtimes` | `PluginRecord` |
|
|
100
|
+
| `errors` | `TopologyError`, `TopologyCircularError`, `TopologyMissingError`, `EntryPointNotFound`, `PluginSameNameError` |
|
|
101
|
+
| `utils` | `topology_sort`, `topology_once`, `missing_check`, `read_manifest`, `remove_package` |
|
|
102
|
+
|
|
103
|
+
`core` 里是**单个插件**的三个原语,`loader` 是**编排层**:把这三个动作对一批插件跑一遍。
|
|
104
|
+
|
|
105
|
+
## 结构
|
|
106
|
+
|
|
107
|
+
```
|
|
108
|
+
miaoli_plugin/
|
|
109
|
+
├── loader.py PluginLoader
|
|
110
|
+
├── core/
|
|
111
|
+
│ ├── prepare_plugin.py prepare_plugin
|
|
112
|
+
│ ├── load_plugin.py load_plugin
|
|
113
|
+
│ └── unload_plugin.py unload_plugin
|
|
114
|
+
├── protocols/
|
|
115
|
+
│ └── base_plugin.py BasePlugin
|
|
116
|
+
├── models/
|
|
117
|
+
│ ├── plugin_manifest.py PluginManifest
|
|
118
|
+
│ ├── plugin_metadata.py PluginMetadata
|
|
119
|
+
│ ├── plugin_dependence.py PluginDependence
|
|
120
|
+
│ ├── plugin_entry.py PluginEntry
|
|
121
|
+
│ └── plugin_context.py PluginContext
|
|
122
|
+
├── runtimes/
|
|
123
|
+
│ └── plugin_record.py PluginRecord
|
|
124
|
+
├── errors/
|
|
125
|
+
│ ├── topology_error/ 拓扑错误三件套
|
|
126
|
+
│ ├── entry_point_not_found.py
|
|
127
|
+
│ └── plugin_same_name.py
|
|
128
|
+
└── utils/
|
|
129
|
+
├── read_manifest.py read_manifest
|
|
130
|
+
├── topology_sort.py topology_sort
|
|
131
|
+
├── topology_once.py topology_once
|
|
132
|
+
├── missing_check.py missing_check
|
|
133
|
+
└── remove_package.py remove_package
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## 注意
|
|
137
|
+
|
|
138
|
+
- `manifest.toml` 必须是 UTF-8、**不能带 BOM**。TOML 规范要求 UTF-8 无 BOM,`tomllib` 遇到 BOM 会直接 `TOMLDecodeError`。
|
|
139
|
+
- 插件名会被直接当成 `sys.modules` 里的**顶层包名**用,别跟标准库重名(否则会遮住真的标准库)。
|
|
140
|
+
- 卸载时 `remove_package()` 会**无条件**清掉该名字在 `sys.modules` 里的所有条目,包括插件自己 import 的子模块。
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from . import (
|
|
2
|
+
core,
|
|
3
|
+
errors,
|
|
4
|
+
models,
|
|
5
|
+
protocols,
|
|
6
|
+
runtimes,
|
|
7
|
+
utils,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
from .loader import PluginLoader
|
|
11
|
+
from .protocols import BasePlugin
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
__all__ = (
|
|
15
|
+
|
|
16
|
+
# loader
|
|
17
|
+
"PluginLoader",
|
|
18
|
+
|
|
19
|
+
# protocols
|
|
20
|
+
"BasePlugin",
|
|
21
|
+
|
|
22
|
+
# 子包
|
|
23
|
+
"core",
|
|
24
|
+
"errors",
|
|
25
|
+
"models",
|
|
26
|
+
"protocols",
|
|
27
|
+
"runtimes",
|
|
28
|
+
"utils",
|
|
29
|
+
|
|
30
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .prepare_plugin import prepare_plugin
|
|
2
|
+
from .load_plugin import load_plugin
|
|
3
|
+
from .unload_plugin import unload_plugin
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
__all__ = (
|
|
7
|
+
|
|
8
|
+
# prepare_plugin
|
|
9
|
+
"prepare_plugin",
|
|
10
|
+
|
|
11
|
+
# load_plugin
|
|
12
|
+
"load_plugin",
|
|
13
|
+
|
|
14
|
+
# unload_plugin
|
|
15
|
+
"unload_plugin",
|
|
16
|
+
|
|
17
|
+
)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from ..models import PluginContext, PluginManifest
|
|
2
|
+
from ..protocols import BasePlugin
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
async def load_plugin(cls: type[BasePlugin], ctx: PluginContext, manifest: PluginManifest) -> BasePlugin:
|
|
6
|
+
|
|
7
|
+
"""加载 BasePlugin 类"""
|
|
8
|
+
|
|
9
|
+
instance = cls()
|
|
10
|
+
await instance.__onload__(ctx=ctx, manifest=manifest)
|
|
11
|
+
|
|
12
|
+
return instance
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from ..errors import EntryPointNotFound
|
|
2
|
+
from ..models import PluginManifest
|
|
3
|
+
from ..protocols import BasePlugin
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import importlib
|
|
8
|
+
import importlib.util
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def prepare_plugin(path: Path, manifest: PluginManifest) -> type[BasePlugin]:
|
|
13
|
+
|
|
14
|
+
"""准备单个插件包 返回插件类"""
|
|
15
|
+
|
|
16
|
+
# 短名引用
|
|
17
|
+
entry_cls = manifest.entry.entry_cls
|
|
18
|
+
entry_module = manifest.entry.entry_module
|
|
19
|
+
package_name = manifest.metadata.name
|
|
20
|
+
|
|
21
|
+
# 用 path 造 ModuleSpec 对象
|
|
22
|
+
module_spec = importlib.util.spec_from_file_location(
|
|
23
|
+
package_name,
|
|
24
|
+
str(path / "__init__.py"),
|
|
25
|
+
submodule_search_locations=[str(path)]
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# 用 ModuleSpec 造 ModuleType 实例
|
|
29
|
+
module_type = importlib.util.module_from_spec(module_spec)
|
|
30
|
+
|
|
31
|
+
# 注册包到 sys.modules
|
|
32
|
+
sys.modules[package_name] = module_type
|
|
33
|
+
|
|
34
|
+
# 执行 module 的代码
|
|
35
|
+
module_spec.loader.exec_module(module_type)
|
|
36
|
+
|
|
37
|
+
# 兼容相对绝对路径与绝对路径两种写法 同时处理入口在 __init__.py 的情况
|
|
38
|
+
if entry_module != package_name and not entry_module.startswith(f"{package_name}."):
|
|
39
|
+
entry_module = f"{package_name}.{entry_module}"
|
|
40
|
+
|
|
41
|
+
# 拿到入口模块
|
|
42
|
+
module = importlib.import_module(entry_module)
|
|
43
|
+
|
|
44
|
+
# 拿入口类 校验入口类存在性与类型
|
|
45
|
+
cls = getattr(module, entry_cls, None)
|
|
46
|
+
if not isinstance(cls, type) or not issubclass(cls, BasePlugin):
|
|
47
|
+
raise EntryPointNotFound(path=str(path), package_name=package_name, entry_module=entry_module, entry_cls=entry_cls)
|
|
48
|
+
|
|
49
|
+
return cls
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from .topology_error import TopologyCircularError, TopologyError, TopologyMissingError
|
|
2
|
+
from .entry_point_not_found import EntryPointNotFound
|
|
3
|
+
from .plugin_same_name import PluginSameNameError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
__all__ = (
|
|
7
|
+
|
|
8
|
+
# topology_error
|
|
9
|
+
"TopologyError",
|
|
10
|
+
"TopologyCircularError",
|
|
11
|
+
"TopologyMissingError",
|
|
12
|
+
|
|
13
|
+
# entry_point_not_found
|
|
14
|
+
"EntryPointNotFound",
|
|
15
|
+
|
|
16
|
+
# plugin_same_name
|
|
17
|
+
"PluginSameNameError",
|
|
18
|
+
|
|
19
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
class EntryPointNotFound(RuntimeError):
|
|
2
|
+
|
|
3
|
+
def __init__(self, path: str, package_name: str, entry_module: str, entry_cls: str) -> None:
|
|
4
|
+
|
|
5
|
+
self.path = path
|
|
6
|
+
self.package_name = package_name
|
|
7
|
+
self.entry_module = entry_module
|
|
8
|
+
self.entry_cls = entry_cls
|
|
9
|
+
|
|
10
|
+
super().__init__(f"找不到 {package_name}({path}) 的入口点 {entry_module}:{entry_cls}")
|
|
11
|
+
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .base import TopologyError
|
|
2
|
+
from .circular_error import TopologyCircularError
|
|
3
|
+
from .missing_error import TopologyMissingError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
__all__ = (
|
|
7
|
+
|
|
8
|
+
# base
|
|
9
|
+
"TopologyError",
|
|
10
|
+
|
|
11
|
+
# circular_error
|
|
12
|
+
"TopologyCircularError",
|
|
13
|
+
|
|
14
|
+
# missing_error
|
|
15
|
+
"TopologyMissingError",
|
|
16
|
+
|
|
17
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .base import TopologyError
|
|
2
|
+
|
|
3
|
+
from typing import Dict, List
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TopologyCircularError(TopologyError):
|
|
7
|
+
|
|
8
|
+
"""拓扑排序检测到循环依赖"""
|
|
9
|
+
|
|
10
|
+
def __init__(self, circular: Dict[str, List[str]]) -> None:
|
|
11
|
+
|
|
12
|
+
self.circular = circular
|
|
13
|
+
|
|
14
|
+
super().__init__(f"检测到循环依赖: {circular}")
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .base import TopologyError
|
|
2
|
+
|
|
3
|
+
from typing import Dict, List
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TopologyMissingError(TopologyError):
|
|
7
|
+
|
|
8
|
+
"""拓扑排序检测到依赖缺失"""
|
|
9
|
+
|
|
10
|
+
def __init__(self, missing: Dict[str, List[str]]) -> None:
|
|
11
|
+
|
|
12
|
+
self.missing = missing
|
|
13
|
+
|
|
14
|
+
super().__init__(f"以下插件依赖了不存在的插件: {missing}")
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from .core import prepare_plugin, load_plugin, unload_plugin
|
|
2
|
+
from .errors import PluginSameNameError
|
|
3
|
+
from .models import PluginContext
|
|
4
|
+
from .protocols import BasePlugin
|
|
5
|
+
from .runtimes import PluginRecord
|
|
6
|
+
from .utils import read_manifest, remove_package, topology_sort
|
|
7
|
+
|
|
8
|
+
from typing import Any, Dict, List, Tuple
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
LOGGER = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PluginLoader:
|
|
17
|
+
|
|
18
|
+
_instances: List[BasePlugin]
|
|
19
|
+
|
|
20
|
+
def __init__(self) -> None:
|
|
21
|
+
self._instances = []
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def instances(self) -> Tuple[BasePlugin, ...]:
|
|
25
|
+
return tuple(self._instances)
|
|
26
|
+
|
|
27
|
+
async def load_all(self, contexts: List[Dict[str, Any]]) -> None:
|
|
28
|
+
|
|
29
|
+
"""
|
|
30
|
+
从 contexts 加载并构建所有 BasePlugin
|
|
31
|
+
|
|
32
|
+
加载失败的插件会打日志并清理 sys.modules 后跳过
|
|
33
|
+
而依赖该失败插件的其他插件照样会被加载 一般来说也会加载失败
|
|
34
|
+
|
|
35
|
+
最终 _instances 里是加载成功的插件 可安全 unload
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
records: Dict[str, PluginRecord] = {}
|
|
39
|
+
|
|
40
|
+
# 从原始字典构建 PluginRecord
|
|
41
|
+
for raw_context in contexts:
|
|
42
|
+
|
|
43
|
+
ctx = PluginContext.model_validate(raw_context)
|
|
44
|
+
manifest = read_manifest(ctx.path)
|
|
45
|
+
|
|
46
|
+
# 如果有重名插件 直接报错而不是覆盖
|
|
47
|
+
if manifest.metadata.name in records:
|
|
48
|
+
raise PluginSameNameError(name=manifest.metadata.name)
|
|
49
|
+
|
|
50
|
+
records[manifest.metadata.name] = PluginRecord(ctx=ctx, manifest=manifest)
|
|
51
|
+
|
|
52
|
+
# 拓扑排序
|
|
53
|
+
order = topology_sort({name: list(record.manifest.dependence.mpm)
|
|
54
|
+
for name, record in records.items()})
|
|
55
|
+
|
|
56
|
+
# 按照拓扑序重建字典
|
|
57
|
+
records = {name: records[name] for name in order}
|
|
58
|
+
|
|
59
|
+
for record in records.values():
|
|
60
|
+
|
|
61
|
+
# 准备插件并加载 但不回滚
|
|
62
|
+
try:
|
|
63
|
+
plugin_cls = prepare_plugin(path=record.ctx.path, manifest=record.manifest)
|
|
64
|
+
instance = await load_plugin(cls=plugin_cls, ctx=record.ctx, manifest=record.manifest)
|
|
65
|
+
|
|
66
|
+
except Exception as exc:
|
|
67
|
+
|
|
68
|
+
# 清理 sys.modules 的残留
|
|
69
|
+
remove_package(record.manifest.metadata.name)
|
|
70
|
+
|
|
71
|
+
LOGGER.exception(f"插件 {record.manifest.metadata.name}"
|
|
72
|
+
f"({record.ctx.path}) 加载失败: {type(exc).__name__}: {exc}")
|
|
73
|
+
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
self._instances.append(instance)
|
|
77
|
+
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
async def unload_all(self) -> None:
|
|
81
|
+
|
|
82
|
+
"""
|
|
83
|
+
卸载所有 self._instances 内插件
|
|
84
|
+
报错会跳过该插件的卸载 (无条件删 sys.modules)
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
# 直接翻转 self._instances 顺序 来源保证顺序
|
|
88
|
+
for instance in tuple(reversed(self._instances)):
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
await unload_plugin(instance)
|
|
92
|
+
|
|
93
|
+
except Exception:
|
|
94
|
+
LOGGER.exception(f"插件 "
|
|
95
|
+
f"{instance.manifest.metadata.name}({instance.ctx.path}) 卸载失败")
|
|
96
|
+
|
|
97
|
+
self._instances.remove(instance)
|
|
98
|
+
|
|
99
|
+
return None
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from .plugin_context import PluginContext
|
|
2
|
+
from .plugin_metadata import PluginMetadata
|
|
3
|
+
from .plugin_dependence import PluginDependence
|
|
4
|
+
from .plugin_entry import PluginEntry
|
|
5
|
+
from .plugin_manifest import PluginManifest
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
__all__ = (
|
|
9
|
+
|
|
10
|
+
# plugin_context
|
|
11
|
+
"PluginContext",
|
|
12
|
+
|
|
13
|
+
# plugin_metadata
|
|
14
|
+
"PluginMetadata",
|
|
15
|
+
|
|
16
|
+
# plugin_dependence
|
|
17
|
+
"PluginDependence",
|
|
18
|
+
|
|
19
|
+
# plugin_entry
|
|
20
|
+
"PluginEntry",
|
|
21
|
+
|
|
22
|
+
# plugin_manifest
|
|
23
|
+
"PluginManifest",
|
|
24
|
+
|
|
25
|
+
)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from pydantic import BaseModel, DirectoryPath, Field
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PluginContext(BaseModel):
|
|
7
|
+
|
|
8
|
+
enabled : bool = Field(..., description="是否启用插件")
|
|
9
|
+
|
|
10
|
+
path : DirectoryPath = Field(..., description="插件路径")
|
|
11
|
+
config : Dict[str, Any] = Field(default_factory=dict, description="插件配置")
|
|
12
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from pydantic import BaseModel, Field
|
|
2
|
+
from typing import List
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class PluginDependence(BaseModel):
|
|
6
|
+
|
|
7
|
+
"""插件依赖"""
|
|
8
|
+
|
|
9
|
+
pip : List[str] = Field(default_factory=list, description="pip 依赖")
|
|
10
|
+
mpm : List[str] = Field(default_factory=list, description="miaoli-plugin 依赖")
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .plugin_metadata import PluginMetadata
|
|
2
|
+
from .plugin_dependence import PluginDependence
|
|
3
|
+
from .plugin_entry import PluginEntry
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PluginManifest(BaseModel):
|
|
9
|
+
|
|
10
|
+
"""插件自身清单"""
|
|
11
|
+
|
|
12
|
+
metadata : PluginMetadata = Field(..., description="插件元数据")
|
|
13
|
+
dependence : PluginDependence = Field(..., description="插件依赖")
|
|
14
|
+
entry : PluginEntry = Field(..., description="插件入口")
|
|
15
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from pydantic import BaseModel, Field
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PluginMetadata(BaseModel):
|
|
7
|
+
|
|
8
|
+
"""插件元数据"""
|
|
9
|
+
|
|
10
|
+
name : str = Field(..., description="插件名")
|
|
11
|
+
version : str = Field(..., description="插件版本")
|
|
12
|
+
author : Optional[str] = Field(default=None, description="插件作者")
|
|
13
|
+
description : Optional[str] = Field(default=None, description="插件描述")
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from ..models import PluginContext, PluginManifest
|
|
2
|
+
from ..utils import remove_package
|
|
3
|
+
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class BasePlugin(ABC):
|
|
8
|
+
|
|
9
|
+
ctx : PluginContext
|
|
10
|
+
manifest: PluginManifest
|
|
11
|
+
|
|
12
|
+
@abstractmethod
|
|
13
|
+
async def onload(self) -> None: ...
|
|
14
|
+
|
|
15
|
+
@abstractmethod
|
|
16
|
+
async def unload(self) -> None: ...
|
|
17
|
+
|
|
18
|
+
async def __onload__(self, ctx: PluginContext, manifest: PluginManifest) -> None:
|
|
19
|
+
|
|
20
|
+
"""
|
|
21
|
+
框架内调用的加载逻辑
|
|
22
|
+
自动挂载 ctx 与 manifest 实例属性
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
self.ctx = ctx
|
|
26
|
+
self.manifest = manifest
|
|
27
|
+
|
|
28
|
+
await self.onload()
|
|
29
|
+
|
|
30
|
+
async def __unload__(self) -> None:
|
|
31
|
+
|
|
32
|
+
"""
|
|
33
|
+
框架内调用的卸载转发
|
|
34
|
+
自动清理 sys.module 对于 name 的残留 (无条件)
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
# 无条件清理 sys.modules
|
|
38
|
+
try:
|
|
39
|
+
await self.unload()
|
|
40
|
+
finally:
|
|
41
|
+
remove_package(self.manifest.metadata.name)
|
|
42
|
+
|
|
43
|
+
return None
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from .topology_sort import topology_sort
|
|
2
|
+
from .topology_once import topology_once
|
|
3
|
+
from .missing_check import missing_check
|
|
4
|
+
from .read_manifest import read_manifest
|
|
5
|
+
from .remove_package import remove_package
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
__all__ = (
|
|
9
|
+
|
|
10
|
+
# topology_sort
|
|
11
|
+
"topology_sort",
|
|
12
|
+
|
|
13
|
+
# topology_once
|
|
14
|
+
"topology_once",
|
|
15
|
+
|
|
16
|
+
# missing_check
|
|
17
|
+
"missing_check",
|
|
18
|
+
|
|
19
|
+
# read_manifest
|
|
20
|
+
"read_manifest",
|
|
21
|
+
|
|
22
|
+
# remove_package
|
|
23
|
+
"remove_package",
|
|
24
|
+
|
|
25
|
+
)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from collections import defaultdict
|
|
2
|
+
from typing import Dict, List
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def missing_check(data: Dict[str, List[str]]) -> Dict[str, List[str]]:
|
|
6
|
+
|
|
7
|
+
"""依赖缺失检查 返回 依赖来源->缺失依赖 的映射表"""
|
|
8
|
+
|
|
9
|
+
# 缺失的依赖映射表 依赖来源 -> 缺失依赖
|
|
10
|
+
missing = defaultdict(list)
|
|
11
|
+
|
|
12
|
+
# 对于不存在的依赖 把名字与依赖添加进 missing
|
|
13
|
+
for name, dependences in data.items():
|
|
14
|
+
for dependence in dependences:
|
|
15
|
+
if dependence not in data:
|
|
16
|
+
missing[name].append(dependence)
|
|
17
|
+
|
|
18
|
+
return dict(missing)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from ..models import PluginManifest
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def read_manifest(package: str) -> PluginManifest:
|
|
9
|
+
|
|
10
|
+
"""读包的 manifest.toml 返回 PluginManifest"""
|
|
11
|
+
|
|
12
|
+
manifest_toml = Path(package) / "manifest.toml"
|
|
13
|
+
|
|
14
|
+
# 清单不存在 直接报错
|
|
15
|
+
if not manifest_toml.is_file():
|
|
16
|
+
raise FileNotFoundError(f"找不到 manifest.toml: {package}")
|
|
17
|
+
|
|
18
|
+
# 校验并返回 manifest.toml 二进制读取 编码由 tomllib 按规范处理
|
|
19
|
+
with manifest_toml.open("rb") as manifest_data:
|
|
20
|
+
manifest = PluginManifest.model_validate(tomllib.load(manifest_data))
|
|
21
|
+
|
|
22
|
+
return manifest
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from typing import Dict, List, Tuple
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def topology_once(data: Dict[str, List[str]]) -> Tuple[Dict[str, List[str]], List[str]]:
|
|
5
|
+
|
|
6
|
+
"""拓扑排序一次 返回排序后的数据副本与排序后的键"""
|
|
7
|
+
|
|
8
|
+
result = []
|
|
9
|
+
data = dict(data)
|
|
10
|
+
|
|
11
|
+
for name, dependences in dict(data).items():
|
|
12
|
+
|
|
13
|
+
# 有依赖则不管
|
|
14
|
+
if dependences:
|
|
15
|
+
continue
|
|
16
|
+
|
|
17
|
+
# 排序并清理 data
|
|
18
|
+
data.pop(name)
|
|
19
|
+
result.append(name)
|
|
20
|
+
|
|
21
|
+
# 清理其他键对 name 的引用
|
|
22
|
+
for _dependences in dict(data).values():
|
|
23
|
+
if name in _dependences:
|
|
24
|
+
_dependences.remove(name)
|
|
25
|
+
|
|
26
|
+
return data, result
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from .missing_check import missing_check
|
|
2
|
+
from .topology_once import topology_once
|
|
3
|
+
from ..errors import TopologyCircularError, TopologyMissingError
|
|
4
|
+
|
|
5
|
+
from typing import Dict, List
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def topology_sort(data: Dict[str, List[str]]) -> List[str]:
|
|
9
|
+
|
|
10
|
+
"""基于字典的通用拓扑排序"""
|
|
11
|
+
|
|
12
|
+
# 检查缺失依赖
|
|
13
|
+
if missing := missing_check(data):
|
|
14
|
+
raise TopologyMissingError(missing=missing)
|
|
15
|
+
|
|
16
|
+
sorted_list = []
|
|
17
|
+
if not data: # 拦截空数据
|
|
18
|
+
return sorted_list
|
|
19
|
+
|
|
20
|
+
while True:
|
|
21
|
+
|
|
22
|
+
# 排序一次 无结果代表有环
|
|
23
|
+
data, result = topology_once(data)
|
|
24
|
+
if not result:
|
|
25
|
+
raise TopologyCircularError(circular=dict(data))
|
|
26
|
+
|
|
27
|
+
sorted_list.extend(result)
|
|
28
|
+
|
|
29
|
+
if not data:
|
|
30
|
+
break
|
|
31
|
+
|
|
32
|
+
return sorted_list
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: miaoli-plugin
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 喵璃的插件加载器:按 manifest.toml 发现、拓扑排序并加载目录式插件
|
|
5
|
+
Author: 超·乃依
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/lyt2011/miaoli_bot
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.12
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: pydantic>=2.0
|
|
16
|
+
|
|
17
|
+
# miaoli-plugin
|
|
18
|
+
|
|
19
|
+
喵璃的插件加载器:按 `manifest.toml` 发现、拓扑排序、加载和卸载**目录式插件**。
|
|
20
|
+
|
|
21
|
+
一个「插件」= 磁盘上一个含 `manifest.toml` 的目录,目录里放一个继承 `BasePlugin` 的类。
|
|
22
|
+
插件身份只由 `manifest.toml` 里的 `metadata.name` 决定,**目录名无所谓**。
|
|
23
|
+
|
|
24
|
+
## 安装
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install .
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## 用法
|
|
31
|
+
|
|
32
|
+
### 写一个插件
|
|
33
|
+
|
|
34
|
+
目录 `plugins/my_plugin/`,先写清单:
|
|
35
|
+
|
|
36
|
+
```toml
|
|
37
|
+
# manifest.toml
|
|
38
|
+
[metadata]
|
|
39
|
+
name = "my_plugin"
|
|
40
|
+
version = "1.0.0"
|
|
41
|
+
author = "超·乃依"
|
|
42
|
+
description = "示例插件"
|
|
43
|
+
|
|
44
|
+
[dependence]
|
|
45
|
+
pip = []
|
|
46
|
+
mpm = []
|
|
47
|
+
|
|
48
|
+
[entry]
|
|
49
|
+
entry_cls = "MyPlugin"
|
|
50
|
+
entry_module = "my_plugin"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
再写入口:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
# plugins/my_plugin/__init__.py
|
|
57
|
+
from miaoli_plugin import BasePlugin
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class MyPlugin(BasePlugin):
|
|
61
|
+
|
|
62
|
+
async def onload(self) -> None:
|
|
63
|
+
print(f"{self.manifest.metadata.name} 已加载")
|
|
64
|
+
|
|
65
|
+
async def unload(self) -> None:
|
|
66
|
+
print(f"{self.manifest.metadata.name} 已卸载")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`onload()` / `unload()` 里可以放心用 `self.ctx` 和 `self.manifest`,框架在调用前已经挂好了。
|
|
70
|
+
|
|
71
|
+
### 加载
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
import asyncio
|
|
75
|
+
|
|
76
|
+
from miaoli_plugin import PluginLoader
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
loader = PluginLoader()
|
|
80
|
+
|
|
81
|
+
asyncio.run(loader.load_all([
|
|
82
|
+
{"enabled": True, "path": "plugins/my_plugin", "config": {}},
|
|
83
|
+
]))
|
|
84
|
+
|
|
85
|
+
for instance in loader.instances:
|
|
86
|
+
print(type(instance).__name__)
|
|
87
|
+
|
|
88
|
+
asyncio.run(loader.unload_all())
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`load_all()` 收的是 `PluginContext` 的原始字典,字段:`enabled` / `path` / `config`。
|
|
92
|
+
`path` 必须是**存在的目录**,加载时用 pydantic 的 `DirectoryPath` 校验。
|
|
93
|
+
|
|
94
|
+
## 加载语义
|
|
95
|
+
|
|
96
|
+
| 行为 | 说明 |
|
|
97
|
+
| --- | --- |
|
|
98
|
+
| 顺序 | 按 `dependence.mpm` 拓扑排序,**依赖在前** |
|
|
99
|
+
| 失败 | 打日志 + 清理 `sys.modules` 残留 + **跳过该插件**,不回滚已加载的 |
|
|
100
|
+
| 连锁失败 | 依赖了失败插件的插件照样尝试加载,通常也会失败 |
|
|
101
|
+
| 卸载 | `unload_all()` 按**加载顺序的逆序**,也就是反向拓扑序 |
|
|
102
|
+
| `instances` | 只读元组,顺序即加载顺序 |
|
|
103
|
+
| 重名 | 两个目录声明了同一个 `name` 直接抛 `PluginSameNameError`,不覆盖 |
|
|
104
|
+
|
|
105
|
+
`dependence.pip` 目前只是清单字段,**加载器不会替你装**;`dependence.mpm` 才会参与拓扑排序。
|
|
106
|
+
|
|
107
|
+
## 内容
|
|
108
|
+
|
|
109
|
+
| 模块 | 导出 |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `loader` | `PluginLoader` |
|
|
112
|
+
| `core` | `prepare_plugin`, `load_plugin`, `unload_plugin` |
|
|
113
|
+
| `protocols` | `BasePlugin` |
|
|
114
|
+
| `models` | `PluginContext`, `PluginMetadata`, `PluginDependence`, `PluginEntry`, `PluginManifest` |
|
|
115
|
+
| `runtimes` | `PluginRecord` |
|
|
116
|
+
| `errors` | `TopologyError`, `TopologyCircularError`, `TopologyMissingError`, `EntryPointNotFound`, `PluginSameNameError` |
|
|
117
|
+
| `utils` | `topology_sort`, `topology_once`, `missing_check`, `read_manifest`, `remove_package` |
|
|
118
|
+
|
|
119
|
+
`core` 里是**单个插件**的三个原语,`loader` 是**编排层**:把这三个动作对一批插件跑一遍。
|
|
120
|
+
|
|
121
|
+
## 结构
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
miaoli_plugin/
|
|
125
|
+
├── loader.py PluginLoader
|
|
126
|
+
├── core/
|
|
127
|
+
│ ├── prepare_plugin.py prepare_plugin
|
|
128
|
+
│ ├── load_plugin.py load_plugin
|
|
129
|
+
│ └── unload_plugin.py unload_plugin
|
|
130
|
+
├── protocols/
|
|
131
|
+
│ └── base_plugin.py BasePlugin
|
|
132
|
+
├── models/
|
|
133
|
+
│ ├── plugin_manifest.py PluginManifest
|
|
134
|
+
│ ├── plugin_metadata.py PluginMetadata
|
|
135
|
+
│ ├── plugin_dependence.py PluginDependence
|
|
136
|
+
│ ├── plugin_entry.py PluginEntry
|
|
137
|
+
│ └── plugin_context.py PluginContext
|
|
138
|
+
├── runtimes/
|
|
139
|
+
│ └── plugin_record.py PluginRecord
|
|
140
|
+
├── errors/
|
|
141
|
+
│ ├── topology_error/ 拓扑错误三件套
|
|
142
|
+
│ ├── entry_point_not_found.py
|
|
143
|
+
│ └── plugin_same_name.py
|
|
144
|
+
└── utils/
|
|
145
|
+
├── read_manifest.py read_manifest
|
|
146
|
+
├── topology_sort.py topology_sort
|
|
147
|
+
├── topology_once.py topology_once
|
|
148
|
+
├── missing_check.py missing_check
|
|
149
|
+
└── remove_package.py remove_package
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## 注意
|
|
153
|
+
|
|
154
|
+
- `manifest.toml` 必须是 UTF-8、**不能带 BOM**。TOML 规范要求 UTF-8 无 BOM,`tomllib` 遇到 BOM 会直接 `TOMLDecodeError`。
|
|
155
|
+
- 插件名会被直接当成 `sys.modules` 里的**顶层包名**用,别跟标准库重名(否则会遮住真的标准库)。
|
|
156
|
+
- 卸载时 `remove_package()` 会**无条件**清掉该名字在 `sys.modules` 里的所有条目,包括插件自己 import 的子模块。
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
miaoli_plugin/__init__.py
|
|
4
|
+
miaoli_plugin/loader.py
|
|
5
|
+
miaoli_plugin/py.typed
|
|
6
|
+
miaoli_plugin.egg-info/PKG-INFO
|
|
7
|
+
miaoli_plugin.egg-info/SOURCES.txt
|
|
8
|
+
miaoli_plugin.egg-info/dependency_links.txt
|
|
9
|
+
miaoli_plugin.egg-info/requires.txt
|
|
10
|
+
miaoli_plugin.egg-info/top_level.txt
|
|
11
|
+
miaoli_plugin/core/__init__.py
|
|
12
|
+
miaoli_plugin/core/load_plugin.py
|
|
13
|
+
miaoli_plugin/core/prepare_plugin.py
|
|
14
|
+
miaoli_plugin/core/unload_plugin.py
|
|
15
|
+
miaoli_plugin/errors/__init__.py
|
|
16
|
+
miaoli_plugin/errors/entry_point_not_found.py
|
|
17
|
+
miaoli_plugin/errors/plugin_same_name.py
|
|
18
|
+
miaoli_plugin/errors/topology_error/__init__.py
|
|
19
|
+
miaoli_plugin/errors/topology_error/base.py
|
|
20
|
+
miaoli_plugin/errors/topology_error/circular_error.py
|
|
21
|
+
miaoli_plugin/errors/topology_error/missing_error.py
|
|
22
|
+
miaoli_plugin/models/__init__.py
|
|
23
|
+
miaoli_plugin/models/plugin_context.py
|
|
24
|
+
miaoli_plugin/models/plugin_dependence.py
|
|
25
|
+
miaoli_plugin/models/plugin_entry.py
|
|
26
|
+
miaoli_plugin/models/plugin_manifest.py
|
|
27
|
+
miaoli_plugin/models/plugin_metadata.py
|
|
28
|
+
miaoli_plugin/protocols/__init__.py
|
|
29
|
+
miaoli_plugin/protocols/base_plugin.py
|
|
30
|
+
miaoli_plugin/runtimes/__init__.py
|
|
31
|
+
miaoli_plugin/runtimes/plugin_record.py
|
|
32
|
+
miaoli_plugin/utils/__init__.py
|
|
33
|
+
miaoli_plugin/utils/missing_check.py
|
|
34
|
+
miaoli_plugin/utils/read_manifest.py
|
|
35
|
+
miaoli_plugin/utils/remove_package.py
|
|
36
|
+
miaoli_plugin/utils/topology_once.py
|
|
37
|
+
miaoli_plugin/utils/topology_sort.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pydantic>=2.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
miaoli_plugin
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "miaoli-plugin"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "喵璃的插件加载器:按 manifest.toml 发现、拓扑排序并加载目录式插件"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "超·乃依" }]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3.12",
|
|
16
|
+
"Programming Language :: Python :: 3.13",
|
|
17
|
+
"Programming Language :: Python :: 3.14",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"pydantic>=2.0",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/lyt2011/miaoli_bot"
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.packages.find]
|
|
28
|
+
where = ["."]
|
|
29
|
+
include = ["miaoli_plugin*"]
|
|
30
|
+
namespaces = false
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.package-data]
|
|
33
|
+
miaoli_plugin = ["py.typed"]
|