# -*- coding: utf-8 -*- """仓库最小 CI 检查(本地与 GitLab Runner 共用)。 用法: .venv\\Scripts\\python.exe tools/ci_check.py # 语法编译 + 单测 .venv\\Scripts\\python.exe tools/ci_check.py --frontend # 追加执行机壳前端构建 检查项: 1. 全量 Python 语法编译(py_compile:只编译不落 __pycache__,避免污染工作区); 2. tests/unit 纯逻辑单测(pytest); 3. --frontend:electron-shell/frontend 的 vite build(需本机有 pnpm/npm 与 node_modules)。 不检查 controlplane-next 前端:其 build 前置 vue-tsc 全量类型检查,历史类型告警 不在本 CI 的阻塞范围,单独治理。 """ import argparse import os import py_compile import shutil import subprocess import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # 依赖目录 / 产物 / 本地临时目录不参与语法检查 EXCLUDE_DIRS = { ".venv", "venv", "node_modules", ".git", "__pycache__", "dist", "build", "dist-plugin", "dist-sdk", "dist-app", "dist-env", "python-env", "logs", "out", ".tmp-deploy", ".tmp2", ".tmp_xq0052", "tmp_probe_js", } def iter_py_files(): for path in ROOT.rglob("*.py"): rel_parts = path.relative_to(ROOT).parts if any(part in EXCLUDE_DIRS for part in rel_parts[:-1]): continue yield path def check_syntax(): files = list(iter_py_files()) errors = [] with tempfile.TemporaryDirectory() as tmp: cfile = str(Path(tmp) / "x.pyc") for path in files: try: py_compile.compile(str(path), cfile=cfile, doraise=True) except py_compile.PyCompileError as exc: errors.append(f"{path.relative_to(ROOT)}: {exc.msg}") print(f"[syntax] 检查 {len(files)} 个 Python 文件,失败 {len(errors)} 个") for line in errors: print(" " + line) return len(errors) def run_pytest(): cmd = [sys.executable, "-m", "pytest", "-p", "no:cacheprovider"] print("[pytest] " + " ".join(cmd)) return subprocess.run(cmd, cwd=ROOT).returncode def run_frontend_build(): front = ROOT / "desktop" / "electron-shell" / "frontend" if not (front / "node_modules").exists(): print("[frontend] 跳过:node_modules 未安装") return 0 # Windows 上 which("pnpm") 可能命中 pnpm.ps1(cmd.exe 无法直接执行),优先取 .cmd pm = (shutil.which("pnpm.cmd") or shutil.which("pnpm") or shutil.which("npm.cmd") or shutil.which("npm")) if not pm: print("[frontend] 跳过:未找到 pnpm/npm") return 0 print(f"[frontend] {Path(pm).name} run build") return subprocess.run(f'"{pm}" run build', cwd=front, shell=True).returncode def main(): parser = argparse.ArgumentParser(description="仓库最小 CI 检查") parser.add_argument("--frontend", action="store_true", help="追加执行机壳前端构建") args = parser.parse_args() os.chdir(ROOT) failed = check_syntax() != 0 if run_pytest() != 0: failed = True if args.frontend and run_frontend_build() != 0: failed = True print("CI 结果:" + ("FAILED" if failed else "PASSED")) return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())