201 lines
6.8 KiB
Python
201 lines
6.8 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
验证 GUI 回退方式控件注入情况的自检脚本。
|
||
|
||
功能:
|
||
- 检查 `gui/gui_app.py` 是否包含关键标记字符串(用于确认控件已被添加)。
|
||
- 读取 `config/config.json` 中的 `return_to_first_back_method` 当前值。
|
||
- 尝试列出当前运行的 Python 进程并检查命令行中是否包含 `gui_app.py`(Windows 下使用 PowerShell/CIM;若可用,优先使用 psutil)。
|
||
|
||
用法:
|
||
python tools/verify_gui_back_method.py
|
||
|
||
返回:
|
||
退出码 0 = 检查通过(所有标记存在);1 = 标记缺失或其他问题。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
from typing import List
|
||
|
||
|
||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||
GUI_APP_PATH = os.path.join(ROOT, "gui", "gui_app.py")
|
||
CONFIG_PATH = os.path.join(ROOT, "config", "config.json")
|
||
|
||
|
||
def check_file_markers(path: str) -> List[str]:
|
||
# 使用变量名和明显的中文标签作为检测标记,兼容不同位置的控件注入实现
|
||
markers = [
|
||
"return_to_first_back_method_var",
|
||
"top_back_method_display_var",
|
||
"back_method_display_var",
|
||
"top_back_method_combo",
|
||
"回退方式:",
|
||
"return_to_first_back_method",
|
||
]
|
||
missing = []
|
||
if not os.path.exists(path):
|
||
return [f"MISSING_FILE:{path}"]
|
||
import unicodedata
|
||
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
txt = f.read()
|
||
|
||
# normalize unicode to NFKC to avoid full-width/half-width or similar variants
|
||
txt_norm = unicodedata.normalize("NFKC", txt).lower()
|
||
for m in markers:
|
||
m_norm = unicodedata.normalize("NFKC", m).lower()
|
||
if m_norm in txt_norm:
|
||
# debug: print where found
|
||
try:
|
||
print(f"DEBUG: marker '{m}' found at index {txt_norm.index(m_norm)}")
|
||
except Exception:
|
||
pass
|
||
continue
|
||
# try a looser check: replace full-width colon variants and simple punctuation
|
||
m_alt = m_norm.replace(":", ":")
|
||
if m_alt in txt_norm:
|
||
try:
|
||
print(f"DEBUG: marker alt '{m}' found at index {txt_norm.index(m_alt)}")
|
||
except Exception:
|
||
pass
|
||
continue
|
||
missing.append(m)
|
||
# Additional raw checks for debugging and fuzzy regex matching
|
||
if missing:
|
||
import re
|
||
|
||
for m in list(missing):
|
||
raw_idx = txt.find(m)
|
||
norm_idx = txt_norm.find(unicodedata.normalize("NFKC", m).lower())
|
||
print(f"DEBUG-RAW: marker '{m}' raw_index={raw_idx}, norm_index={norm_idx}")
|
||
# try fuzzy regex: split by non-word/underscore and allow any separators
|
||
parts = [p for p in re.split(r"[_\W]+", m) if p]
|
||
if parts:
|
||
pattern = r"\b" + r"\W*".join([re.escape(p) for p in parts]) + r"\b"
|
||
if re.search(pattern, txt, flags=re.IGNORECASE):
|
||
print(f"DEBUG-FUZZY: marker '{m}' matched fuzzy pattern: {pattern}")
|
||
missing.remove(m)
|
||
continue
|
||
if raw_idx >= 0 and m in txt:
|
||
# show surrounding repr for inspection
|
||
start = max(0, raw_idx - 40)
|
||
end = min(len(txt), raw_idx + len(m) + 40)
|
||
print("DEBUG-SURROUND:", repr(txt[start:end]))
|
||
# debug: if missing all, print snippet to help diagnosis
|
||
if missing:
|
||
try:
|
||
snippet = txt[:800].replace("\n", " ")[:800]
|
||
print("DEBUG: file starts with:", snippet)
|
||
print("DEBUG: file length:", len(txt))
|
||
except Exception:
|
||
pass
|
||
return missing
|
||
|
||
|
||
def read_config_value(
|
||
path: str, key: str = "return_to_first_back_method"
|
||
) -> str | None:
|
||
if not os.path.exists(path):
|
||
return None
|
||
try:
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
cfg = json.load(f)
|
||
return str(cfg.get(key))
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def list_python_processes_filtering_gui() -> List[dict]:
|
||
"""尝试列出运行中的 python/pythonw 进程并返回其命令行中包含 gui_app.py 的条目。
|
||
|
||
优先使用 psutil(如可用),否则在 Windows 上使用 PowerShell CIM 查询。
|
||
"""
|
||
procs = []
|
||
try:
|
||
import psutil # type: ignore[import]
|
||
|
||
for p in psutil.process_iter(["pid", "name", "cmdline"]):
|
||
try:
|
||
name = (p.info.get("name") or "").lower()
|
||
if "python" in name:
|
||
cmd = " ".join(p.info.get("cmdline") or [])
|
||
if "gui_app.py" in cmd or "gui\\gui_app.py" in cmd:
|
||
procs.append({"pid": p.info.get("pid"), "cmdline": cmd})
|
||
except Exception:
|
||
continue
|
||
return procs
|
||
except Exception:
|
||
pass
|
||
|
||
# Fallback: Windows PowerShell CIM query
|
||
try:
|
||
pw_cmd = [
|
||
"powershell",
|
||
"-NoProfile",
|
||
"-Command",
|
||
"Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and ($_.CommandLine -match 'gui_app.py') } | Select-Object ProcessId,CommandLine | ConvertTo-Json",
|
||
]
|
||
proc = subprocess.run(
|
||
pw_cmd, capture_output=True, text=True, timeout=5, check=False
|
||
)
|
||
out = proc.stdout.strip()
|
||
if not out:
|
||
return []
|
||
# out may be a JSON array or object
|
||
try:
|
||
j = json.loads(out)
|
||
if isinstance(j, dict):
|
||
j = [j]
|
||
for item in j:
|
||
procs.append(
|
||
{"pid": item.get("ProcessId"), "cmdline": item.get("CommandLine")}
|
||
)
|
||
except Exception:
|
||
# fallback to raw parsing
|
||
for line in out.splitlines():
|
||
if "gui_app.py" in line:
|
||
procs.append({"pid": None, "cmdline": line})
|
||
return procs
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
def main() -> int:
|
||
print("Verifying gui injection and runtime usage\n")
|
||
print(f"Workspace root: {ROOT}")
|
||
print(f"Checking file: {GUI_APP_PATH}")
|
||
|
||
missing = check_file_markers(GUI_APP_PATH)
|
||
if missing:
|
||
print("Missing markers in gui_app.py:")
|
||
for m in missing:
|
||
print(" -", m)
|
||
else:
|
||
print("All expected markers present in gui_app.py")
|
||
|
||
cfg_val = read_config_value(CONFIG_PATH)
|
||
print(f"Config: {CONFIG_PATH} -> return_to_first_back_method = {cfg_val}")
|
||
|
||
procs = list_python_processes_filtering_gui()
|
||
if procs:
|
||
print("Found running Python processes with gui_app.py in command line:")
|
||
for p in procs:
|
||
print(f" - PID={p.get('pid')}, CMD={p.get('cmdline')}")
|
||
else:
|
||
print(
|
||
"No running Python processes with gui_app.py detected (psutil/PowerShell lookup)"
|
||
)
|
||
|
||
# Exit code: 0 if no missing markers, else 1
|
||
return 0 if not missing else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
rc = main()
|
||
sys.exit(rc)
|