- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
787 lines
34 KiB
Python
787 lines
34 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""SDK 兼容预检(`sdk-publish` / `sdk_pack` 的门禁)。
|
||
|
||
回答三个问题:
|
||
1. 哪些插件声明了旧 `compat`,需要跟着升?
|
||
2. 哪些插件代码里用了新 SDK 已删除的 API?
|
||
3. 哪些插件在新 SDK 下导入/自测失败?
|
||
|
||
分类(决定能不能发):
|
||
COMPATIBLE 插件全部可用 → SDK 可单独发(minor/patch 的正常情况)
|
||
PLUGIN_BUMP 只有受影响的插件需要升 compat/改代码,与 SDK 同批发
|
||
ACCIDENTAL_BREAK 本应是 minor/patch 却破坏了兼容 → 拒绝发布,修 SDK 或改 major
|
||
SDK_INVALID SDK 包/清单本身非法 → 先修包
|
||
|
||
用法::
|
||
|
||
.venv\\Scripts\\python.exe tools\\sdk_compat_check.py `
|
||
--sdk libs\\hotel_report --plugins plugins `
|
||
--baseline-sdk dist-sdk\\hotel_report_v0.1.0.zip --json out\\report.json
|
||
|
||
退出码:0=COMPATIBLE / 1=需处理 / 2=SDK 非法 / 3=工具内部错误
|
||
|
||
只用标准库;AST 静态检查 + 子进程导入,不执行业务 run()、不碰生产凭据。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import ast
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import zipfile
|
||
from collections import defaultdict
|
||
from pathlib import Path
|
||
|
||
TOOL_VERSION = "1.0.0"
|
||
|
||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||
|
||
#: 顶层包名黑名单(与 sdk_pack 一致)
|
||
GENERIC_NAMES = {"utils", "common", "config", "core", "lib", "tools", "shared", "models", "api"}
|
||
|
||
#: 扫描插件时跳过的目录(插件 ui-src/node_modules 已入库,每个约 1.1 万文件,必须排除)
|
||
EXCLUDE_DIRS = {
|
||
"node_modules", "ui-src", "dist-plugin", "dist-sdk", "dist-app", "dist-env",
|
||
"__pycache__", ".venv", "venv", ".git", ".idea", ".sessions", "debug",
|
||
"legacy", "tests", "docs", "python-env",
|
||
}
|
||
|
||
#: "SDK 破坏了兼容"的信号(同 major 下出现即判 ACCIDENTAL_BREAK)
|
||
#: 注意 UNDECLARED_SDK / COMPAT_INVALID / NEEDS_BUMP 属于插件侧问题,不算 SDK 破坏
|
||
_BREAK_SIGNALS = {"MISSING_API", "IMPORT_FAIL", "SELFTEST_FAIL", "API_REMOVED"}
|
||
|
||
_IMPORT_SCRIPT = r'''
|
||
import importlib.util, os, sys, traceback
|
||
plugin_dir, webhost_parent = sys.argv[1], sys.argv[2]
|
||
for p in sys.argv[3:]:
|
||
if p and p not in sys.path:
|
||
sys.path.append(p)
|
||
if webhost_parent and webhost_parent not in sys.path:
|
||
sys.path.insert(0, webhost_parent)
|
||
try:
|
||
init = os.path.join(plugin_dir, "__init__.py")
|
||
spec = importlib.util.spec_from_file_location(
|
||
"plugin_under_test", init, submodule_search_locations=[plugin_dir])
|
||
mod = importlib.util.module_from_spec(spec)
|
||
sys.modules["plugin_under_test"] = mod
|
||
spec.loader.exec_module(mod)
|
||
except BaseException:
|
||
traceback.print_exc()
|
||
sys.exit(1)
|
||
sys.exit(0)
|
||
'''
|
||
|
||
_SELFTEST_SCRIPT = r'''
|
||
import os, runpy, sys
|
||
plugin_dir, webhost_parent = sys.argv[1], sys.argv[2]
|
||
for p in sys.argv[3:]:
|
||
if p and p not in sys.path:
|
||
sys.path.append(p)
|
||
if webhost_parent and webhost_parent not in sys.path:
|
||
sys.path.insert(0, webhost_parent)
|
||
os.chdir(plugin_dir)
|
||
sys.path.insert(0, plugin_dir)
|
||
runpy.run_path(os.path.join(plugin_dir, "_selftest.py"), run_name="__main__")
|
||
'''
|
||
|
||
|
||
class SdkInvalid(Exception):
|
||
"""SDK 包/清单非法(退出码 2)。"""
|
||
|
||
|
||
# ---------------------------------------------------------------- 版本比较
|
||
def parse_ver(v) -> tuple:
|
||
core = re.split(r"[-+]", str(v or ""))[0]
|
||
parts = [int(x) for x in core.split(".") if x.isdigit()]
|
||
while len(parts) < 3:
|
||
parts.append(0)
|
||
return tuple(parts[:3])
|
||
|
||
|
||
def cmp_ver(a, b) -> int:
|
||
va, vb = parse_ver(a), parse_ver(b)
|
||
return (va > vb) - (va < vb)
|
||
|
||
|
||
def _satisfy_one(version: str, part: str) -> bool:
|
||
v = parse_ver(version)
|
||
m = re.match(r"^\^(.+)$", part)
|
||
if m:
|
||
b = parse_ver(m.group(1))
|
||
up = (b[0] + 1, 0, 0) if b[0] > 0 else (0, b[1] + 1, 0)
|
||
return v >= b and v < up
|
||
m = re.match(r"^~(.+)$", part)
|
||
if m:
|
||
b = parse_ver(m.group(1))
|
||
return v >= b and v < (b[0], b[1] + 1, 0)
|
||
m = re.match(r"^(>=|<=|>|<|=)?\s*(\d[\w.+-]*)$", part)
|
||
if not m:
|
||
return False
|
||
op, b = (m.group(1) or "="), parse_ver(m.group(2))
|
||
return {
|
||
">=": v >= b, "<=": v <= b, ">": v > b, "<": v < b, "=": v == b,
|
||
}[op]
|
||
|
||
|
||
def satisfies(version: str, rng: str) -> bool:
|
||
"""与客户端 sdk-resolver.js 完全一致的 semver 子集(^ ~ >= <= > < = *)。"""
|
||
raw = str(rng or "*").strip()
|
||
if not raw or raw == "*":
|
||
return True
|
||
return all(_satisfy_one(version, p) for p in raw.split() if p)
|
||
|
||
|
||
def valid_range(rng: str) -> bool:
|
||
raw = str(rng or "*").strip()
|
||
if not raw or raw == "*":
|
||
return True
|
||
return all(re.match(r"^(\^|~)?\d[\w.+-]*$", p) or re.match(r"^(>=|<=|>|<|=)\s*\d[\w.+-]*$", p)
|
||
for p in raw.split() if p)
|
||
|
||
|
||
# ---------------------------------------------------------------- SDK 载入
|
||
class SdkInfo:
|
||
def __init__(self, root: Path, manifest: dict, api: dict, source: str, tmp: str = ""):
|
||
self.root = root
|
||
self.manifest = manifest
|
||
self.api = api
|
||
self.source = source
|
||
self.tmp = tmp
|
||
|
||
@property
|
||
def id(self) -> str:
|
||
return str(self.manifest.get("id") or "")
|
||
|
||
@property
|
||
def version(self) -> str:
|
||
return str(self.manifest.get("version") or "")
|
||
|
||
@property
|
||
def provides(self) -> list:
|
||
return [str(p) for p in (self.manifest.get("provides") or [])]
|
||
|
||
@property
|
||
def modules(self) -> dict:
|
||
return self.api.get("modules") or {}
|
||
|
||
|
||
def _safe_extract(zip_path: Path, dest: Path) -> None:
|
||
with zipfile.ZipFile(zip_path) as zf:
|
||
for info in zf.infolist():
|
||
name = info.filename.replace("\\", "/")
|
||
if name.startswith("/") or ".." in name.split("/") or ":" in name:
|
||
raise SdkInvalid(f"zip 含不安全路径:{info.filename}")
|
||
zf.extractall(dest)
|
||
|
||
|
||
def load_sdk(path: str) -> SdkInfo:
|
||
p = Path(path).resolve()
|
||
tmp = ""
|
||
if p.is_dir():
|
||
root = p
|
||
elif p.is_file() and p.suffix.lower() == ".zip":
|
||
tmp = tempfile.mkdtemp(prefix="sdkchk_")
|
||
try:
|
||
_safe_extract(p, Path(tmp))
|
||
except SdkInvalid:
|
||
shutil.rmtree(tmp, ignore_errors=True)
|
||
raise
|
||
except (zipfile.BadZipFile, OSError) as e:
|
||
shutil.rmtree(tmp, ignore_errors=True)
|
||
raise SdkInvalid(f"SDK 包损坏:{e}") from e
|
||
root = Path(tmp)
|
||
else:
|
||
raise SdkInvalid(f"SDK 路径不存在或不是目录/zip:{path}")
|
||
|
||
man_path = root / "sdk.json"
|
||
if not man_path.is_file():
|
||
raise SdkInvalid(f"缺少 sdk.json:{man_path}")
|
||
try:
|
||
manifest = json.loads(man_path.read_text(encoding="utf-8").lstrip("\ufeff"))
|
||
except Exception as e: # noqa: BLE001
|
||
raise SdkInvalid(f"sdk.json 解析失败:{e}") from e
|
||
|
||
if int(manifest.get("schema_version") or 0) != 1:
|
||
raise SdkInvalid("sdk.json.schema_version 必须为 1")
|
||
if not re.match(r"^[a-z][a-z0-9_]{1,63}$", str(manifest.get("id") or "")):
|
||
raise SdkInvalid(f"sdk.json.id 非法:{manifest.get('id')!r}")
|
||
if not re.match(r"^\d+\.\d+\.\d+([-.][0-9A-Za-z.]+)?$", str(manifest.get("version") or "")):
|
||
raise SdkInvalid(f"sdk.json.version 非法:{manifest.get('version')!r}")
|
||
provides = manifest.get("provides") or []
|
||
if not isinstance(provides, list) or not provides:
|
||
raise SdkInvalid("sdk.json.provides 必须是非空数组")
|
||
for name in provides:
|
||
if name in GENERIC_NAMES:
|
||
raise SdkInvalid(f"provides 含泛名 {name!r}(会被环境包遮蔽)")
|
||
if not (root / name / "__init__.py").is_file():
|
||
raise SdkInvalid(f"provides 目录缺失:{root / name}")
|
||
|
||
api_rel = str(manifest.get("api") or "api.json")
|
||
api_path = root / api_rel
|
||
if not api_path.is_file():
|
||
raise SdkInvalid(f"缺少 {api_rel}(打包时由 tools/sdk_pack.py 生成)")
|
||
try:
|
||
api = json.loads(api_path.read_text(encoding="utf-8").lstrip("\ufeff"))
|
||
except Exception as e: # noqa: BLE001
|
||
raise SdkInvalid(f"{api_rel} 解析失败:{e}") from e
|
||
if str(api.get("sdk_id") or "") != str(manifest.get("id") or ""):
|
||
raise SdkInvalid(f"{api_rel}.sdk_id 与 sdk.json.id 不一致")
|
||
if str(api.get("version") or "") != str(manifest.get("version") or ""):
|
||
raise SdkInvalid(f"{api_rel}.version 与 sdk.json.version 不一致(api.json 需重新生成)")
|
||
if not api.get("modules"):
|
||
raise SdkInvalid(f"{api_rel}.modules 为空")
|
||
|
||
return SdkInfo(root, manifest, api, str(p), tmp)
|
||
|
||
|
||
def sdk_side_findings(info: SdkInfo, python: str, runtime_version: str) -> list:
|
||
"""SDK 自身合法性(任一 error → SDK_INVALID,退出码 2)。"""
|
||
out: list = []
|
||
|
||
need = str(info.manifest.get("python") or "").strip()
|
||
if need:
|
||
cur = sys.version_info
|
||
cur_t = (cur.major, cur.minor, cur.micro)
|
||
ok = True
|
||
for part in need.split(","):
|
||
m = re.match(r"^(>=|<=|==|>|<)?\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?$", part.strip())
|
||
if not m:
|
||
ok = False
|
||
break
|
||
op = m.group(1) or "=="
|
||
want = (int(m.group(2)), int(m.group(3) or 0), int(m.group(4) or 0))
|
||
checks = {
|
||
">=": cur_t >= want, "<=": cur_t <= want, ">": cur_t > want,
|
||
"<": cur_t < want, "==": cur_t[:len(want)] == want,
|
||
}
|
||
ok = ok and checks[op]
|
||
if not ok:
|
||
out.append(_f("SDK_PYTHON_MISMATCH", "error",
|
||
f"sdk.json.python={need},当前解释器 {cur_t[0]}.{cur_t[1]}.{cur_t[2]}",
|
||
suggestion="用匹配的解释器跑预检,或调整 sdk.json.python"))
|
||
|
||
import importlib.util
|
||
for dep in (info.manifest.get("deps") or []):
|
||
try:
|
||
found = importlib.util.find_spec(str(dep)) is not None
|
||
except (ImportError, ValueError):
|
||
found = False
|
||
if not found:
|
||
out.append(_f("SDK_DEP_MISSING", "error", f"deps 不可导入:{dep}",
|
||
suggestion="执行机环境包必须预装该依赖;先在 .venv 安装再打包"))
|
||
|
||
for pkg in info.provides:
|
||
try:
|
||
found = importlib.util.find_spec(pkg)
|
||
except (ImportError, ValueError):
|
||
found = None
|
||
if found is not None:
|
||
out.append(_f("SDK_PACKAGE_COLLISION", "error",
|
||
f"provides 包名与环境已装包冲突:{pkg}({getattr(found, 'origin', '?')})",
|
||
suggestion="换顶层包名;或从环境包移除同名包后再发"))
|
||
|
||
need_rt = str(info.manifest.get("minRuntimeVersion") or "").strip()
|
||
if runtime_version and need_rt and cmp_ver(runtime_version, need_rt) < 0:
|
||
out.append(_f("SDK_RUNTIME_TOO_OLD", "error",
|
||
f"minRuntimeVersion={need_rt} > 当前壳版本 {runtime_version}",
|
||
suggestion="先发壳子/环境包,或下调 minRuntimeVersion"))
|
||
|
||
ver_in_pkg = _package_version(info)
|
||
if ver_in_pkg and ver_in_pkg != info.version:
|
||
out.append(_f("SDK_INVALID", "error",
|
||
f"包内 __version__={ver_in_pkg} 与 sdk.json.version={info.version} 不一致",
|
||
suggestion="同步修改 __version__ 与 sdk.json.version"))
|
||
return out
|
||
|
||
|
||
def _package_version(info: SdkInfo) -> str:
|
||
pkg = info.provides[0]
|
||
init = info.root / pkg / "__init__.py"
|
||
try:
|
||
tree = ast.parse(init.read_text(encoding="utf-8", errors="replace"))
|
||
except (SyntaxError, OSError):
|
||
return ""
|
||
for node in tree.body:
|
||
if isinstance(node, ast.Assign):
|
||
for t in node.targets:
|
||
if isinstance(t, ast.Name) and t.id == "__version__":
|
||
try:
|
||
return str(ast.literal_eval(node.value))
|
||
except (ValueError, SyntaxError):
|
||
return ""
|
||
return ""
|
||
|
||
|
||
# ---------------------------------------------------------------- 插件发现/扫描
|
||
def discover_plugins(root: str, only: set, exclude: set) -> list:
|
||
base = Path(root).resolve()
|
||
out = []
|
||
if not base.is_dir():
|
||
return out
|
||
for dirpath, dirnames, filenames in os.walk(base):
|
||
dirnames[:] = sorted(d for d in dirnames
|
||
if d not in EXCLUDE_DIRS and not d.startswith("."))
|
||
if "plugin.json" in filenames:
|
||
dirnames[:] = [] # 插件内部不再向下找
|
||
mf = Path(dirpath) / "plugin.json"
|
||
try:
|
||
man = json.loads(mf.read_text(encoding="utf-8").lstrip("\ufeff"))
|
||
except Exception as e: # noqa: BLE001
|
||
out.append({"dir": Path(dirpath), "manifest": None,
|
||
"findings": [_f("PLUGIN_MANIFEST_INVALID", "error",
|
||
f"plugin.json 解析失败:{e}", file=str(mf))]})
|
||
continue
|
||
pid = str(man.get("id") or "")
|
||
if not pid:
|
||
out.append({"dir": Path(dirpath), "manifest": man,
|
||
"findings": [_f("PLUGIN_MANIFEST_INVALID", "error",
|
||
"plugin.json 缺 id", file=str(mf))]})
|
||
continue
|
||
if only and pid not in only:
|
||
continue
|
||
if exclude and pid in exclude:
|
||
continue
|
||
out.append({"dir": Path(dirpath), "manifest": man, "findings": []})
|
||
return out
|
||
|
||
|
||
def scan_python(plugin_dir: Path, provides: list) -> dict:
|
||
"""AST 扫描插件源码里对 SDK 的静态引用(import / from-import / 动态 import)。"""
|
||
mods: set = set()
|
||
symbols: dict = defaultdict(set)
|
||
dynamic: list = []
|
||
files = 0
|
||
roots = set(provides)
|
||
for path in sorted(plugin_dir.rglob("*.py")):
|
||
rel = path.relative_to(plugin_dir)
|
||
if any(p in EXCLUDE_DIRS or p.startswith(".") for p in rel.parts[:-1]):
|
||
continue
|
||
files += 1
|
||
try:
|
||
tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"), filename=str(path))
|
||
except SyntaxError:
|
||
continue
|
||
for node in ast.walk(tree):
|
||
if isinstance(node, ast.Import):
|
||
for a in node.names:
|
||
if a.name.split(".")[0] in roots:
|
||
mods.add(a.name)
|
||
elif isinstance(node, ast.ImportFrom):
|
||
if node.level or not node.module:
|
||
continue
|
||
if node.module.split(".")[0] not in roots:
|
||
continue
|
||
mods.add(node.module)
|
||
for a in node.names:
|
||
if a.name != "*":
|
||
symbols[node.module].add(
|
||
(a.name, getattr(node, "lineno", 0), str(rel).replace("\\", "/")))
|
||
elif isinstance(node, ast.Call):
|
||
fn = node.func
|
||
name = getattr(fn, "attr", None) if isinstance(fn, ast.Attribute) else getattr(fn, "id", None)
|
||
if name in ("import_module", "__import__") and node.args:
|
||
arg = node.args[0]
|
||
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
|
||
root = arg.value.split(".")[0]
|
||
if root in roots:
|
||
dynamic.append((arg.value, getattr(node, "lineno", 0),
|
||
str(rel).replace("\\", "/")))
|
||
return {"modules": mods, "symbols": symbols, "dynamic": dynamic, "files": files}
|
||
|
||
|
||
def check_plugin(plugin: dict, sdk: SdkInfo) -> tuple:
|
||
"""返回 (findings, scan)。"""
|
||
findings: list = list(plugin["findings"])
|
||
man = plugin["manifest"] or {}
|
||
declared = ((man.get("requires") or {}).get("sdks") or {})
|
||
scan = scan_python(plugin["dir"], sdk.provides)
|
||
uses = bool(scan["modules"]) or bool(scan["dynamic"])
|
||
|
||
# 1) 声明与使用的一致性
|
||
if uses and not declared:
|
||
findings.append(_f("UNDECLARED_SDK", "error",
|
||
"代码 import 了 SDK,但 plugin.json.requires.sdks 未声明",
|
||
suggestion=f"增加 requires.sdks.{sdk.id}.compat(建议 ^{sdk.version.rsplit('.', 1)[0]})"))
|
||
if declared and not uses:
|
||
findings.append(_f("UNUSED_DECLARATION", "warning",
|
||
"声明了 SDK 但源码里没找到 import(可能动态使用)"))
|
||
|
||
# 2. compat 是否覆盖新版本
|
||
for sdk_id, conf in declared.items():
|
||
rng = str((conf or {}).get("compat") or "*")
|
||
if not valid_range(rng):
|
||
findings.append(_f("COMPAT_INVALID", "error", f"compat 不是合法 semver 范围:{rng!r}"))
|
||
continue
|
||
if sdk_id == sdk.id and not satisfies(sdk.version, rng):
|
||
major = sdk.version.split(".")[0]
|
||
findings.append(_f("NEEDS_BUMP", "error",
|
||
f"compat {rng} 不包含新版本 {sdk.version}",
|
||
suggestion=f"升插件版本并把 compat 改成 ^{major}.0"))
|
||
|
||
# 3) 静态 API 比对
|
||
api_mods = sdk.modules
|
||
for mod in sorted(scan["modules"]):
|
||
if mod not in api_mods:
|
||
findings.append(_f("MISSING_API", "error", f"模块不存在:{mod}",
|
||
suggestion=f"改用 api.json 里仍存在的模块"))
|
||
for mod, names in scan["symbols"].items():
|
||
exports = set((api_mods.get(mod) or {}).get("exports") or [])
|
||
for name, line, rel in sorted(names):
|
||
if mod in api_mods and name not in exports:
|
||
findings.append(_f("MISSING_API", "error",
|
||
f"{mod} 中不存在符号 {name}",
|
||
file=rel, line=line,
|
||
suggestion="改用新 API,或由 SDK 保留该导出"))
|
||
|
||
# 4) 动态导入只警告
|
||
for target, line, rel in scan["dynamic"]:
|
||
findings.append(_f("DYNAMIC_IMPORT", "warning",
|
||
f"动态导入 {target}:静态检查无法校验",
|
||
file=rel, line=line))
|
||
|
||
# 5) 插件内复制了 SDK 副本(口径迟早分叉,应改用挂载)
|
||
for rel in vendored_copies(plugin["dir"], sdk.provides):
|
||
findings.append(_f("VENDORED_SDK", "warning",
|
||
f"插件内出现 SDK 副本:{rel}",
|
||
suggestion=f"改用 plugin.json.requires.sdks.{sdk.id} + import {sdk.id}(挂载)"))
|
||
return findings, scan
|
||
|
||
|
||
def vendored_copies(plugin_dir: Path, provides: list) -> list:
|
||
"""启发式检测插件目录里是否复制了 SDK 包(顶层或一层子目录内的同名包/模块)。"""
|
||
roots = set(provides)
|
||
hits: list = []
|
||
for depth_dir in (plugin_dir, None):
|
||
if depth_dir is plugin_dir:
|
||
candidates = [plugin_dir]
|
||
else:
|
||
candidates = [p for p in plugin_dir.iterdir()
|
||
if p.is_dir() and p.name not in EXCLUDE_DIRS
|
||
and not p.name.startswith(".")]
|
||
for base in candidates:
|
||
try:
|
||
entries = list(base.iterdir())
|
||
except OSError:
|
||
continue
|
||
for p in entries:
|
||
if p.name in roots:
|
||
if p.is_dir() and (p / "__init__.py").is_file():
|
||
hits.append(str(p.relative_to(plugin_dir)).replace("\\", "/") + "/")
|
||
elif p.is_file() and p.suffix == ".py":
|
||
hits.append(str(p.relative_to(plugin_dir)).replace("\\", "/"))
|
||
return hits
|
||
|
||
|
||
def run_import(plugin_dir: Path, sdk: SdkInfo, python: str, webhost: str, timeout: int):
|
||
"""子进程真实加载插件包(等价宿主 load_plugins 的 import 行为)。"""
|
||
cmd = [python, "-c", _IMPORT_SCRIPT, str(plugin_dir), webhost or "", str(sdk.root)]
|
||
return _run(cmd, plugin_dir, timeout)
|
||
|
||
|
||
def run_selftest(plugin_dir: Path, sdk: SdkInfo, python: str, webhost: str, timeout: int):
|
||
script = plugin_dir / "_selftest.py"
|
||
if not script.is_file():
|
||
return None
|
||
cmd = [python, "-c", _SELFTEST_SCRIPT, str(plugin_dir), webhost or "", str(sdk.root)]
|
||
return _run(cmd, plugin_dir, timeout)
|
||
|
||
|
||
def _run(cmd, cwd: Path, timeout: int):
|
||
env = {k: v for k, v in os.environ.items()
|
||
if k not in ("GS_CONN", "PLATFORM_ACCOUNT", "GS_WCF_URL", "HOTEL_WCF_URL")}
|
||
env.update({"PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8", "SDK_COMPAT_CHECK": "1"})
|
||
try:
|
||
proc = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True,
|
||
encoding="utf-8", errors="replace", timeout=timeout, env=env)
|
||
except subprocess.TimeoutExpired:
|
||
return False, f"超时(>{timeout}s)"
|
||
if proc.returncode == 0:
|
||
return True, ""
|
||
tail = (proc.stderr or proc.stdout or "").strip().splitlines()
|
||
return False, " | ".join(tail[-3:])[:400]
|
||
|
||
|
||
def _f(code: str, severity: str, message: str, **kw) -> dict:
|
||
d = {"code": code, "severity": severity, "message": message}
|
||
d.update({k: v for k, v in kw.items() if v not in (None, "")})
|
||
return d
|
||
|
||
|
||
# ---------------------------------------------------------------- 汇总/分类
|
||
def classify(sdk_errors: list, findings_by_plugin: dict, sdk_ver: str,
|
||
baseline_ver: str, api_removed: bool = False) -> str:
|
||
if sdk_errors:
|
||
return "SDK_INVALID"
|
||
errs = [f for fl in findings_by_plugin.values() for f in fl if f["severity"] == "error"]
|
||
if not errs and not api_removed:
|
||
return "COMPATIBLE"
|
||
codes = {f["code"] for f in errs}
|
||
# 没有 baseline 时按"同 major"处理(此时只能靠 compat 判断,是最保守的假设)
|
||
same_major = True
|
||
if baseline_ver:
|
||
same_major = sdk_ver.split(".")[0] == baseline_ver.split(".")[0]
|
||
if not same_major:
|
||
return "PLUGIN_BUMP"
|
||
# 同 major(minor/patch)下出现"删 API / 导入失败 / 自测失败"→ SDK 破坏了兼容
|
||
if api_removed or (codes & _BREAK_SIGNALS):
|
||
return "ACCIDENTAL_BREAK"
|
||
# 只剩插件侧问题(NEEDS_BUMP / UNDECLARED_SDK / COMPAT_INVALID)→ 升插件即可
|
||
return "PLUGIN_BUMP"
|
||
|
||
|
||
EXIT_BY_CLASS = {"COMPATIBLE": 0, "PLUGIN_BUMP": 1, "ACCIDENTAL_BREAK": 1, "SDK_INVALID": 2}
|
||
|
||
|
||
def check(args) -> dict:
|
||
sdk = load_sdk(args.sdk)
|
||
baseline = None
|
||
sdk_errors = sdk_side_findings(sdk, args.python, args.runtime_version)
|
||
if args.baseline_sdk:
|
||
try:
|
||
baseline = load_sdk(args.baseline_sdk)
|
||
except SdkInvalid as e:
|
||
sdk_errors.append(_f("SDK_INVALID", "error", f"baseline SDK 非法:{e}"))
|
||
|
||
# baseline API diff
|
||
api_diff = {"added": [], "removed": [], "changed": []}
|
||
api_findings: list = []
|
||
if baseline:
|
||
old = set(baseline.modules)
|
||
new = set(sdk.modules)
|
||
api_diff["added"] = sorted(new - old)
|
||
removed = sorted(old - new)
|
||
for mod in sorted(old & new):
|
||
lost = set((baseline.modules[mod].get("exports") or [])) - set(
|
||
(sdk.modules[mod].get("exports") or []))
|
||
removed.extend(f"{mod}.{name}" for name in sorted(lost))
|
||
api_diff["removed"] = removed
|
||
# 同名但签名变了:minor/patch 下通常是"加了必填参数/换了参数含义",属软破坏 → warning
|
||
for mod in sorted(old & new):
|
||
old_sigs = baseline.modules[mod].get("signatures") or {}
|
||
new_sigs = sdk.modules[mod].get("signatures") or {}
|
||
for name in sorted(old_sigs):
|
||
if name in new_sigs and new_sigs[name] != old_sigs[name]:
|
||
api_diff["changed"].append(f"{mod}.{name}")
|
||
if api_diff["changed"]:
|
||
api_findings.append(_f(
|
||
"API_SIGNATURE_CHANGED", "warning",
|
||
f"函数签名变化:{', '.join(api_diff['changed'][:6])}"
|
||
+ ("…" if len(api_diff["changed"]) > 6 else ""),
|
||
suggestion="确认调用方仍兼容;破坏性变更请发 major"))
|
||
if removed and baseline.version.split(".")[0] == sdk.version.split(".")[0]:
|
||
# 注意:这是"兼容性破坏",不是"包非法"——分类走 ACCIDENTAL_BREAK(exit 1)
|
||
api_findings.append(_f(
|
||
"API_REMOVED", "error",
|
||
f"同 major 下删除了 API:{', '.join(removed[:8])}"
|
||
+ ("…" if len(removed) > 8 else ""),
|
||
suggestion="minor/patch 必须向后兼容;不改回就把版本升成 major"))
|
||
|
||
plugins = discover_plugins(args.plugins, _csv(args.only), _csv(args.exclude))
|
||
rows = []
|
||
for p in plugins:
|
||
pid = str((p["manifest"] or {}).get("id") or p["dir"].name)
|
||
fl, scan = check_plugin(p, sdk)
|
||
declared = ((p["manifest"] or {}).get("requires") or {}).get("sdks") or {}
|
||
# 只对"真的用到这个 SDK"的插件做导入/自测(否则 26 个无关插件也要各起一个子进程)
|
||
uses = (sdk.id in declared) or bool(scan["modules"]) or bool(scan["dynamic"])
|
||
|
||
# 壳子 PluginPage:ui:false 只有「运行日志/历史运行」两个 tab,
|
||
# 插件界面(参数表单 + 执行按钮)整个不渲染 —— 等于人工跑不了。
|
||
# 用本 SDK 的插件若没界面 → 直接 error 拦发版;无关插件只给提醒。
|
||
if not (p["manifest"] or {}).get("ui"):
|
||
fl.append(_f("NO_UI", "error" if uses else "warning",
|
||
"plugin.json 未声明 ui:true:壳子里没有「插件界面」tab,无法提交参数或触发执行",
|
||
file="plugin.json",
|
||
suggestion="补 ui-src(Vue3 + Element Plus,见 docs/插件/插件UI开发规范.md §1)并构建 ui/"))
|
||
|
||
if uses and not args.skip_import:
|
||
ok, detail = run_import(p["dir"], sdk, args.python, args.webhost, args.timeout)
|
||
if not ok:
|
||
fl.append(_f("IMPORT_FAIL", "error", f"插件导入失败:{detail}"))
|
||
if not args.skip_selftest and uses:
|
||
res = run_selftest(p["dir"], sdk, args.python, args.webhost, args.timeout)
|
||
if res is None:
|
||
dep = [d for d in declared if d == sdk.id]
|
||
if dep:
|
||
fl.append(_f("SELFTEST_MISSING", "warning", "插件无 _selftest.py,建议补"))
|
||
elif not res[0]:
|
||
fl.append(_f("SELFTEST_FAIL", "error", f"_selftest 失败:{res[1]}"))
|
||
|
||
if not uses and not fl:
|
||
rows.append({"id": pid, "status": "SKIP", "findings": []})
|
||
continue
|
||
has_err = any(f["severity"] == "error" for f in fl)
|
||
rows.append({
|
||
"id": pid,
|
||
"version": str((p["manifest"] or {}).get("version") or ""),
|
||
"dir": str(p["dir"]),
|
||
"declared": declared,
|
||
"status": "FAIL" if has_err else ("WARN" if fl else "PASS"),
|
||
"findings": fl,
|
||
})
|
||
|
||
checked = [r for r in rows if r["status"] != "SKIP"]
|
||
by_plugin = {r["id"]: r["findings"] for r in checked}
|
||
klass = classify(sdk_errors, by_plugin, sdk.version,
|
||
baseline.version if baseline else "", bool(api_findings))
|
||
exit_code = EXIT_BY_CLASS[klass]
|
||
|
||
report = {
|
||
"schema_version": 1,
|
||
"tool_version": TOOL_VERSION,
|
||
"sdk": {"id": sdk.id, "version": sdk.version, "path": sdk.source,
|
||
"baseline": baseline.version if baseline else ""},
|
||
"python": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||
"runtime_version": args.runtime_version,
|
||
"classification": klass,
|
||
"exit_code": exit_code,
|
||
"summary": {
|
||
"plugins_total": len(rows),
|
||
"checked": len(checked),
|
||
"skipped": len(rows) - len(checked),
|
||
"pass": sum(1 for r in checked if r["status"] == "PASS"),
|
||
"warn": sum(1 for r in checked if r["status"] == "WARN"),
|
||
"fail": sum(1 for r in checked if r["status"] == "FAIL"),
|
||
"errors": len([f for r in checked for f in r["findings"] if f["severity"] == "error"])
|
||
+ len([f for f in sdk_errors if f["severity"] == "error"])
|
||
+ len([f for f in api_findings if f["severity"] == "error"]),
|
||
"warnings": len([f for r in checked for f in r["findings"] if f["severity"] == "warning"]),
|
||
},
|
||
"sdk_findings": sdk_errors + api_findings,
|
||
"api_diff": api_diff,
|
||
"plugins": rows,
|
||
}
|
||
if sdk.tmp:
|
||
shutil.rmtree(sdk.tmp, ignore_errors=True)
|
||
if baseline and baseline.tmp:
|
||
shutil.rmtree(baseline.tmp, ignore_errors=True)
|
||
return report
|
||
|
||
|
||
# ---------------------------------------------------------------- 输出
|
||
def render_md(rep: dict) -> str:
|
||
s = rep["summary"]
|
||
lines = [f"# SDK 兼容预检:{rep['sdk']['id']} {rep['sdk']['version']}", ""]
|
||
verdict = {
|
||
"COMPATIBLE": "COMPATIBLE(插件无需改动,SDK 可单独发版)",
|
||
"PLUGIN_BUMP": "PLUGIN_BUMP(只有列出的插件需要升 compat/改代码,与 SDK 同批发)",
|
||
"ACCIDENTAL_BREAK": "ACCIDENTAL_BREAK(本应兼容却破坏 → 拒绝发布,修 SDK 或改 major)",
|
||
"SDK_INVALID": "SDK_INVALID(SDK 包/清单本身非法,先修包)",
|
||
}[rep["classification"]]
|
||
lines += [f"**结论:{verdict}**", "",
|
||
f"- SDK {rep['sdk']['version']}(baseline {rep['sdk']['baseline'] or '未提供'}),"
|
||
f"解释器 {rep['python']}",
|
||
f"- 插件:检查 {s['checked']},通过 {s['pass']},警告 {s['warn']},"
|
||
f"失败 {s['fail']},跳过 {s['skipped']}",
|
||
f"- error {s['errors']},warning {s['warnings']}", ""]
|
||
problems = [r for r in rep["plugins"] if r["status"] == "FAIL"]
|
||
lines.append("## 需要处理的插件" + ("(无)" if not problems else ""))
|
||
for r in problems:
|
||
lines.append(f"### {r['id']} {r.get('version', '')}")
|
||
for f in r["findings"]:
|
||
if f["severity"] != "error":
|
||
continue
|
||
loc = f"{f.get('file', '')}:{f.get('line', '')}" if f.get("file") else ""
|
||
lines.append(f"- `{f['code']}` {f['message']} {loc}".rstrip())
|
||
if f.get("suggestion"):
|
||
lines.append(f" - 建议:{f['suggestion']}")
|
||
warnings = [(r["id"], f) for r in rep["plugins"] for f in r["findings"] if f["severity"] == "warning"]
|
||
if warnings:
|
||
lines += ["", "## 警告", "| 插件 | 代码 | 说明 |", "|---|---|---|"]
|
||
for pid, f in warnings:
|
||
lines.append(f"| {pid} | {f['code']} | {f['message']} |")
|
||
if rep["sdk_findings"]:
|
||
lines += ["", "## SDK 自身问题"]
|
||
for f in rep["sdk_findings"]:
|
||
lines.append(f"- `{f['code']}` {f['message']}")
|
||
diff = rep["api_diff"]
|
||
if diff["added"] or diff["removed"] or diff.get("changed"):
|
||
lines += ["", "## API 变更"]
|
||
lines.append("- 新增:" + (", ".join(diff["added"]) or "无"))
|
||
lines.append("- 移除:" + (", ".join(diff["removed"]) or "无"))
|
||
lines.append("- 签名变化:" + (", ".join(diff.get("changed") or []) or "无"))
|
||
return "\n".join(lines) + "\n"
|
||
|
||
|
||
def console_line(rep: dict) -> str:
|
||
s = rep["summary"]
|
||
base = (f"[{rep['classification']}] {rep['sdk']['id']} {rep['sdk']['version']} | "
|
||
f"plugins {s['checked']} checked, {s['pass']} pass, {s['warn']} warn, "
|
||
f"{s['fail']} fail, {s['skipped']} skipped | exit {rep['exit_code']}")
|
||
if rep["classification"] in ("PLUGIN_BUMP", "ACCIDENTAL_BREAK"):
|
||
bad = [r["id"] for r in rep["plugins"] if r["status"] == "FAIL"]
|
||
first = next((f for r in rep["plugins"] for f in r["findings"] if f["severity"] == "error"), None)
|
||
base += f" | {', '.join(bad[:6])}"
|
||
if first:
|
||
base += f" | {first['code']} in {first['message'][:60]}"
|
||
return base
|
||
|
||
|
||
def _csv(text: str) -> set:
|
||
return {s.strip() for s in str(text or "").split(",") if s.strip()}
|
||
|
||
|
||
def build_parser() -> argparse.ArgumentParser:
|
||
ap = argparse.ArgumentParser(
|
||
description="SDK 兼容预检(发版门禁)",
|
||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||
ap.add_argument("--sdk", required=True, help="SDK 目录或 dist-sdk/<id>_v<ver>.zip")
|
||
ap.add_argument("--plugins", default=str(REPO_ROOT / "plugins"), help="插件根目录")
|
||
ap.add_argument("--python", default=sys.executable, help="执行插件导入/自测的解释器")
|
||
ap.add_argument("--webhost", default=str(REPO_ROOT / "desktop" / "electron-shell" / "python"),
|
||
help="webhost 包所在目录(插件 import webhost.backend... 需要)")
|
||
ap.add_argument("--baseline-sdk", default="", help="上一版 SDK(目录/zip),用于 API diff")
|
||
ap.add_argument("--runtime-version", default="", help="当前壳版本,用于 minRuntimeVersion 检查")
|
||
ap.add_argument("--only", default="", help="只检查这些插件 id(逗号分隔)")
|
||
ap.add_argument("--exclude", default="", help="排除这些插件 id(逗号分隔)")
|
||
ap.add_argument("--timeout", type=int, default=60, help="单插件导入/自测超时(秒)")
|
||
ap.add_argument("--skip-import", action="store_true", help="跳过子进程导入检查")
|
||
ap.add_argument("--skip-selftest", action="store_true", help="跳过插件 _selftest")
|
||
ap.add_argument("--json", default="", help="JSON 报告输出路径(- = stdout)")
|
||
ap.add_argument("--md", default="", help="Markdown 报告输出路径")
|
||
ap.add_argument("--verbose", action="store_true", help="打印每个插件的检查结论")
|
||
return ap
|
||
|
||
|
||
def main(argv=None) -> int:
|
||
args = build_parser().parse_args(argv)
|
||
try:
|
||
rep = check(args)
|
||
except SdkInvalid as e:
|
||
print(f"[SDK_INVALID] {e}", file=sys.stderr)
|
||
return 2
|
||
except Exception as e: # noqa: BLE001
|
||
import traceback
|
||
traceback.print_exc()
|
||
print(f"[TOOL_ERROR] {e}", file=sys.stderr)
|
||
return 3
|
||
|
||
print(console_line(rep))
|
||
if args.verbose:
|
||
for r in rep["plugins"]:
|
||
print(f" {r['id']:<12}{r['status']:<6}"
|
||
f"{','.join(sorted({f['code'] for f in r['findings']})) }")
|
||
if args.md:
|
||
Path(args.md).parent.mkdir(parents=True, exist_ok=True)
|
||
Path(args.md).write_text(render_md(rep), encoding="utf-8")
|
||
print(f"Markdown 报告:{args.md}")
|
||
if args.json:
|
||
text = json.dumps(rep, ensure_ascii=False, indent=2)
|
||
if args.json == "-":
|
||
print(text)
|
||
else:
|
||
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
|
||
Path(args.json).write_text(text, encoding="utf-8")
|
||
print(f"JSON 报告:{args.json}")
|
||
return rep["exit_code"]
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|