Skip to content

Commit

Permalink
💥 use ~ to disable plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Dec 15, 2024
1 parent 26ddd5a commit 8b1b9bc
Show file tree
Hide file tree
Showing 10 changed files with 39 additions and 52 deletions.
2 changes: 1 addition & 1 deletion arclet/entari/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
plugins:
$prelude:
- ::auto_reload
~record_message: true
.record_message: true
::auto_reload:
watch_dirs: ["."]
::echo: true
Expand Down
23 changes: 7 additions & 16 deletions arclet/entari/builtins/auto_reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ def detect_filter_change(old: dict, new: dict):
if "$allow" in removed:
allow = {}
else:
allow = new["$allow"]
allow = new.get("$allow", {})
if "$deny" in removed:
deny = {}
else:
deny = new["$deny"]
deny = new.get("$deny", {})
return allow, deny, not ((added | removed | changed) - {"$allow", "$deny"})


Expand Down Expand Up @@ -122,13 +122,10 @@ async def watch_config(self):
logger("DEBUG", f"Basic config <y>{key!r}</y> appended")
await es.publish(ConfigReload("basic", key, EntariConfig.instance.basic[key]))
for plugin_name in old_plugin:
if plugin_name == "$prelude":
if plugin_name.startswith("$") or plugin_name.startswith("~"):
continue
pid = plugin_name.replace("::", "arclet.entari.builtins.")
if (
plugin_name not in EntariConfig.instance.plugin
or EntariConfig.instance.plugin[plugin_name] is False
):
if plugin_name not in EntariConfig.instance.plugin:
if plugin := find_plugin(pid):
await plugin._cleanup()
del plugin
Expand All @@ -141,14 +138,8 @@ async def watch_config(self):
f"Plugin <y>{plugin_name!r}</y> config changed from <r>{old_plugin[plugin_name]!r}</r> "
f"to <g>{EntariConfig.instance.plugin[plugin_name]!r}</g>",
)
if isinstance(old_plugin[plugin_name], bool):
old_conf = {}
else:
old_conf: dict = old_plugin[plugin_name] # type: ignore
if isinstance(EntariConfig.instance.plugin[plugin_name], bool):
new_conf = {}
else:
new_conf: dict = EntariConfig.instance.plugin[plugin_name] # type: ignore
old_conf = old_plugin[plugin_name]
new_conf = EntariConfig.instance.plugin[plugin_name]
if plugin := find_plugin(pid):
allow, deny, only_filter = detect_filter_change(old_conf, new_conf)
plugin.update_filter(allow, deny)
Expand Down Expand Up @@ -178,7 +169,7 @@ async def watch_config(self):
load_plugin(plugin_name, new_conf)
if new := (set(EntariConfig.instance.plugin) - set(old_plugin)):
for plugin_name in new:
if plugin_name == "$prelude":
if plugin_name.startswith("$") or plugin_name.startswith("~"):
continue
if not (plugin := load_plugin(plugin_name)):
continue
Expand Down
2 changes: 1 addition & 1 deletion arclet/entari/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def _(plg: RootlessPlugin):
def update(event: ConfigReload):
if event.scope != "plugin":
return
if event.key != "~commands":
if event.key != ".commands":
return
if "need_notice_me" in event.value:
_commands.judge.need_notice_me = event.value["need_notice_me"]
Expand Down
4 changes: 2 additions & 2 deletions arclet/entari/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class BasicConfig(TypedDict, total=False):
class EntariConfig:
path: Path
basic: BasicConfig = field(default_factory=dict, init=False) # type: ignore
plugin: dict[str, dict | bool] = field(default_factory=dict, init=False)
plugin: dict[str, dict] = field(default_factory=dict, init=False)
prelude_plugin: list[str] = field(default_factory=list, init=False)
updater: Callable[[EntariConfig], None]

Expand All @@ -30,7 +30,7 @@ def __post_init__(self):

def reload(self):
self.updater(self)
self.plugin.setdefault("~commands", True)
self.plugin.setdefault(".commands", {})
self.prelude_plugin = self.plugin.pop("$prelude", []) # type: ignore

@classmethod
Expand Down
7 changes: 5 additions & 2 deletions arclet/entari/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,11 @@ def __init__(
requires(*EntariConfig.instance.prelude_plugin)
for plug in EntariConfig.instance.prelude_plugin:
load_plugin(plug, prelude=True)
requires(*EntariConfig.instance.plugin)
for plug in EntariConfig.instance.plugin:
plugins = [
plug for plug in EntariConfig.instance.plugin if not plug.startswith("~") or not plug.startswith("$")
]
requires(*plugins)
for plug in plugins:
load_plugin(plug)
self.ignore_self_message = ignore_self_message
self.register(self.handle_event)
Expand Down
19 changes: 8 additions & 11 deletions arclet/entari/plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ def load_plugin(
prelude (bool): 是否为前置插件
"""
if config is None:
_config = EntariConfig.instance.plugin.get(path)
if isinstance(_config, dict):
config = _config.copy()
elif _config is False:
return
config = EntariConfig.instance.plugin.get(path)
conf = config or {}
if "$static" in conf:
del conf["$static"]
conf = conf.copy()
if prelude:
conf["$static"] = True
if recursive_guard is None:
recursive_guard = set()
path = path.replace("::", "arclet.entari.builtins.")
Expand All @@ -52,13 +54,8 @@ def load_plugin(
if path in plugin_service.plugins:
return plugin_service.plugins[path]
if path in plugin_service._apply:
return plugin_service._apply[path](config or {})
return plugin_service._apply[path](conf)
try:
conf = config or {}
if "$static" in conf:
del conf["$static"]
if prelude:
conf["$static"] = True
mod = import_plugin(path, config=conf)
if not mod:
log.plugin.opt(colors=True).error(f"cannot found plugin <blue>{path!r}</blue>")
Expand Down
4 changes: 2 additions & 2 deletions arclet/entari/plugin/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,8 +333,8 @@ def apply(cls, id: str, func: Callable[[RootlessPlugin], Any]) -> Callable[[], N

@classmethod
def apply(cls, id: str, func: Callable[[RootlessPlugin], Any] | None = None) -> Any:
if not id.startswith("~"):
id = f"~{id}"
if not id.startswith("."):
id = f".{id}"

def dispose():
if id in plugin_service.plugins:
Expand Down
7 changes: 4 additions & 3 deletions arclet/entari/plugin/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ def __entari_import__(name: str, plugin_name: str, ensure_plugin: bool = False):
return mod.__plugin__.proxy()
return __import__(name, fromlist=["__path__"])
if name in EntariConfig.instance.plugin:
if EntariConfig.instance.plugin[name] is False:
raise ImportError(f"plugin {name!r} is disabled")
mod = import_plugin(name)
config = EntariConfig.instance.plugin[name]
if "$static" in config:
del config["$static"]
mod = import_plugin(name, config=config)
if mod:
log.plugin.opt(colors=True).success(f"loaded plugin <blue>{name!r}</blue>")
if plugin_name != mod.__plugin__.id:
Expand Down
8 changes: 4 additions & 4 deletions example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ basic:
plugins:
::auto_reload:
watch_dirs: ["."]
::echo: true
example_plugin: true
~record_message: true
~scheduler: true
::echo: {}
example_plugin: {}
.record_message: {}
.scheduler: {}
15 changes: 5 additions & 10 deletions example_plugin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import re
import sys
from arclet.entari import (
Session,
Expand Down Expand Up @@ -29,22 +28,18 @@ async def cleanup():
print("example: Cleanup")


disp_message = plug.dispatch(MessageCreatedEvent)


@disp_message
@plug.dispatch(MessageCreatedEvent)
@Filter().public().bind
async def _(msg: MessageChain, session: Session):
content = msg.extract_plain_text()
if re.match(r"(.{0,3})(上传|设定)(.{0,3})(上传|设定)(.{0,3})", content):
return await session.send("上传设定的帮助是...")
if content == "test":
async def _(session: Session):
if session.content == "test":
resp = await session.send("This message will recall in 5s...")

@scheduler.invoke(5)
async def _():
await session.message_delete(resp[0].id)

disp_message = plug.dispatch(MessageCreatedEvent)


@disp_message.on(auxiliaries=[Filter().public().to_me().and_(lambda sess: str(sess.content) == "aaa")])
async def _(session: Session):
Expand Down

0 comments on commit 8b1b9bc

Please sign in to comment.