restore: 恢复 11-06~11-09 本地未提交改动
- 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)
This commit is contained in:
+196
-5
@@ -49,6 +49,8 @@ import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
@@ -197,6 +199,27 @@ class Client:
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
def upload_sdk(self, path: str, sdk_id: str, name: str, version: str,
|
||||
channel: str = "test") -> dict:
|
||||
"""上传 SDK 包(POST /api/admin/sdk-pkg,服务端校验 sdk.json 并算 sha256)。"""
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"sdk_id": sdk_id, "name": name,
|
||||
"version": version, "channel": channel})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/sdk-pkg?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/zip")},
|
||||
timeout=60)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
def shell_release(self, path: str, version: str, notes: str, sha256: str = "") -> dict:
|
||||
"""上传壳子新版安装包到中心机(管理接口,缺省 sha256 由服务端计算并写 version.json)。"""
|
||||
import requests
|
||||
@@ -218,16 +241,63 @@ class Client:
|
||||
|
||||
|
||||
# ------------------------------ 输出辅助 ------------------------------
|
||||
def _read_zip_json(path: str, entry: str) -> dict:
|
||||
"""读取 zip 内某个 JSON 文件(缺文件/解析失败返回 {},不阻断打包产物校验由服务端负责)。"""
|
||||
import zipfile
|
||||
try:
|
||||
with zipfile.ZipFile(path) as zf:
|
||||
return json.loads(zf.read(entry).decode("utf-8").lstrip("\ufeff"))
|
||||
except (KeyError, OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def _sdk_precheck(pkg: str, plugins: str = "", baseline: str = "", python: str = "") -> int:
|
||||
"""发布前跑兼容预检(tools/sdk_compat_check.py),返回其退出码(0=可发布)。"""
|
||||
tool = TOOLS_DIR / "sdk_compat_check.py"
|
||||
if not tool.is_file():
|
||||
print(f"[!] 未找到预检工具 {tool},跳过预检(建议补齐后再发布 SDK)")
|
||||
return 0
|
||||
cmd = [python or sys.executable, str(tool), "--sdk", pkg,
|
||||
"--plugins", plugins or str(REPO_ROOT / "plugins")]
|
||||
if baseline:
|
||||
cmd += ["--baseline-sdk", baseline]
|
||||
proc = subprocess.run(cmd, cwd=str(REPO_ROOT), capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace", timeout=1800)
|
||||
out = (proc.stdout or "").strip()
|
||||
if out:
|
||||
print(out)
|
||||
if proc.returncode not in (0, 1, 2):
|
||||
print((proc.stderr or "").strip()[:800])
|
||||
return proc.returncode
|
||||
|
||||
|
||||
def _sha256_file(path: str) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as fp:
|
||||
for chunk in iter(lambda: fp.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _print_json(obj) -> None:
|
||||
"""输出 JSON;控制台编码装不下(如名称带 ⓪ 等字符)时退回 ASCII 转义,保证仍是合法 JSON。"""
|
||||
text = json.dumps(obj, ensure_ascii=False, indent=2)
|
||||
try:
|
||||
print(text)
|
||||
except UnicodeEncodeError:
|
||||
print(json.dumps(obj, ensure_ascii=True, indent=2))
|
||||
|
||||
|
||||
def _emit(args: argparse.Namespace, obj: dict, human: str) -> None:
|
||||
"""--json 时输出机器可读 JSON,否则输出人类可读文本。"""
|
||||
if getattr(args, "json", False):
|
||||
print(json.dumps(obj, ensure_ascii=False, indent=2))
|
||||
_print_json(obj)
|
||||
else:
|
||||
print(human)
|
||||
|
||||
|
||||
def _plugin_rows(plugins) -> None:
|
||||
"""overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。"""
|
||||
"""插件清单(含版本/授权明细),此处只打印核心字段。"""
|
||||
rows = plugins if isinstance(plugins, list) else \
|
||||
(list(plugins.values()) if isinstance(plugins, dict) else [])
|
||||
if not rows:
|
||||
@@ -242,6 +312,30 @@ def _plugin_rows(plugins) -> None:
|
||||
f"{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
def fetch_plugins(c: Client) -> list:
|
||||
"""取插件清单(含每个插件的已授权账号 accounts)。
|
||||
|
||||
必须走 /api/admin/plugins:/api/admin/overview 不返回 accounts,
|
||||
用它统计「账号数」会一律显示 0(旧实现踩过这个坑)。
|
||||
"""
|
||||
try:
|
||||
rows, page = [], 1
|
||||
while page <= 50:
|
||||
d = c.call("GET", f"/api/admin/plugins?page={page}&page_size=200")
|
||||
items = d.get("items") or []
|
||||
rows.extend(items)
|
||||
if not items or len(rows) >= int(d.get("total") or 0):
|
||||
break
|
||||
page += 1
|
||||
return rows
|
||||
except SystemExit:
|
||||
# 兼容旧中心机:退回 overview(无 accounts,账号数会显示 0)
|
||||
print("[!] /api/admin/plugins 不可用,退回 overview(账号数不可信)", file=sys.stderr)
|
||||
d = c.call("GET", "/api/admin/overview")
|
||||
p = d.get("plugins", {})
|
||||
return p if isinstance(p, list) else list(p.values())
|
||||
|
||||
|
||||
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||
"""file push / list / rm:内网大文件源管理。"""
|
||||
try:
|
||||
@@ -364,6 +458,34 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
p_pub.add_argument("--prod", action="store_true",
|
||||
help="直发正式通道(跳过测试,全量已授权账号立即升级;默认走测试通道)")
|
||||
|
||||
p_sdk_pub = sub.add_parser("sdk-publish", help="发布 SDK 包 zip(默认进测试通道,仅管理员账号可同步)")
|
||||
p_sdk_pub.add_argument("pkg", help="SDK zip 路径(dist-sdk/<id>_v<ver>.zip)")
|
||||
p_sdk_pub.add_argument("--id", dest="sdk_id", default="",
|
||||
help="SDK ID(缺省读包内 sdk.json 的 id)")
|
||||
p_sdk_pub.add_argument("--version", default="",
|
||||
help="版本号(缺省读包内 sdk.json 的 version)")
|
||||
p_sdk_pub.add_argument("--name", default="", help="SDK 名称(缺省取 sdk.json 内 name)")
|
||||
p_sdk_pub.add_argument("--prod", action="store_true",
|
||||
help="直发正式通道(默认测试通道;正式发版须先预检 + 人工验证)")
|
||||
p_sdk_pub.add_argument("--plugins", default="",
|
||||
help="预检用的插件根(默认仓库 plugins/)")
|
||||
p_sdk_pub.add_argument("--baseline-sdk", default="",
|
||||
help="上一版 SDK 目录/zip(minor/patch 发版建议必传,用于 API diff)")
|
||||
p_sdk_pub.add_argument("--skip-check", action="store_true", help="跳过兼容预检(不推荐)")
|
||||
p_sdk_pub.add_argument("--force", action="store_true",
|
||||
help="预检不通过也发布(仅限紧急热修,需人工确认)")
|
||||
|
||||
sub.add_parser("sdks", help="列出 SDK 清单(含版本历史与可用版本)")
|
||||
|
||||
p_sdk_status = sub.add_parser("sdk-status", help="变更 SDK 状态(published 即把在测版本转正)")
|
||||
p_sdk_status.add_argument("sdk_id")
|
||||
p_sdk_status.add_argument("--status", choices=["published", "testing", "disabled", "revoked"], default="",
|
||||
help="published=转正并全量生效 / testing=回到测试通道 / disabled / revoked")
|
||||
|
||||
p_sdk_yank = sub.add_parser("sdk-yank", help="撤回某个 SDK 版本(执行机自动回落上一可用版本)")
|
||||
p_sdk_yank.add_argument("sdk_id")
|
||||
p_sdk_yank.add_argument("--version", required=True, help="要撤回的版本号")
|
||||
|
||||
sub.add_parser("plugins", help="列出插件清单")
|
||||
|
||||
p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)")
|
||||
@@ -511,10 +633,9 @@ def _run(args: argparse.Namespace) -> int:
|
||||
f" 已授权账号下次同步即升级(跳过了测试通道)。")
|
||||
|
||||
elif cmd == "plugins":
|
||||
data = c.call("GET", "/api/admin/overview")
|
||||
rows = data.get("plugins", {})
|
||||
rows = fetch_plugins(c)
|
||||
if args.json:
|
||||
print(json.dumps(rows, ensure_ascii=False, indent=2))
|
||||
_print_json(rows)
|
||||
else:
|
||||
_plugin_rows(rows)
|
||||
|
||||
@@ -535,6 +656,76 @@ def _run(args: argparse.Namespace) -> int:
|
||||
r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body)
|
||||
_emit(args, {"ok": True, **r}, "[ok] " + json.dumps(r, ensure_ascii=False))
|
||||
|
||||
elif cmd == "sdk-publish":
|
||||
meta = _read_zip_json(args.pkg, "sdk.json")
|
||||
sid = (args.sdk_id or str(meta.get("id") or "")).strip()
|
||||
ver = (args.version or str(meta.get("version") or "")).strip()
|
||||
name = (args.name or str(meta.get("name") or "")).strip() or sid
|
||||
if not sid or not ver:
|
||||
raise SystemExit("[x] 缺少 sdk_id/version:包内 sdk.json 未提供,请显式传 --id / --version")
|
||||
channel = "prod" if getattr(args, "prod", False) else "test"
|
||||
# 发版门禁:先预检所有插件在新 SDK 下的声明/API/导入/自测
|
||||
if not getattr(args, "skip_check", False):
|
||||
rc = _sdk_precheck(args.pkg, args.plugins, args.baseline_sdk)
|
||||
if rc == 2:
|
||||
raise SystemExit("[x] SDK 包非法(预检退出码 2),已拒绝发布。")
|
||||
if rc == 1:
|
||||
if not getattr(args, "force", False):
|
||||
raise SystemExit(
|
||||
"[x] 兼容预检未通过(退出码 1):按上面的清单升级受影响插件的 compat/代码后重跑;\n"
|
||||
" 确属紧急热修并已人工确认时,可加 --force 强制发布(请同步记录风险)。")
|
||||
print("[!] 已按 --force 忽略预检失败继续发布,请在发布说明中注明。")
|
||||
local_sha = _sha256_file(args.pkg)
|
||||
r = c.upload_sdk(args.pkg, sid, name, ver, channel)
|
||||
if channel == "test":
|
||||
_emit(args, {"ok": True, "sdk_id": r.get("sdk_id"), "version": r.get("version"),
|
||||
"channel": "test", "status": r.get("status"),
|
||||
"test_version": r.get("test_version"), "filename": r.get("filename"),
|
||||
"sha256": r.get("sha256", "")},
|
||||
f"[ok] 已发布测试版 SDK {r.get('sdk_id')} v{r.get('version')} → {r.get('filename')}\n"
|
||||
f" sha256={str(r.get('sha256') or local_sha)[:16]}… "
|
||||
f"状态={r.get('status') or 'testing'},仅管理员账号可同步(其他账号继续用 "
|
||||
f"v{r.get('latest_version') or '(暂无正式版)'})。\n"
|
||||
f" 验证通过后转正:sdk-status {r.get('sdk_id')} --status published")
|
||||
else:
|
||||
_emit(args, {"ok": True, "sdk_id": r.get("sdk_id"), "version": r.get("version"),
|
||||
"channel": "prod", "latest_version": r.get("latest_version"),
|
||||
"filename": r.get("filename"), "sha256": r.get("sha256", "")},
|
||||
f"[ok] 已直发正式 SDK {r.get('sdk_id')} v{r.get('version')} → {r.get('filename')}\n"
|
||||
f" sha256={str(r.get('sha256') or local_sha)[:16]}…(已授权账号下次同步即升级)")
|
||||
|
||||
elif cmd == "sdks":
|
||||
data = c.call("GET", "/api/admin/sdks")
|
||||
items = [it for it in (data.get("items") or []) if isinstance(it, dict)]
|
||||
if args.json:
|
||||
print(json.dumps({"sdks": items}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
if not items:
|
||||
print("(暂无 SDK)")
|
||||
return 0
|
||||
for s in items:
|
||||
print(f"{str(s.get('id', '')):<16}正式={s.get('latest_version') or '-'} "
|
||||
f"在测={s.get('test_version') or '-'} 状态={s.get('status')} "
|
||||
f"可用={s.get('effective_version') or '-'}")
|
||||
for v in s.get("versions") or []:
|
||||
print(f" {str(v.get('version', '')):<10}{str(v.get('status', '')):<10}"
|
||||
f"{v.get('uploaded_at', '')}")
|
||||
|
||||
elif cmd == "sdk-status":
|
||||
import urllib.parse as _q
|
||||
body = {"status": args.status} if args.status else {}
|
||||
if not body:
|
||||
raise SystemExit("[x] 请指定 --status(published/testing/disabled/revoked)")
|
||||
r = c.call("POST", f"/api/admin/sdk/patch?{_q.urlencode({'sdk_id': args.sdk_id})}", body)
|
||||
_emit(args, {"ok": True, **r},
|
||||
f"[ok] SDK {r.get('sdk_id')} 状态={r.get('status')} 正式版={r.get('latest_version') or '-'} "
|
||||
f"在测版={r.get('test_version') or '-'}")
|
||||
|
||||
elif cmd == "sdk-yank":
|
||||
r = c.call("POST", "/api/admin/sdk-yank", {"sdk_id": args.sdk_id, "version": args.version})
|
||||
_emit(args, {"ok": True, **r},
|
||||
f"[ok] 已撤回 SDK {r.get('sdk_id')} v{r.get('version')}(执行机下次同步回落到上一可用版本)")
|
||||
|
||||
elif cmd == "users":
|
||||
data = c.call("GET", "/api/admin/accounts")
|
||||
# 兼容新旧控制面响应:旧 FastAPI 返回 {"accounts": [...]},新 controlplane-next 返回 {"items": [...]}
|
||||
|
||||
Reference in New Issue
Block a user