feat: 同步 LightCore 应用后台 CLI
This commit is contained in:
@@ -7,16 +7,22 @@ import re
|
||||
import subprocess
|
||||
|
||||
from .api import format_response
|
||||
from .shop_visual import render
|
||||
from .system_client import LOGIN_PATH, LOGOUT_PATH
|
||||
from .system_routes import GROUPS
|
||||
from .system_schema import REQUESTS
|
||||
from .transport import ClientError, MultipartBody, compact, private_output, reject_constant
|
||||
|
||||
|
||||
PRIVATE_INPUT_FIELDS = {"accessKey", "accessKeyId", "accessKeySecret", "secretKey", "oldPassword", "newPassword"}
|
||||
PRIVATE_INPUT_FIELDS = {
|
||||
"accessKey", "accessKeyId", "accessKeySecret", "apiKey", "clientSecret", "secretKey",
|
||||
"password", "oldPassword", "newPassword", "token",
|
||||
}
|
||||
|
||||
|
||||
def example_value(name, field):
|
||||
if "type" not in field:
|
||||
return {}
|
||||
if "const" in field:
|
||||
return field["const"]
|
||||
if "default" in field:
|
||||
@@ -28,11 +34,13 @@ def example_value(name, field):
|
||||
if field["type"] == "array":
|
||||
return [example_value(name, field["items"])]
|
||||
if field["type"] == "object":
|
||||
return {key: example_value(key, spec) for key, spec in field["properties"].items()}
|
||||
return {key: example_value(key, spec) for key, spec in field.get("properties", {}).items()}
|
||||
if field["type"] == "integer":
|
||||
return 600 if name == "ttl" else field.get("minimum", 1)
|
||||
if field["type"] == "boolean":
|
||||
return True
|
||||
if field["type"] == "number":
|
||||
return field.get("minimum", 0.0)
|
||||
examples = {"uuid": "0198d956-1111-4444-8888-111111111111", "uri": "https://example.com/",
|
||||
"email": "admin@example.com", "binary": "example.png"}
|
||||
if field.get("format") in examples:
|
||||
@@ -60,14 +68,28 @@ def request_body(args):
|
||||
if flags:
|
||||
raise ClientError("--body-file 与字段参数只能选择一种。")
|
||||
try:
|
||||
body = json.loads(args.body_file.read_text(encoding="utf-8-sig"), parse_constant=reject_constant)
|
||||
with args.body_file.open("rb") as stream:
|
||||
raw = stream.read((8 << 20) + 1)
|
||||
if len(raw) > 8 << 20:
|
||||
raise ClientError("请求文件不能超过 8 MiB。")
|
||||
body = json.loads(raw.decode("utf-8-sig"), parse_constant=reject_constant,
|
||||
object_pairs_hook=unique_fields)
|
||||
except ValueError:
|
||||
raise ClientError("请求正文必须是有效 JSON 对象。") from None
|
||||
raise ClientError("请求正文必须是有效且无重复字段的 JSON 对象。") from None
|
||||
if not isinstance(body, dict):
|
||||
raise ClientError("请求正文必须是 JSON 对象。")
|
||||
return body
|
||||
|
||||
|
||||
def unique_fields(pairs):
|
||||
fields = {}
|
||||
for key, value in pairs:
|
||||
if key in fields:
|
||||
raise ValueError("duplicate JSON field")
|
||||
fields[key] = value
|
||||
return fields
|
||||
|
||||
|
||||
def save_private_json(args, data, details):
|
||||
target = args.output.absolute()
|
||||
try:
|
||||
@@ -82,60 +104,94 @@ def call(client, args):
|
||||
if args.output is not None and (args.output.exists() or args.output.is_symlink()):
|
||||
raise ClientError("目标文件已存在,拒绝覆盖。")
|
||||
body = request_body(args)
|
||||
if getattr(args, "dry_run", False):
|
||||
body["dryRun"] = True
|
||||
client.remember_secrets(body)
|
||||
payload = (MultipartBody(args.file, body) if args.mode == "upload" else compact(body).encode("utf-8"))
|
||||
response = client.exchange(args.endpoint, payload, output=args.output if args.mode == "zip" else None)
|
||||
if client.app == "shop" and args.endpoint in (
|
||||
"/general/agentPublicFile/importFile", "/content/workspaceAgent/importAttachment",
|
||||
) and isinstance(body.get("url"), str):
|
||||
client.secrets.append(body["url"])
|
||||
if args.mode == "render":
|
||||
return render(client, args, body)
|
||||
if args.mode == "metadata-upload":
|
||||
payload = MultipartBody(args.file, {"metadata": compact(body)}, reject_symlink=True)
|
||||
elif args.mode == "upload":
|
||||
payload = MultipartBody(args.file, body, reject_symlink=client.app == "shop")
|
||||
else:
|
||||
payload = compact(body).encode("utf-8")
|
||||
try:
|
||||
response = client.exchange(args.endpoint, payload, output=args.output if args.mode in ("zip", "download") else None)
|
||||
except ClientError as error:
|
||||
if "结果未知" in str(error):
|
||||
meta = body.get("meta")
|
||||
request_id = body.get("requestId") or (meta.get("requestId") if isinstance(meta, dict) else None)
|
||||
if request_id:
|
||||
error.details["requestId"] = request_id
|
||||
if body.get("idempotencyKey"):
|
||||
error.details["idempotencyKey"] = body["idempotencyKey"]
|
||||
raise
|
||||
if response.get("downloaded"):
|
||||
return response
|
||||
details = {key: response[key] for key in ("httpStatus", "code", "traceId")}
|
||||
if args.mode in ("zip", "private-output"):
|
||||
if args.mode in ("zip", "download", "private-output"):
|
||||
if not client.success(response):
|
||||
message = (response["json"] or {}).get("msg") if isinstance(response["json"], dict) else None
|
||||
raise ClientError(message or "System 请求失败。", **details)
|
||||
if args.mode == "zip":
|
||||
raise ClientError("System 响应未包含证书 ZIP。", **details)
|
||||
raise ClientError(message or "请求失败。", **details)
|
||||
if args.mode in ("zip", "download"):
|
||||
raise ClientError("响应未包含可下载文件。", **details)
|
||||
data = response["json"].get("data")
|
||||
if not isinstance(data, dict) or not data:
|
||||
raise ClientError("System 响应未包含所需数据。", **details)
|
||||
raise ClientError("响应未包含所需数据。", **details)
|
||||
return save_private_json(args, data, details)
|
||||
if args.endpoint == "/user/updatePassword" and client.success(response):
|
||||
data = response["json"].get("data")
|
||||
if not isinstance(data, dict) or data.get("success") is not True:
|
||||
message = (data or {}).get("message") if isinstance(data, dict) else None
|
||||
raise ClientError(message or "System 密码修改失败。", **details)
|
||||
return format_response(client, response, Path.cwd() / ".work" / "lightcore" / "system", args.max_chars)
|
||||
return format_response(client, response, Path.cwd() / ".work" / "lightcore" / client.app, args.max_chars)
|
||||
|
||||
|
||||
def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=None):
|
||||
def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=None, *, schema=None):
|
||||
command = actions.add_parser(name, help=summary, description=summary, allow_abbrev=False)
|
||||
request = REQUESTS[request_type] if request_type else {"properties": {}, "required": []}
|
||||
schema = {"type": "object", **request}
|
||||
if schema is None:
|
||||
request = REQUESTS[request_type] if request_type else {"properties": {}, "required": []}
|
||||
schema = {"type": "object", **request}
|
||||
private_input = bool(PRIVATE_INPUT_FIELDS.intersection(schema["properties"]))
|
||||
inputs = command.add_mutually_exclusive_group(required=private_input)
|
||||
inputs.add_argument("--schema", action=ShowRequest, nargs=0, help="离线查看请求字段、类型和约束")
|
||||
inputs.add_argument("--example", action=ShowRequest, nargs=0, help="离线生成示例请求")
|
||||
if mode == "upload":
|
||||
if mode in ("upload", "metadata-upload"):
|
||||
command.add_argument("--file", type=Path, required=True, help="上传的本机文件")
|
||||
else:
|
||||
if mode != "upload" or schema["properties"].keys() - {"file"}:
|
||||
label = "本机私有 JSON 输入文件" if private_input else "UTF-8 JSON 请求文件"
|
||||
inputs.add_argument("--body-file", type=Path, help=label)
|
||||
if mode in ("zip", "private-output"):
|
||||
if mode in ("zip", "download", "private-output"):
|
||||
command.add_argument("--output", type=Path, required=True, help="私有输出路径,拒绝覆盖")
|
||||
if mode == "render":
|
||||
command.add_argument("--output-dir", dest="output", type=Path, required=True, help="私有视觉包输出目录")
|
||||
command.add_argument("--renderer", type=Path, help="本地 light 可执行文件路径")
|
||||
fields = []
|
||||
if not private_input:
|
||||
for field, spec in schema["properties"].items():
|
||||
value_type = spec["type"]
|
||||
value_type = spec.get("type")
|
||||
if isinstance(value_type, list):
|
||||
value_type = value_type[0]
|
||||
if field == "file" or value_type not in ("string", "integer", "boolean"):
|
||||
repeated = value_type == "array"
|
||||
if repeated:
|
||||
value_type = spec.get("items", {}).get("type")
|
||||
if field in ("file", "dryRun") or value_type not in ("string", "integer", "number", "boolean"):
|
||||
continue
|
||||
flag = "--" + re.sub(r"[A-Z]", lambda hit: "-" + hit[0].lower(), field)
|
||||
label = f"JSON 字段 {field}"
|
||||
if field in schema["required"] and "default" not in spec:
|
||||
label += ",必填"
|
||||
options = {"dest": field, "help": label}
|
||||
if repeated:
|
||||
options.update(action="append", help=f"{label},可重复指定")
|
||||
if value_type == "integer":
|
||||
options["type"] = int
|
||||
if value_type == "number":
|
||||
options["type"] = float
|
||||
if value_type == "boolean":
|
||||
options.update(type=parse_bool, metavar="true|false")
|
||||
if "enum" in spec:
|
||||
@@ -146,6 +202,8 @@ def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=N
|
||||
fields.append(field)
|
||||
command.set_defaults(handler=call, endpoint=f"{prefix}/{endpoint}" if prefix else endpoint,
|
||||
mode=mode, request_schema=schema, output=None, body_file=None, fields=fields)
|
||||
if "dryRun" in schema["properties"]:
|
||||
command.add_argument("--dry-run", action="store_true", help="只预检输入与状态")
|
||||
|
||||
|
||||
def parse_bool(value):
|
||||
|
||||
Reference in New Issue
Block a user