muse-agent-example/工具/生成接口.py
zizi b86516505f W02 安装工程、启动骨架与验证环境:pyproject/uv 安装工程、启动装配骨架、conftest 用例身份与 OS 离线隔离。
按 R2 串行阶段整理提交;包内文件为该阶段交付(含后续小增量),状态以工作包清单为准。
2026-09-10 19:25:40 +08:00

65 lines
2.7 KiB
Python
Raw 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.

"""从登记的实际路由工厂生成 OpenAPI;不启动应用、不连接数据库或读取凭据。
未支持的非空输入失败,生成结果由同一公开合同产生。
"""
from __future__ import annotations
import argparse
import importlib
import json
from pathlib import Path
from typing import Any
仓库根 = Path(__file__).resolve().parent.parent
登记文件 = 仓库根 / "工具" / "生成输入.json"
def 已登记输入() -> dict[str, Any]:
"""读取生成登记;文件不存在视为空登记(如实报告,不猜测)。"""
if not 登记文件.is_file():
return {"资源": []}
数据: Any = json.loads(登记文件.read_text(encoding="utf-8"))
if not isinstance(数据, dict) or not isinstance(数据.get("资源"), list):
raise SystemExit(f"生成输入登记不合法:{登记文件}(需要 dict 含 资源 表)")
return 数据
def 主() -> int:
解析器 = argparse.ArgumentParser(description="生成 Schema、OpenAPI 和 TypeScript")
解析器.parse_args()
输入 = 已登记输入()
if not 输入["资源"]:
print("生成接口:无登记输入,未生成任何合同(业务外壳随 W04/W07 定稿后登记)")
return 0
for 条目 in 输入["资源"]:
if 条目.get("格式") != "OpenAPI" or not 条目.get("工厂") or not 条目.get("输出"):
raise SystemExit("生成接口:未接入此输入的生成器,未生成合同")
模块, 名称 = 条目["工厂"].split(":", 1)
合同 = getattr(importlib.import_module(模块), 名称)()
if not isinstance(合同, dict) or "openapi" not in 合同:
raise SystemExit("生成接口:工厂未返回 OpenAPI 合同")
输出 = 仓库根 / 条目["输出"]
输出.parent.mkdir(parents=True, exist_ok=True)
输出.write_text(json.dumps(合同, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
客户端 = 仓库根 / "web/src/接口/生成/客户端.ts"
客户端.parent.mkdir(parents=True, exist_ok=True)
客户端.write_text(
"// 由工具/生成接口.py生成;稳定外壳来自同一OpenAPI。\n"
'import createClient from "openapi-fetch";\n'
'import type { paths } from "./类型";\n'
'import { 传输 } from "../传输";\n\n'
"export const 客户端 = createClient<paths>({\n"
" baseUrl: globalThis.location.origin, fetch: 传输,\n"
' credentials: "same-origin"\n'
"});\n",
encoding="utf-8",
)
print(f"生成接口:{条目['输出']}")
return 0
if __name__ == "__main__":
raise SystemExit(主())