Skip to content

Commit

Permalink
💥 upgrade letoderea to 0.15.0 (#10)
Browse files Browse the repository at this point in the history
* 💥 upgrade letoderea to 0.15.0

* 🍻 sync
(cherry-pick commit:865c8c039bb97d6dbed2745d7a3052d584955762)

* 🐛 fix logger

* 🍻 filter use propagator & depends

* 🐛 fix logger.opt

* ✨ filter shortcut

* 🍻 revert _Filter
  • Loading branch information
RF-Tar-Railt authored Jan 27, 2025
1 parent 4e3dbfe commit 5658dab
Show file tree
Hide file tree
Showing 19 changed files with 329 additions and 560 deletions.
2 changes: 1 addition & 1 deletion arclet/entari/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from arclet.letoderea import bind as bind
from arclet.letoderea import propagate as propagate
from satori import ArgvInteraction as ArgvInteraction
from satori import At as At
from satori import Audio as Audio
Expand Down Expand Up @@ -45,7 +46,6 @@
from .core import Entari as Entari
from .event import MessageCreatedEvent as MessageCreatedEvent
from .event import MessageEvent as MessageEvent
from .filter import Filter as Filter
from .filter import filter_ as filter_
from .message import MessageChain as MessageChain
from .plugin import Plugin as Plugin
Expand Down
40 changes: 12 additions & 28 deletions arclet/entari/builtins/auto_reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,7 @@ def detect_filter_change(old: dict, new: dict):
added = set(new) - set(old)
removed = set(old) - set(new)
changed = {key for key in set(new) & set(old) if new[key] != old[key]}
if "$allow" in removed:
allow = {}
else:
allow = new.get("$allow", {})
if "$deny" in removed:
deny = {}
else:
deny = new.get("$deny", {})
return allow, deny, not ((added | removed | changed) - {"$allow", "$deny"})
return "allow" in (added | removed | changed) or "$deny" in (added | removed | changed)


class Watcher(Service):
Expand Down Expand Up @@ -86,9 +78,7 @@ async def watch(self):
logger.error(f"Failed to reload <blue>{pid!r}</blue>")
self.fail[change[1]] = pid
elif change[1] in self.fail:
logger.info(
f"Detected change in {change[1]!r} which failed to reload, retrying..."
)
logger.info(f"Detected change in {change[1]!r} which failed to reload, retrying...")
if plugin := load_plugin(self.fail[change[1]]):
logger.info(f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
Expand All @@ -108,7 +98,6 @@ async def watch_config(self):
or Path(change[1]).resolve() in extra
or Path(change[1]).resolve().parent in extra
):
print(change)
continue
logger.info(f"Detected change in {change[1]!r}, reloading config...")

Expand Down Expand Up @@ -143,22 +132,17 @@ async def watch_config(self):
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)
if only_filter:
logger.debug(f"Plugin <y>{pid!r}</y> config only changed filter.")
continue
res = await es.post(
ConfigReload("plugin", plugin_name, new_conf, old_conf),
)
if res and res.value:
logger.debug(f"Plugin <y>{pid!r}</y> config change handled by itself.")
continue
logger.info(
f"Detected config of <blue>{pid!r}</blue> changed, reloading..."
)
filter_changed = detect_filter_change(old_conf, new_conf)
if not filter_changed:
res = await es.post(
ConfigReload("plugin", plugin_name, new_conf, old_conf),
)
if res and res.value:
logger.debug(f"Plugin <y>{pid!r}</y> config change handled by itself.")
continue
logger.info(f"Detected config of <blue>{pid!r}</blue> changed, reloading...")
plugin_file = str(plugin.module.__file__)
unload_plugin(plugin_name)
unload_plugin(pid)
if plugin := load_plugin(plugin_name, new_conf):
logger.info(f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
Expand Down
30 changes: 15 additions & 15 deletions arclet/entari/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from arclet.alconna import Alconna, Arg, Args, CommandMeta, Namespace, command_manager, config
from arclet.alconna.tools.construct import AlconnaString, alconna_from_format
from arclet.alconna.typing import TAValue
from arclet.letoderea import BaseAuxiliary, Provider, Scope, Subscriber, es
from arclet.letoderea import Provider, Scope, Subscriber, es
from arclet.letoderea.handler import generate_contexts
from arclet.letoderea.provider import ProviderFactory, get_providers
from arclet.letoderea.typing import Contexts, TTarget
Expand All @@ -28,7 +28,9 @@


def get_cmd(target: Subscriber):
return next(a for a in target.auxiliaries["prepare"] if isinstance(a, AlconnaSuppiler)).cmd
if sub := target.get_propagator(AlconnaSuppiler.supply):
return sub.callable_target.__self__.cmd # type: ignore
raise ValueError("Subscriber has no command.")


class EntariCommands:
Expand Down Expand Up @@ -104,28 +106,25 @@ def command(
self,
command: str,
help_text: Optional[str] = None,
auxiliaries: Optional[list[BaseAuxiliary]] = None,
providers: Optional[list[Union[Provider, type[Provider], ProviderFactory, type[ProviderFactory]]]] = None,
):
class Command(AlconnaString):
def __call__(_cmd_self, func: TTarget[Optional[TM]]) -> Subscriber[Optional[TM]]:
return self.on(_cmd_self.build(), auxiliaries, providers)(func)
return self.on(_cmd_self.build(), providers)(func)

return Command(command, help_text)

@overload
def on(
self,
command: Alconna,
auxiliaries: Optional[list[BaseAuxiliary]] = None,
providers: Optional[list[Union[Provider, type[Provider], ProviderFactory, type[ProviderFactory]]]] = None,
) -> Callable[[TTarget[Optional[TM]]], Subscriber[Optional[TM]]]: ...

@overload
def on(
self,
command: str,
auxiliaries: Optional[list[BaseAuxiliary]] = None,
providers: Optional[list[Union[Provider, type[Provider], ProviderFactory, type[ProviderFactory]]]] = None,
*,
args: Optional[dict[str, Union[TAValue, Args, Arg]]] = None,
Expand All @@ -135,15 +134,12 @@ def on(
def on(
self,
command: Union[Alconna, str],
auxiliaries: Optional[list[BaseAuxiliary]] = None,
providers: Optional[list[Union[Provider, type[Provider], ProviderFactory, type[ProviderFactory]]]] = None,
*,
args: Optional[dict[str, Union[TAValue, Args, Arg]]] = None,
meta: Optional[CommandMeta] = None,
) -> Callable[[TTarget[Optional[TM]]], Subscriber[Optional[TM]]]:
auxiliaries = auxiliaries or []
if plg := _current_plugin.get():
auxiliaries.extend(plg._scope.auxiliaries)
plg = _current_plugin.get()
providers = providers or []

def wrapper(func: TTarget[Optional[TM]]) -> Subscriber[Optional[TM]]:
Expand All @@ -155,8 +151,10 @@ def wrapper(func: TTarget[Optional[TM]]) -> Subscriber[Optional[TM]]:
key = _command.name + "".join(
f" {arg.value.target}" for arg in _command.args if isinstance(arg.value, DirectPattern)
)
auxiliaries.append(AlconnaSuppiler(_command))
target = self.scope.register(func, auxiliaries=auxiliaries, providers=providers)
target = self.scope.register(func, providers=providers)
target.propagate(AlconnaSuppiler(_command))
if plg:
target.propagates(*plg._scope.propagators)
self.trie[key] = target.id

def _remove(_):
Expand All @@ -175,7 +173,6 @@ def _remove(_):
if not isinstance(command.command, str):
raise TypeError("Command name must be a string.")
_command.reset_namespace(self.__namespace__)
auxiliaries.insert(0, AlconnaSuppiler(_command))
keys = []
if not _command.prefixes:
keys.append(_command.command)
Expand All @@ -185,7 +182,10 @@ def _remove(_):
for prefix in cast(list[str], _command.prefixes):
keys.append(prefix + _command.command)

target = self.scope.register(func, auxiliaries=auxiliaries, providers=providers)
target = self.scope.register(func, providers=providers)
target.propagate(AlconnaSuppiler(_command))
if plg:
target.propagates(*plg._scope.propagators)

for _key in keys:
self.trie[_key] = target.id
Expand Down Expand Up @@ -234,7 +234,7 @@ def _(plg: RootlessPlugin):
if "use_config_prefix" in plg.config:
_commands.judge.use_config_prefix = plg.config["use_config_prefix"]

plg.dispatch(MessageCreatedEvent).handle(_commands.handle, auxiliaries=[_commands.judge])
plg.dispatch(MessageCreatedEvent).handle(_commands.handle).propagate(_commands.judge)

@plg.use(ConfigReload)
def update(event: ConfigReload):
Expand Down
30 changes: 17 additions & 13 deletions arclet/entari/command/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Any

from arclet.alconna import Alconna, command_manager
from arclet.letoderea import BaseAuxiliary, Provider, ProviderFactory, es
from arclet.letoderea import Provider, ProviderFactory, es

from ..event import MessageCreatedEvent
from ..event.command import CommandExecute
Expand All @@ -28,10 +28,10 @@ def __init__(
plugin._extra.setdefault("commands", []).append((command.prefixes, command.command))
self.supplier = AlconnaSuppiler(command)
super().__init__(plugin, MessageCreatedEvent, command.path)
self.auxiliaries.append(
self.propagators.append(
MessageJudges(need_reply_me, need_notice_me, use_config_prefix),
)
self.auxiliaries.append(self.supplier)
self.propagators.append(self.supplier)
self.providers.append(AlconnaProviderFactory())

@plugin.collect
Expand All @@ -46,24 +46,28 @@ def assign(
value: Any = _seminal,
or_not: bool = False,
priority: int = 16,
auxiliaries: list[BaseAuxiliary] | None = None,
providers: list[Provider | type[Provider] | ProviderFactory | type[ProviderFactory]] | None = None,
):
_auxiliaries = auxiliaries or []
_auxiliaries.append(Assign(path, value, or_not))
return self.register(priority=priority, auxiliaries=_auxiliaries, providers=providers)
assign = Assign(path, value, or_not)
try:
self.propagators.append(assign)
return self.register(priority=priority, providers=providers)
finally:
self.propagators.remove(assign)

def on_execute(
self,
priority: int = 16,
auxiliaries: list[BaseAuxiliary] | None = None,
providers: list[Provider | type[Provider] | ProviderFactory | type[ProviderFactory]] | None = None,
):
_auxiliaries = auxiliaries or []
_auxiliaries.append(self.supplier)
return self.plugin._scope.register(
priority=priority, auxiliaries=_auxiliaries, providers=providers, publisher=exec_pub
)
wrapper = self.plugin._scope.register(priority=priority, providers=providers, publisher=exec_pub)

def decorator(func):
sub = wrapper(func)
sub.propagate(self.supplier)
return sub

return decorator

Match = Match
Query = Query
Expand Down
Loading

0 comments on commit 5658dab

Please sign in to comment.