From 4797037ae8bfd2e158cefe272552f6acf8e23ca5 Mon Sep 17 00:00:00 2001 From: qianlifeng Date: Thu, 29 May 2025 22:51:17 +0800 Subject: [PATCH] refactor(python_host): improve python module load * Updated function signatures to include return types for better clarity and type checking. * Enhanced maintainability and readability of the logger module. * Ensured consistency across the codebase by applying type hints to all relevant functions. --- .../src/wox_plugin_host/__main__.py | 8 ++++---- .../src/wox_plugin_host/host.py | 9 +++++---- .../src/wox_plugin_host/jsonrpc.py | 19 +++++-------------- .../src/wox_plugin_host/logger.py | 12 ++++++------ 4 files changed, 20 insertions(+), 28 deletions(-) diff --git a/wox.plugin.host.python/src/wox_plugin_host/__main__.py b/wox.plugin.host.python/src/wox_plugin_host/__main__.py index 1154788c..fb83c567 100644 --- a/wox.plugin.host.python/src/wox_plugin_host/__main__.py +++ b/wox.plugin.host.python/src/wox_plugin_host/__main__.py @@ -19,7 +19,7 @@ host_id = f"python-{uuid.uuid4()}" logger.update_log_directory(log_directory) -def check_wox_process(): +def check_wox_process() -> bool: """Check if Wox process is still alive""" try: os.kill(wox_pid, 0) @@ -28,7 +28,7 @@ def check_wox_process(): return False -async def monitor_wox_process(): +async def monitor_wox_process() -> None: """Monitor Wox process and exit if it's not alive""" await logger.info(trace_id, "start monitor wox process") while True: @@ -38,7 +38,7 @@ async def monitor_wox_process(): await asyncio.sleep(1) -async def main(): +async def main() -> None: """Main function""" # Log startup information @@ -53,5 +53,5 @@ async def main(): await asyncio.gather(monitor_task, websocket_task) -def run(): +def run() -> None: asyncio.run(main()) diff --git a/wox.plugin.host.python/src/wox_plugin_host/host.py b/wox.plugin.host.python/src/wox_plugin_host/host.py index a1e4a5c7..515e0d91 100644 --- a/wox.plugin.host.python/src/wox_plugin_host/host.py +++ b/wox.plugin.host.python/src/wox_plugin_host/host.py @@ -2,6 +2,7 @@ import asyncio import json import uuid import traceback +from typing import Any from wox_plugin import Context import websockets @@ -11,7 +12,7 @@ from .plugin_manager import waiting_for_response from .jsonrpc import handle_request_from_wox -def _clean_for_serialization(obj): +def _clean_for_serialization(obj: Any) -> Any: """Remove non-serializable properties from any object recursively""" if obj is None: return obj @@ -43,7 +44,7 @@ def _clean_for_serialization(obj): return None -async def handle_message(ws: websockets.asyncio.server.ServerConnection, message: str): +async def handle_message(ws: websockets.asyncio.server.ServerConnection, message: str) -> None: """Handle incoming WebSocket message""" trace_id = str(uuid.uuid4()) @@ -99,7 +100,7 @@ async def handle_message(ws: websockets.asyncio.server.ServerConnection, message ) -async def handler(websocket: websockets.asyncio.server.ServerConnection): +async def handler(websocket: websockets.asyncio.server.ServerConnection) -> None: """WebSocket connection handler""" logger.update_websocket(websocket) @@ -118,7 +119,7 @@ async def handler(websocket: websockets.asyncio.server.ServerConnection): logger.update_websocket(None) -async def start_websocket(websocket_port: int): +async def start_websocket(websocket_port: int) -> None: """Start WebSocket server""" await logger.info(str(uuid.uuid4()), "start websocket server") async with websockets.serve(handler, "", websocket_port): diff --git a/wox.plugin.host.python/src/wox_plugin_host/jsonrpc.py b/wox.plugin.host.python/src/wox_plugin_host/jsonrpc.py index aab510c9..2cc09f86 100644 --- a/wox.plugin.host.python/src/wox_plugin_host/jsonrpc.py +++ b/wox.plugin.host.python/src/wox_plugin_host/jsonrpc.py @@ -62,28 +62,19 @@ async def load_plugin(ctx: Context, request: Dict[str, Any]) -> None: # Add plugin directory to Python path if plugin_directory not in sys.path: + await logger.info(ctx.get_trace_id(), f"add: {plugin_directory} to sys.path") sys.path.append(plugin_directory) deps_dir = path.join(plugin_directory, "dependencies") if path.exists(deps_dir) and deps_dir not in sys.path: + await logger.info(ctx.get_trace_id(), f"add: {deps_dir} to sys.path") sys.path.append(deps_dir) try: - # Add the parent directory to Python path - parent_dir = path.dirname(plugin_directory) - if parent_dir not in sys.path: - sys.path.append(parent_dir) - # Convert entry path to module path - # e.g., "killprocess/main.py" -> "dist.killprocess.main" - plugin_dir_name = path.basename(plugin_directory) - entry_without_ext = entry.replace(".py", "").replace("/", ".") - module_path = f"{plugin_dir_name}.{entry_without_ext}" - - await logger.info( - ctx.get_trace_id(), - f"module_path: {module_path}, plugin_dir_name: {plugin_dir_name}, entry_without_ext: {entry_without_ext}", - ) + # e.g., "replaceme_with_projectname/main.py" -> "replaceme_with_projectname.main" + module_path = entry.replace(".py", "").replace("/", ".") + await logger.info(ctx.get_trace_id(), f"module_path: {module_path}") # Import the module module = importlib.import_module(module_path) diff --git a/wox.plugin.host.python/src/wox_plugin_host/logger.py b/wox.plugin.host.python/src/wox_plugin_host/logger.py index 224a48ad..06b3cbbb 100644 --- a/wox.plugin.host.python/src/wox_plugin_host/logger.py +++ b/wox.plugin.host.python/src/wox_plugin_host/logger.py @@ -7,19 +7,19 @@ PLUGIN_JSONRPC_TYPE_SYSTEM_LOG = "WOX_JSONRPC_SYSTEM_LOG" websocket: Optional[ServerConnection] = None -def update_log_directory(log_directory: str): +def update_log_directory(log_directory: str) -> None: """Update the log directory for the logger""" logger.remove() logger.add(f"{log_directory}/python.log", format="{time} {message}") -def update_websocket(ws: Optional[ServerConnection]): +def update_websocket(ws: Optional[ServerConnection]) -> None: """Update the websocket connection for logging""" global websocket websocket = ws -async def log(trace_id: str, level: str, msg: str): +async def log(trace_id: str, level: str, msg: str) -> None: """Log a message to both file and websocket if available""" logger.log(level.upper(), f"{trace_id} [{level}] {msg}") @@ -39,13 +39,13 @@ async def log(trace_id: str, level: str, msg: str): logger.error(f"Failed to send log message through websocket: {e}") -async def debug(trace_id: str, msg: str): +async def debug(trace_id: str, msg: str) -> None: await log(trace_id, "debug", msg) -async def info(trace_id: str, msg: str): +async def info(trace_id: str, msg: str) -> None: await log(trace_id, "info", msg) -async def error(trace_id: str, msg: str): +async def error(trace_id: str, msg: str) -> None: await log(trace_id, "error", msg)