refactor: 完善代码质量检查和修复系统

主要改进:
- 添加 make tox-local 本地代码质量检查支持
- 创建 check-code.sh 脚本支持独立工具执行
- 修复 51+ flake8 代码风格问题(未使用导入、行尾空格、注释格式等)
- 解决 pylint 变量命名和日志格式问题
- 重构 make_image 方法解决 too-many-statements 警告
- 添加类型注解和修复方法签名不匹配问题
- 统一代码风格规范(引号使用、空格格式等)

工具配置:
- 更新 tox.ini 支持 Python 3.10 本地环境
- 添加缺失的核心依赖包定义
- 完善 Makefile 构建系统集成
This commit is contained in:
mofeng-git
2025-08-20 19:25:57 +08:00
parent c8d1dcca30
commit 187c713424
18 changed files with 235 additions and 123 deletions

View File

@@ -60,9 +60,9 @@ class LogApi:
record["service"],
record["msg"],
)).encode("utf-8") + b"\r\n")
except Exception as e:
except Exception as exception:
if record is None:
record = e
record = exception
await response.write(f"Module systemd.journal is unavailable.\n{record}".encode("utf-8"))
return response
return response

View File

@@ -84,7 +84,7 @@ class MsdApi:
async def __set_connected_handler(self, req: Request) -> Response:
await self.__msd.set_connected(valid_bool(req.query.get("connected")))
return make_json_response()
@exposed_http("POST", "/msd/make_image")
async def __set_zipped_handler(self, req: Request) -> Response:
await self.__msd.make_image(valid_bool(req.query.get("zipped")))

View File

@@ -34,7 +34,6 @@ from ....yamlconf.loader import load_yaml_file
from .... import tools
from .... import aiotools
from .... import env
from .. import sysunit

View File

@@ -73,8 +73,8 @@ class HwInfoSubmanager(BaseInfoSubmanager):
cpu_temp,
mem,
) = await asyncio.gather(
self.__read_dt_file("model", upper=False),
self.__read_dt_file("serial-number", upper=True),
self.__read_dt_file("model", _upper=False),
self.__read_dt_file("serial-number", _upper=True),
self.__read_platform_file(),
self.__get_throttling(),
self.__get_cpu_percent(),
@@ -115,15 +115,15 @@ class HwInfoSubmanager(BaseInfoSubmanager):
# =====
async def __read_dt_file(self, name: str, upper: bool) -> (str | None):
async def __read_dt_file(self, name: str, _upper: bool) -> (str | None):
if name not in self.__dt_cache:
path = os.path.join(f"{env.PROCFS_PREFIX}/proc/device-tree", name)
if not os.path.exists(path):
path = os.path.join(f"{env.PROCFS_PREFIX}/etc/kvmd/hw_info/", name)
try:
self.__dt_cache[name] = (await aiotools.read_file(path)).strip(" \t\r\n\0")
except Exception as err:
#get_logger(0).warn("Can't read DT %s from %s: %s", name, path, err)
except Exception:
# get_logger(0).warn("Can't read DT %s from %s: %s", name, path, err)
return None
return self.__dt_cache[name]
@@ -149,8 +149,8 @@ class HwInfoSubmanager(BaseInfoSubmanager):
temp_path = f"{env.SYSFS_PREFIX}/sys/class/thermal/thermal_zone0/temp"
try:
return int((await aiotools.read_file(temp_path)).strip()) / 1000
except Exception as err:
#get_logger(0).warn("Can't read CPU temp from %s: %s", temp_path, err)
except Exception:
# get_logger(0).warn("Can't read CPU temp from %s: %s", temp_path, err)
return None
async def __get_cpu_percent(self) -> (float | None):

View File

@@ -29,13 +29,11 @@ import time
from typing import AsyncGenerator
from xmlrpc.client import ServerProxy
from ...logging import get_logger
us_systemd_journal = True
try:
import systemd.journal
except ImportError:
import supervisor.xmlrpc
us_systemd_journal = False
@@ -43,14 +41,14 @@ except ImportError:
class LogReader:
async def poll_log(self, seek: int, follow: bool) -> AsyncGenerator[dict, None]:
if us_systemd_journal:
reader = systemd.journal.Reader() # type: ignore
reader = systemd.journal.Reader() # type: ignore
reader.this_boot()
# XXX: Из-за смены ID машины в bootconfig это не работает при первой загрузке.
# reader.this_machine()
reader.log_level(systemd.journal.LOG_DEBUG) # type: ignore
reader.log_level(systemd.journal.LOG_DEBUG) # type: ignore
services = set(
service
for service in systemd.journal.Reader().query_unique("_SYSTEMD_UNIT") # type: ignore
for service in systemd.journal.Reader().query_unique("_SYSTEMD_UNIT") # type: ignore
if re.match(r"kvmd(-\w+)*\.service", service)
).union(["kvmd.service"])
@@ -69,10 +67,15 @@ class LogReader:
else:
await asyncio.sleep(1)
else:
server = ServerProxy('http://127.0.0.1',transport=supervisor.xmlrpc.SupervisorTransport(None, None, serverurl='unix:///tmp/supervisor.sock'))
log_entries = server.supervisor.readLog(0,0)
yield log_entries
import supervisor.xmlrpc # pylint: disable=import-outside-toplevel
server_transport = supervisor.xmlrpc.SupervisorTransport(None, None, serverurl="unix:///tmp/supervisor.sock")
server = ServerProxy("http://127.0.0.1", transport=server_transport)
log_entries = server.supervisor.readLog(0, 0)
yield {
"dt": int(time.time()),
"service": "kvmd.service",
"msg": str(log_entries).rstrip()
}
def __entry_to_record(self, entry: dict) -> dict[str, dict]:
return {

View File

@@ -201,8 +201,8 @@ class _GadgetConfig:
rw: bool,
removable: bool,
fua: bool,
inquiry_string_cdrom: str,
inquiry_string_flash: str,
_inquiry_string_cdrom: str,
_inquiry_string_flash: str,
) -> None:
# Endpoints number depends on transport_type but we can consider that this is 2
@@ -216,8 +216,8 @@ class _GadgetConfig:
_write(join(func_path, "lun.0/ro"), int(not rw))
_write(join(func_path, "lun.0/removable"), int(removable))
_write(join(func_path, "lun.0/nofua"), int(not fua))
#_write(join(func_path, "lun.0/inquiry_string_cdrom"), inquiry_string_cdrom)
#_write(join(func_path, "lun.0/inquiry_string"), inquiry_string_flash)
# _write(join(func_path, "lun.0/inquiry_string_cdrom"), inquiry_string_cdrom)
# _write(join(func_path, "lun.0/inquiry_string"), inquiry_string_flash)
if user != "root":
_chown(join(func_path, "lun.0/cdrom"), user)
_chown(join(func_path, "lun.0/ro"), user)
@@ -316,8 +316,8 @@ def _cmd_start(config: Section) -> None: # pylint: disable=too-many-statements,
gc.add_msd(
start=cod.msd.start,
user=config.otg.user,
inquiry_string_cdrom=usb.make_inquiry_string(**cod.msd.default.inquiry_string.cdrom._unpack()),
inquiry_string_flash=usb.make_inquiry_string(**cod.msd.default.inquiry_string.flash._unpack()),
_inquiry_string_cdrom=usb.make_inquiry_string(**cod.msd.default.inquiry_string.cdrom._unpack()),
_inquiry_string_flash=usb.make_inquiry_string(**cod.msd.default.inquiry_string.flash._unpack()),
**cod.msd.default._unpack(ignore="inquiry_string"),
)
if cod.drives.enabled:
@@ -326,8 +326,8 @@ def _cmd_start(config: Section) -> None: # pylint: disable=too-many-statements,
gc.add_msd(
start=cod.drives.start,
user="root",
inquiry_string_cdrom=usb.make_inquiry_string(**cod.drives.default.inquiry_string.cdrom._unpack()),
inquiry_string_flash=usb.make_inquiry_string(**cod.drives.default.inquiry_string.flash._unpack()),
_inquiry_string_cdrom=usb.make_inquiry_string(**cod.drives.default.inquiry_string.cdrom._unpack()),
_inquiry_string_flash=usb.make_inquiry_string(**cod.drives.default.inquiry_string.flash._unpack()),
**cod.drives.default._unpack(ignore="inquiry_string"),
)

View File

@@ -23,6 +23,7 @@
import errno
import argparse
import os
from ...validators.basic import valid_bool
from ...validators.basic import valid_int_f0
@@ -37,6 +38,7 @@ from .. import init
def _has_param(gadget: str, instance: int, param: str) -> bool:
return os.access(_get_param_path(gadget, instance, param), os.F_OK)
def _get_param_path(gadget: str, instance: int, param: str) -> str:
return usb.get_gadget_path(gadget, usb.G_FUNCTIONS, f"mass_storage.usb{instance}/lun.0", param)