Files

212 lines
8.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""VDE Debug 本地检查脚本(P4/WP-108-03)。
一条命令完成:配置 Debug -> 构建 -> 按标签分批跑 CTest -> 汇总。
不改变仓库 CI 触发,也不修改产品源码。
用法示例:
python tools/vde_debug_check.py # subset:Debug 构建 + slow/fuzz/perf/tool 分批
python tools/vde_debug_check.py --full # Debug 构建 + 全量 CTest
python tools/vde_debug_check.py --configure-only
python tools/vde_debug_check.py --list-slow # 只列出慢标签测试(需已配置)
python tools/vde_debug_check.py --build-dir build-fb-debugcheck --jobs 10
退出码:0 全部通过;1 构建或测试失败;2 用法/配置错误。
"""
from __future__ import annotations
import argparse
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
def run(command: list[str], cwd: Path | None = None) -> int:
print("+ " + " ".join(str(part) for part in command), flush=True)
try:
return subprocess.call(command, cwd=str(cwd or REPO_ROOT))
except FileNotFoundError:
print(f"命令未找到: {command[0]}", file=sys.stderr)
return 127
def find_cmake() -> str:
return shutil.which("cmake") or "cmake"
def build_dir(path_text: str) -> Path:
path = Path(path_text)
return path if path.is_absolute() else (REPO_ROOT / path)
def configure(build: Path, build_type: str, generator: str, jobs: int) -> int:
cmake = find_cmake()
command = [
cmake,
"-S", str(REPO_ROOT),
"-B", str(build),
"-G", generator,
f"-DCMAKE_BUILD_TYPE={build_type}",
"-DFETCHCONTENT_FULLY_DISCONNECTED=ON",
f"-DFETCHCONTENT_SOURCE_DIR_JSON={REPO_ROOT / 'json'}",
f"-DFETCHCONTENT_SOURCE_DIR_GOOGLETEST={REPO_ROOT / 'googletest'}",
]
# 允许用环境变量 CC/CXX 指定编译器(Linux/Windows MinGW 通用)。
if os.environ.get("CC"):
command.append(f"-DCMAKE_C_COMPILER={os.environ['CC']}")
if os.environ.get("CXX"):
command.append(f"-DCMAKE_CXX_COMPILER={os.environ['CXX']}")
if shutil.which("ccache"):
command.append("-DCMAKE_C_COMPILER_LAUNCHER=ccache")
command.append("-DCMAKE_CXX_COMPILER_LAUNCHER=ccache")
return run(command)
def build(build: Path, jobs: int) -> int:
return run([find_cmake(), "--build", str(build), "-j", str(jobs)])
TEST_LABEL_BATCHES = [
("fuzz", ["-L", "fuzz"]),
("perf", ["-L", "perf"]),
("slow-tool", ["-L", "slow", "-LE", "fuzz|perf"]),
]
def ctest_command(build: Path, extra: list[str], timeout: int) -> list[str]:
return [shutil.which("ctest") or "ctest", "--output-on-failure",
"--timeout", str(timeout)] + extra
def parse_summary(text: str) -> tuple[int, int]:
passed = 0
failed = 0
for line in text.splitlines():
match = re.search(r"(\d+)% tests passed,\s*(\d+) tests failed out of (\d+)", line)
if match:
failed += int(match.group(2))
total = int(match.group(3))
passed += total - int(match.group(2))
else:
match = re.search(r"(\d+)% tests passed,\s*0 tests failed out of (\d+)", line)
if match:
passed += int(match.group(2))
return passed, failed
def run_ctest_batch(build: Path, label: str, args: list[str], timeout: int,
ctest_filter: str | None) -> tuple[int, int, int]:
extra = list(args)
if ctest_filter:
extra += ["-R", ctest_filter]
command = ctest_command(build, extra, timeout)
print(f"\n=== CTest batch: {label} ===", flush=True)
started = time.time()
result = subprocess.run(command, cwd=str(build), text=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
elapsed = time.time() - started
print(result.stdout, end="")
passed, failed = parse_summary(result.stdout)
rc = result.returncode
print(f"--- {label}: rc={rc} passed={passed} failed={failed} elapsed={elapsed:.1f}s")
return rc, passed, failed
def list_slow(build: Path) -> int:
command = [shutil.which("ctest") or "ctest", "-N", "-L", "slow"]
result = subprocess.run(command, cwd=str(build), text=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
print(result.stdout, end="")
return 0 if result.returncode == 0 else 1
def main() -> int:
parser = argparse.ArgumentParser(description="VDE Debug 构建 + CTest 分批检查")
parser.add_argument("--build-dir", default="build-fb-debugcheck",
help="独立构建目录(默认 build-fb-debugcheck)")
parser.add_argument("--build-type", default="Debug", choices=["Debug", "Release",
"RelWithDebInfo", "MinSizeRel"], help="CMake 构建类型(默认 Debug)")
parser.add_argument("--generator", default="Ninja", help="CMake generator(默认 Ninja)")
parser.add_argument("--jobs", type=int, default=max(2, (os.cpu_count() or 4) // 2),
help="并行构建/测试数")
parser.add_argument("--timeout", type=int, default=900,
help="ctest --timeout 每用例秒数(Debug 默认 900)")
group = parser.add_mutually_exclusive_group()
group.add_argument("--full", action="store_true", help="构建后跑全量 CTest")
group.add_argument("--subset", action="store_true",
help="构建后按 slow/fuzz/perf/tool 标签分批跑(默认)")
parser.add_argument("--filter", default=None, help="额外 ctest -R 正则过滤")
parser.add_argument("--configure-only", action="store_true", help="只配置,不构建/测试")
parser.add_argument("--no-configure", action="store_true", help="跳过配置")
parser.add_argument("--no-build", action="store_true", help="跳过构建")
parser.add_argument("--list-slow", action="store_true", help="列出 slow 标签测试")
args = parser.parse_args()
build = build_dir(args.build_dir)
if shutil.which("cmake") is None:
print("错误:PATH 中找不到 cmake", file=sys.stderr)
return 2
if shutil.which("ctest") is None and not args.list_slow:
print("错误:PATH 中找不到 ctest", file=sys.stderr)
return 2
print(f"VDE debug check: repo={REPO_ROOT} build={build} type={args.build_type}")
if args.list_slow:
if not (build / "CTestTestfile.cmake").exists():
print(f"错误:{build} 尚未配置(先运行不带 --list-slow 的命令)",
file=sys.stderr)
return 2
return list_slow(build)
if not args.no_configure:
rc = configure(build, args.build_type, args.generator, args.jobs)
if rc != 0:
print("配置失败", file=sys.stderr)
return 1 if rc != 1 else rc
if args.configure_only:
print("configure-only: PASS")
return 0
elif args.configure_only:
print("configure-only 与 --no-configure 同时给出", file=sys.stderr)
return 2
if not args.no_build:
rc = build(build, args.jobs)
if rc != 0:
print("构建失败", file=sys.stderr)
return 1
total_passed = 0
total_failed = 0
batches: list[tuple[str, list[str]]] = []
if args.full:
batches = [("full", [])]
else:
batches = TEST_LABEL_BATCHES
for label, extra in batches:
rc, passed, failed = run_ctest_batch(build, label, extra, args.timeout,
args.filter)
total_passed += passed
total_failed += failed
if rc != 0:
total_failed = max(total_failed, failed, 1)
print("\n=== summary ===")
print(f"passed={total_passed} failed={total_failed} "
f"batches={len(batches)} build_type={args.build_type}")
if total_failed != 0:
print("debug check: FAIL")
return 1
print("debug check: PASS")
return 0
if __name__ == "__main__":
sys.exit(main())