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)
|
logger.update_log_directory(log_directory)
|
||||||
|
|
||||||
|
|
||||||
def check_wox_process():
|
def check_wox_process() -> bool:
|
||||||
"""Check if Wox process is still alive"""
|
"""Check if Wox process is still alive"""
|
||||||
try:
|
try:
|
||||||
os.kill(wox_pid, 0)
|
os.kill(wox_pid, 0)
|
||||||
|
@ -28,7 +28,7 @@ def check_wox_process():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
async def monitor_wox_process():
|
async def monitor_wox_process() -> None:
|
||||||
"""Monitor Wox process and exit if it's not alive"""
|
"""Monitor Wox process and exit if it's not alive"""
|
||||||
await logger.info(trace_id, "start monitor wox process")
|
await logger.info(trace_id, "start monitor wox process")
|
||||||
while True:
|
while True:
|
||||||
|
@ -38,7 +38,7 @@ async def monitor_wox_process():
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main() -> None:
|
||||||
"""Main function"""
|
"""Main function"""
|
||||||
# Log startup information
|
# Log startup information
|
||||||
|
|
||||||
|
@ -53,5 +53,5 @@ async def main():
|
||||||
await asyncio.gather(monitor_task, websocket_task)
|
await asyncio.gather(monitor_task, websocket_task)
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run() -> None:
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
|
@ -2,6 +2,7 @@ import asyncio
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
import traceback
|
import traceback
|
||||||
|
from typing import Any
|
||||||
from wox_plugin import Context
|
from wox_plugin import Context
|
||||||
import websockets
|
import websockets
|
||||||
|
|
||||||
|
@ -11,7 +12,7 @@ from .plugin_manager import waiting_for_response
|
||||||
from .jsonrpc import handle_request_from_wox
|
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"""
|
"""Remove non-serializable properties from any object recursively"""
|
||||||
if obj is None:
|
if obj is None:
|
||||||
return obj
|
return obj
|
||||||
|
@ -43,7 +44,7 @@ def _clean_for_serialization(obj):
|
||||||
return None
|
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"""
|
"""Handle incoming WebSocket message"""
|
||||||
|
|
||||||
trace_id = str(uuid.uuid4())
|
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"""
|
"""WebSocket connection handler"""
|
||||||
logger.update_websocket(websocket)
|
logger.update_websocket(websocket)
|
||||||
|
|
||||||
|
@ -118,7 +119,7 @@ async def handler(websocket: websockets.asyncio.server.ServerConnection):
|
||||||
logger.update_websocket(None)
|
logger.update_websocket(None)
|
||||||
|
|
||||||
|
|
||||||
async def start_websocket(websocket_port: int):
|
async def start_websocket(websocket_port: int) -> None:
|
||||||
"""Start WebSocket server"""
|
"""Start WebSocket server"""
|
||||||
await logger.info(str(uuid.uuid4()), "start websocket server")
|
await logger.info(str(uuid.uuid4()), "start websocket server")
|
||||||
async with websockets.serve(handler, "", websocket_port):
|
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
|
# Add plugin directory to Python path
|
||||||
if plugin_directory not in sys.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)
|
sys.path.append(plugin_directory)
|
||||||
|
|
||||||
deps_dir = path.join(plugin_directory, "dependencies")
|
deps_dir = path.join(plugin_directory, "dependencies")
|
||||||
if path.exists(deps_dir) and deps_dir not in sys.path:
|
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)
|
sys.path.append(deps_dir)
|
||||||
|
|
||||||
try:
|
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
|
# Convert entry path to module path
|
||||||
# e.g., "killprocess/main.py" -> "dist.killprocess.main"
|
# e.g., "replaceme_with_projectname/main.py" -> "replaceme_with_projectname.main"
|
||||||
plugin_dir_name = path.basename(plugin_directory)
|
module_path = entry.replace(".py", "").replace("/", ".")
|
||||||
entry_without_ext = entry.replace(".py", "").replace("/", ".")
|
await logger.info(ctx.get_trace_id(), f"module_path: {module_path}")
|
||||||
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}",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Import the module
|
# Import the module
|
||||||
module = importlib.import_module(module_path)
|
module = importlib.import_module(module_path)
|
||||||
|
|
|
@ -7,19 +7,19 @@ PLUGIN_JSONRPC_TYPE_SYSTEM_LOG = "WOX_JSONRPC_SYSTEM_LOG"
|
||||||
websocket: Optional[ServerConnection] = None
|
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"""
|
"""Update the log directory for the logger"""
|
||||||
logger.remove()
|
logger.remove()
|
||||||
logger.add(f"{log_directory}/python.log", format="{time} {message}")
|
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"""
|
"""Update the websocket connection for logging"""
|
||||||
global websocket
|
global websocket
|
||||||
websocket = ws
|
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"""
|
"""Log a message to both file and websocket if available"""
|
||||||
logger.log(level.upper(), f"{trace_id} [{level}] {msg}")
|
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}")
|
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)
|
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)
|
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)
|
await log(trace_id, "error", msg)
|
||||||
|
|
Loading…
Reference in New Issue