From a5f3f08f9ae4465b723ed827c72dada74fdb473c Mon Sep 17 00:00:00 2001 From: 苏向夜 Date: Tue, 5 Dec 2023 15:05:17 +0800 Subject: :rocket: 优化抽象基类 修复部分声明异常 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hydrorollcore/__init__.py | 2 +- src/hydrorollcore/cli.py | 13 +++++++------ src/hydrorollcore/config.py | 1 - src/hydrorollcore/core.py | 13 ++++++++----- src/hydrorollcore/exceptions.py | 8 ++++++-- src/hydrorollcore/log.py | 5 +++-- src/hydrorollcore/rule.py | 12 ++++-------- src/hydrorollcore/typing.py | 9 ++++++++- 8 files changed, 37 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/hydrorollcore/__init__.py b/src/hydrorollcore/__init__.py index 93c042eb..f0a096fd 100644 --- a/src/hydrorollcore/__init__.py +++ b/src/hydrorollcore/__init__.py @@ -3,4 +3,4 @@ from HydroRollCore.config import Config from HydroRollCore.rule import Rule from HydroRollCore.core import Core -__all__ = ['Core', 'Rule', 'Config', 'Cli'] +__all__ = ["Core", "Rule", "Config", "Cli"] diff --git a/src/hydrorollcore/cli.py b/src/hydrorollcore/cli.py index d9d34ef2..8ce0fd9e 100644 --- a/src/hydrorollcore/cli.py +++ b/src/hydrorollcore/cli.py @@ -1,21 +1,22 @@ import argparse from tkinter import messagebox + class Cli: - def parse_args(): + def parse_args(self): # 创建解析器对象 - parser = argparse.ArgumentParser(description='HydroRoll 命令行工具') + parser = argparse.ArgumentParser(description="HydroRoll 命令行工具") # 添加命令行参数 - parser.add_argument('--gui', action='store_true', help='显示弹窗') - parser.add_argument('--path', help='指定路径') + parser.add_argument("--gui", action="store_true", help="显示弹窗") + parser.add_argument("--path", help="指定路径") # 解析命令行参数 args = parser.parse_args() # 处理命令行参数 if args.gui: - messagebox.showinfo('提示', '这是一个弹窗!') + messagebox.showinfo("提示", "这是一个弹窗!") if args.path: - print('输入的路径:', args.path) \ No newline at end of file + print("输入的路径:", args.path) diff --git a/src/hydrorollcore/config.py b/src/hydrorollcore/config.py index c7697d15..b76f4b2c 100644 --- a/src/hydrorollcore/config.py +++ b/src/hydrorollcore/config.py @@ -4,4 +4,3 @@ from pydantic import BaseModel class Config(BaseModel): rule_dir: list = [] rules: list = [] - diff --git a/src/hydrorollcore/core.py b/src/hydrorollcore/core.py index 56ec9404..6f6bbcc1 100644 --- a/src/hydrorollcore/core.py +++ b/src/hydrorollcore/core.py @@ -2,24 +2,27 @@ import importlib from typing import List from .exceptions import RuleLoadError from .rule import Rule +from .config import Config class Core: - def __init__(self, config): + def __init__(self, config: Config): self.rule_dir = config.rule_dir self.rules = config.rules - async def load_rules(self) -> List[Rule]: + def load_rules(self) -> List[Rule]: loaded_rules = [] for rule in self.rules: try: module = importlib.import_module(rule) except ImportError as e: - raise RuleLoadError(f'Failed to load rule {rule}: {e}') from e + raise RuleLoadError(f"Failed to load rule {rule}: {e}") from e try: - rule_cls = getattr(module, rule.split('.')[-1]) + rule_cls = getattr(module, rule.split(".")[-1]) if not issubclass(rule_cls, Rule): - raise RuleLoadError(f"Class '{rule_cls.__name__}' is not a subclass of 'Rule'") + raise RuleLoadError( + f"Class '{rule_cls.__name__}' is not a subclass of 'Rule'" + ) except AttributeError as e: raise RuleLoadError( f"Failed to get rule class from module '{rule}': {e}" diff --git a/src/hydrorollcore/exceptions.py b/src/hydrorollcore/exceptions.py index a7cf2c0b..62c88fa1 100644 --- a/src/hydrorollcore/exceptions.py +++ b/src/hydrorollcore/exceptions.py @@ -1,2 +1,6 @@ -class RuleLoadError(Exception): - pass +class HydroError(Exception): + """HydroRoll 异常基类""" + + +class RuleLoadError(HydroError): + """规则导入错误""" diff --git a/src/hydrorollcore/log.py b/src/hydrorollcore/log.py index 19073fc3..3eb07e7a 100644 --- a/src/hydrorollcore/log.py +++ b/src/hydrorollcore/log.py @@ -9,8 +9,9 @@ from datetime import datetime from loguru import logger as _logger -logger = _logger +__all__ = ["logger", "error_or_exception"] +logger = _logger current_path = os.path.dirname(os.path.abspath("__file__")) log_path = os.path.join( current_path, "logs", datetime.now().strftime("%Y-%m-%d") + ".log" @@ -27,4 +28,4 @@ def error_or_exception(message: str, exception: Exception, verbose: bool): if verbose: logger.exception(message) else: - logger.critical(f"{message} {exception!r}") \ No newline at end of file + logger.critical(f"{message} {exception!r}") diff --git a/src/hydrorollcore/rule.py b/src/hydrorollcore/rule.py index eb4b92cd..a7e5d9a7 100644 --- a/src/hydrorollcore/rule.py +++ b/src/hydrorollcore/rule.py @@ -14,16 +14,12 @@ class RuleLoadType(Enum): class Rule(metaclass=ABCMeta): + """规则基类""" + @abstractmethod def __init__(self): - pass - - @classmethod - def __subclasshook__(cls, other): - if cls is Rule: - return hasattr(other, "run") and callable(getattr(other, "run")) - return NotImplemented + raise NotImplementedError @abstractmethod async def run(self): - pass + raise NotImplementedError diff --git a/src/hydrorollcore/typing.py b/src/hydrorollcore/typing.py index ca6a7e65..d22e3e18 100644 --- a/src/hydrorollcore/typing.py +++ b/src/hydrorollcore/typing.py @@ -1,5 +1,12 @@ from pydantic import BaseModel -from typing import TYPE_CHECKING, TypeVar, Callable, NoReturn, Awaitable +from typing import ( + TYPE_CHECKING as TYPE_CHECKING, + TypeVar as TypeVar, + Callable as Callable, + NoReturn as NoReturn, + Awaitable as Awaitable, +) + class Config(BaseModel): rule_dir: list = [] -- cgit v1.2.3-70-g09d2 From d3076462c53afc848622052611a2ed7c241434e9 Mon Sep 17 00:00:00 2001 From: 苏向夜 Date: Tue, 5 Dec 2023 15:20:12 +0800 Subject: :sparkles: 依照文档增加Rule基类参数 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hydrorollcore/rule.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/hydrorollcore/rule.py b/src/hydrorollcore/rule.py index a7e5d9a7..a1b07cb9 100644 --- a/src/hydrorollcore/rule.py +++ b/src/hydrorollcore/rule.py @@ -16,6 +16,9 @@ class RuleLoadType(Enum): class Rule(metaclass=ABCMeta): """规则基类""" + name: str + priority: int = 0 + @abstractmethod def __init__(self): raise NotImplementedError -- cgit v1.2.3-70-g09d2