mirror of https://github.com/Wox-launcher/Wox
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.
This commit is contained in:
parent
872e2873be
commit
4797037ae8
|
@ -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())
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue