Skip to content

Commit

Permalink
✨ initial config
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Nov 1, 2024
1 parent f471d1c commit b47e723
Show file tree
Hide file tree
Showing 8 changed files with 131 additions and 3 deletions.
1 change: 1 addition & 0 deletions arclet/entari/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from satori.config import WebhookInfo as WebhookInfo
from satori.config import WebsocketsInfo as WebsocketsInfo

from .config import load_config as load_config
from .core import Entari as Entari
from .event import MessageCreatedEvent as MessageCreatedEvent
from .event import MessageEvent as MessageEvent
Expand Down
62 changes: 62 additions & 0 deletions arclet/entari/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from __future__ import annotations

import os
import json
from pathlib import Path
from dataclasses import dataclass, field
from typing import Callable, ClassVar


@dataclass
class Config:
path: Path
basic: dict = field(default_factory=dict, init=False)
plugin: dict[str, dict] = field(default_factory=dict, init=False)
updater: Callable[["Config"], None]

instance: ClassVar[Config]

def __post_init__(self):
self.updater(self)

def reload(self):
self.updater(self)

@classmethod
def load(cls, path: str | os.PathLike[str] | None = None) -> Config:
if path is None:
_path = Path.cwd() / ".entari.json"
else:
_path = Path(path)
if not _path.exists():
return cls(_path, lambda _: None)
if not _path.is_file():
raise ValueError(f"{_path} is not a file")
if _path.suffix.startswith(".json"):

def _updater(self: Config):
with self.path.open("r", encoding="utf-8") as f:
data = json.load(f)
self.basic = data.get("basic", {})
self.plugin = data.get("plugin", {})
obj = cls(_path, _updater)
cls.instance = obj
return obj
if _path.suffix in (".yaml", ".yml"):
try:
import yaml
except ImportError:
raise RuntimeError("yaml is not installed")

def _updater(self: Config):
with self.path.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f)
self.basic = data.get("basic", {})
self.plugin = data.get("plugin", {})
obj = cls(_path, _updater)
cls.instance = obj
return obj
raise NotImplementedError(f"unsupported config file format: {_path.suffix}")


load_config = Config.load
3 changes: 3 additions & 0 deletions arclet/entari/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from satori.model import Event
from tarina.generic import get_origin

from .config import Config as EntariConfig
from .command import _commands
from .event import MessageCreatedEvent, event_parse
from .plugin.service import plugin_service
Expand Down Expand Up @@ -43,6 +44,8 @@ class Entari(App):

def __init__(self, *configs: Config, ignore_self_message: bool = True):
super().__init__(*configs)
if "ignore_self_message" in EntariConfig.instance.basic:
ignore_self_message = EntariConfig.instance.basic["ignore_self_message"]
self.ignore_self_message = ignore_self_message
self.event_system = EventSystem()
self.event_system.register(_commands.publisher)
Expand Down
3 changes: 2 additions & 1 deletion arclet/entari/plugin/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from .model import Plugin, PluginMetadata, _current_plugin
from .service import plugin_service
from ..config import Config

_SUBMODULE_WAITLIST: dict[str, set[str]] = {}
_ENSURE_IS_PLUGIN: set[str] = set()
Expand Down Expand Up @@ -209,7 +210,7 @@ def exec_module(self, module: ModuleType, config: Optional[dict[str, str]] = Non
return

# create plugin before executing
plugin = Plugin(module.__name__, module, config=config or {})
plugin = Plugin(module.__name__, module, config=config or Config.instance.plugin.get(module.__name__, {}))
# for `dataclasses` module
sys.modules[module.__name__] = plugin.proxy() # type: ignore
setattr(module, "__plugin__", plugin)
Expand Down
5 changes: 5 additions & 0 deletions example.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
basic:
ignore_self_message: true
plugins:
::auto_reload:
watch_dirs: ["."]
3 changes: 2 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from satori import Image

from arclet.entari import Session, Entari, command, WebsocketsInfo, load_plugin, dispose_plugin
from arclet.entari import Session, Entari, command, WebsocketsInfo, load_plugin, dispose_plugin, load_config


@command.on("echoimg {img}")
async def echoimg(img: Image, session: Session):
await session.send_message([img])


load_config("example.yml")
load_plugin("::auto_reload")
load_plugin("example_plugin")

Expand Down
56 changes: 55 additions & 1 deletion pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ dev = [
"ruff>=0.4.2",
"fix-future-annotations>=0.5.0",
"watchfiles>=0.24.0",
"pyyaml>=6.0.2",
]
[tool.black]
line-length = 120
Expand Down

0 comments on commit b47e723

Please sign in to comment.