22import os
33import re
44import warnings
5+ from collections import defaultdict
56from collections .abc import Callable , MutableMapping
67from dataclasses import dataclass , field
78from importlib import import_module
89from io import StringIO
10+ from itertools import chain
911from pathlib import Path
1012from typing import TYPE_CHECKING , Any , ClassVar , TypeVar
1113
@@ -43,14 +45,17 @@ class EntariConfig:
4345 path : Path
4446 basic : BasicConfig = field (default_factory = BasicConfig , init = False )
4547 plugin : dict [str , dict ] = field (default_factory = dict , init = False )
48+ plugin_prefixes : dict [str , list [str ]] = field (default_factory = dict , init = False )
4649 prelude_plugin : list [str ] = field (default_factory = list , init = False )
4750 plugin_extra_files : list [str ] = field (default_factory = list , init = False )
4851 save_flag : bool = field (default = False )
4952 env_vars : dict [str , str ] = field (default_factory = dict )
53+ _plugin_names : dict [str , list [str ]] = field (default_factory = dict , init = False )
5054 _origin_data : dict [str , Any ] = field (init = False )
5155 _env_replaced : dict [str , dict [int , tuple [str , int ]]] = field (default_factory = dict , init = False )
5256
5357 instance : ClassVar ["EntariConfig" ]
58+ _inited : ClassVar [bool ] = False
5459
5560 def loader (self , path : Path ):
5661 if not path .exists ():
@@ -103,6 +108,7 @@ def dumper(self, path: Path, save_path: Path, data: dict, indent: int, apply_sch
103108
104109 def __post_init__ (self ):
105110 self .__class__ .instance = self
111+ self .__class__ ._inited = True
106112 self .reload ()
107113
108114 @property
@@ -111,21 +117,26 @@ def data(self) -> dict[str, Any]:
111117
112118 @property
113119 def prelude_plugin_names (self ) -> list [str ]:
114- return [name for name in self .plugin_names if name in self .prelude_plugin ]
120+ return [
121+ name
122+ for key , names in self ._plugin_names .items ()
123+ for name in names
124+ if key in self .prelude_plugin or name in self .prelude_plugin
125+ ]
115126
116127 @property
117128 def plugin_names (self ) -> list [str ]:
118- slots = [
119- (name , self .plugin [name ].get ("$priority" , 16 ))
120- for name in self .plugin
121- if not name .startswith ("$" ) and not self .plugin [name ].get ("$optional" , False )
122- ]
123- slots .sort (key = lambda x : x [1 ])
124- return [name for name , _ in slots ]
129+ return list (chain .from_iterable (self ._plugin_names .values ()))
125130
126131 def _reload_plugins (self ):
127132 self .plugin_extra_files : list [str ] = self .plugin .get ("$files" , []) # type: ignore
128133 self .prelude_plugin = self .plugin .get ("$prelude" , []) # type: ignore
134+ plugin_prefixes = {item ["key" ]: item ["plugins" ] for item in self .plugin .get ("$prefix" , [])} # type: ignore
135+ inverted = defaultdict (list )
136+ for key , plugs in plugin_prefixes .items ():
137+ for plug in plugs :
138+ inverted [plug ].append (key )
139+ self .plugin_prefixes = dict (inverted )
129140 for key in list (self .plugin .keys ()):
130141 if key .startswith ("$" ):
131142 continue
@@ -150,6 +161,22 @@ def _reload_plugins(self):
150161 elif path .name .endswith (".schema.json" ):
151162 self .plugin [path .stem ] = self .loader (path )
152163
164+ slots = [
165+ (name , self .plugin [name ].get ("$priority" , 16 ))
166+ for name in self .plugin
167+ if not name .startswith ("$" ) and not self .plugin [name ].get ("$optional" , False )
168+ ]
169+ slots .sort (key = lambda x : x [1 ])
170+ ans : defaultdict [str , list [str ]] = defaultdict (list )
171+ for name , _ in slots :
172+ if (prefixes := self .plugin_prefixes .get (name )) is not None :
173+ ans [name ].extend ((f"{ prefix } { name } " if prefix else name ) for prefix in prefixes )
174+ elif name .count ("." ) or name .startswith ("::" ) or name .startswith ("entari_plugin_" ):
175+ ans [name ].append (name )
176+ else :
177+ ans [name ].append (f"entari_plugin_{ name } " )
178+ self ._plugin_names = dict (ans )
179+
153180 def reload (self ):
154181 if self .save_flag :
155182 self .save_flag = False
@@ -242,7 +269,11 @@ def bind(self, key: str, plugin: dict, obj: T) -> T:
242269 Bind the plugin object to the config, allowing the config to be updated when the object changes.
243270 """
244271 if key not in self .plugin :
245- raise KeyError (f"Plugin Config { key } not found in config" )
272+ for _ , names in self ._plugin_names .items ():
273+ if key in names :
274+ break
275+ else :
276+ raise KeyError (f"Plugin Config { key } not found in config" )
246277
247278 def updater (target ):
248279 nest_dict_update (plugin , config_model_dump (target ))
@@ -256,7 +287,7 @@ def updater(target):
256287 def generate_schema (self , plugins : list ["Plugin" ]):
257288 plugins_properties = {}
258289 # fmt: off
259- plugin_meta_properties = {"$disable" : {"type" : "string" , "description" : "Expression for whether disable this plugin" }, "$prefix" : { "type" : "string" , "description" : "Plugin name prefix" }, "$ priority" : {"type" : "integer" , "description" : "Plugin loading priority, lower value means higher priority (default: 16)" }, "$filter" : {"type" : "string" , "description" : "Plugin filter expression, which will be evaluated in the context of the plugin" }} # noqa: E501
290+ plugin_meta_properties = {"$disable" : {"type" : "string" , "description" : "Expression for whether disable this plugin" }, "$priority" : {"type" : "integer" , "description" : "Plugin loading priority, lower value means higher priority (default: 16)" }, "$filter" : {"type" : "string" , "description" : "Plugin filter expression, which will be evaluated in the context of the plugin" }} # noqa: E501
260291 # Build a mapping from plugin config key to plugin object for $files schema generation
261292 plugin_map : dict [str , "Plugin" ] = {} # noqa: UP037
262293 for plug in plugins :
@@ -271,7 +302,7 @@ def generate_schema(self, plugins: list["Plugin"]):
271302 else :
272303 plugins_properties [plug ._config_key ] = {"type" : "object" , "description" : "No configuration required" , "additionalProperties" : True , "properties" : plugin_meta_properties } # noqa: E501
273304 schemas = {
274- "basic" : config_model_schema (BasicConfig , ref_root = "/properties/basic/" ), "plugins" : {"type" : "object" , "description" : "Plugin configurations" , "properties" : {"$prelude" : {"type" : "array" , "items" : {"type" : "string" , "description" : "Plugin name" }, "description" : "List of prelude plugins to load" , "default" : [], "uniqueItems" : True }, "$files" : {"type" : "array" , "items" : {"type" : "string" , "description" : "File path" }, "description" : "List of configuration files to load" , "default" : [], "uniqueItems" : True }, ** plugins_properties }}, "adapters" : {"type" : "array" , "description" : "Adapter configurations" , "items" : {"type" : "object" , "description" : "Adapter configuration" , "properties" : {"$path" : {"type" : "string" , "description" : "Adapter Module Path" }}, "required" : ["$path" ], "additionalProperties" : True }} # noqa: E501
305+ "basic" : config_model_schema (BasicConfig , ref_root = "/properties/basic/" ), "plugins" : {"type" : "object" , "description" : "Plugin configurations" , "properties" : {"$prefix" : {"description" : "List of prefix config" , "items" : {"properties" : {"key" : {"description" : "Prefix key" , "title" : "Key" , "type" : "string" }, "plugins" : {"description" : "List of plugins under the prefix" , "items" : {"type" : "string" , "description" : "Plugin name" }, "title" : "Plugins" , "type" : "array" , "uniqueItems" : True }}, "required" : ["key" ], "title" : "Prefix Config" , "type" : "object" }, "type" : "array" }, "$prelude" : {"type" : "array" , "items" : {"type" : "string" , "description" : "Plugin name" }, "description" : "List of prelude plugins to load" , "default" : [], "uniqueItems" : True }, "$files" : {"type" : "array" , "items" : {"type" : "string" , "description" : "File path" }, "description" : "List of configuration files to load" , "default" : [], "uniqueItems" : True }, ** plugins_properties }}, "adapters" : {"type" : "array" , "description" : "Adapter configurations" , "items" : {"type" : "object" , "description" : "Adapter configuration" , "properties" : {"$path" : {"type" : "string" , "description" : "Adapter Module Path" }}, "required" : ["$path" ], "additionalProperties" : True }} # noqa: E501
275306 }
276307 with open (f"{ self .path .stem } .schema.json" , "w" , encoding = "utf-8" ) as f :
277308 json .dump ({"$schema" : "https://json-schema.org/draft/2020-12/schema" , "type" : "object" , "properties" : schemas , "additionalProperties" : False , "required" : ["basic" ]}, f , indent = 2 , ensure_ascii = False ) # noqa: E501
0 commit comments