新增完整的 lightcore-cli 命令行工具代码,包含: - CLI 入口与参数解析 - System 和 Media 应用的客户端实现 - 丰富的子命令与操作接口 - 测试用例与项目配置 - .gitignore 与 README 文档
168 lines
8.1 KiB
Python
168 lines
8.1 KiB
Python
"""CLI entry points for the System Admin HTTP API."""
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
|
|
from .api import format_response
|
|
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"}
|
|
|
|
|
|
def example_value(name, field):
|
|
if "const" in field:
|
|
return field["const"]
|
|
if "default" in field:
|
|
return field["default"]
|
|
if "examples" in field:
|
|
return field["examples"][0]
|
|
if "enum" in field:
|
|
return field["enum"][0]
|
|
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()}
|
|
if field["type"] == "integer":
|
|
return 600 if name == "ttl" else field.get("minimum", 1)
|
|
if field["type"] == "boolean":
|
|
return True
|
|
examples = {"uuid": "0198d956-1111-4444-8888-111111111111", "uri": "https://example.com/",
|
|
"email": "admin@example.com", "binary": "example.png"}
|
|
if field.get("format") in examples:
|
|
return examples[field["format"]]
|
|
return {"rr": "www", "value": "192.0.2.1", "domains": "example.com",
|
|
"domainName": "example.com", "modules": "system", "tables": "system_admin_users"}.get(name, "示例")
|
|
|
|
|
|
class ShowRequest(argparse.Action):
|
|
def __call__(self, parser, namespace, values, option_string=None):
|
|
schema = namespace.request_schema
|
|
result = schema
|
|
if option_string == "--example":
|
|
result = {name: example_value(name, field) for name, field in schema["properties"].items()
|
|
if name in schema["required"] or "default" in field or "examples" in field}
|
|
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
parser.exit()
|
|
|
|
|
|
def request_body(args):
|
|
flags = {name: getattr(args, name) for name in args.fields if getattr(args, name) is not None}
|
|
if args.body_file is None:
|
|
return {name: field["default"] for name, field in args.request_schema["properties"].items()
|
|
if "default" in field and args.mode != "upload"} | flags
|
|
if flags:
|
|
raise ClientError("--body-file 与字段参数只能选择一种。")
|
|
try:
|
|
body = json.loads(args.body_file.read_text(encoding="utf-8-sig"), parse_constant=reject_constant)
|
|
except ValueError:
|
|
raise ClientError("请求正文必须是有效 JSON 对象。") from None
|
|
if not isinstance(body, dict):
|
|
raise ClientError("请求正文必须是 JSON 对象。")
|
|
return body
|
|
|
|
|
|
def save_private_json(args, data, details):
|
|
target = args.output.absolute()
|
|
try:
|
|
with private_output(target) as stream:
|
|
stream.write((compact(data) + "\n").encode("utf-8"))
|
|
except (OSError, subprocess.SubprocessError, ClientError):
|
|
raise ClientError("已收到服务端响应,但私有输出保存失败。", **details) from None
|
|
return {"ok": True, **details, "outputFile": str(target)}
|
|
|
|
|
|
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)
|
|
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 response.get("downloaded"):
|
|
return response
|
|
details = {key: response[key] for key in ("httpStatus", "code", "traceId")}
|
|
if args.mode in ("zip", "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)
|
|
data = response["json"].get("data")
|
|
if not isinstance(data, dict) or not data:
|
|
raise ClientError("System 响应未包含所需数据。", **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)
|
|
|
|
|
|
def add_operation(actions, prefix, name, endpoint, summary, request_type, mode=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}
|
|
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":
|
|
command.add_argument("--file", type=Path, required=True, help="上传的本机文件")
|
|
else:
|
|
label = "本机私有 JSON 输入文件" if private_input else "UTF-8 JSON 请求文件"
|
|
inputs.add_argument("--body-file", type=Path, help=label)
|
|
if mode in ("zip", "private-output"):
|
|
command.add_argument("--output", type=Path, required=True, help="私有输出路径,拒绝覆盖")
|
|
fields = []
|
|
if not private_input:
|
|
for field, spec in schema["properties"].items():
|
|
value_type = spec["type"]
|
|
if isinstance(value_type, list):
|
|
value_type = value_type[0]
|
|
if field == "file" or value_type not in ("string", "integer", "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 value_type == "integer":
|
|
options["type"] = int
|
|
if value_type == "boolean":
|
|
options.update(type=parse_bool, metavar="true|false")
|
|
if "enum" in spec:
|
|
options["choices"] = spec["enum"]
|
|
if "default" in spec:
|
|
options["help"] += f",默认 {spec['default']}"
|
|
command.add_argument(flag, **options)
|
|
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)
|
|
|
|
|
|
def parse_bool(value):
|
|
if value not in ("true", "false"):
|
|
raise argparse.ArgumentTypeError("需要 true 或 false")
|
|
return value == "true"
|
|
|
|
|
|
def add_commands(commands):
|
|
login = commands.add_parser("login", help="交互登录 System 并保存本机会话")
|
|
login.add_argument("--base-url", help="目标后端地址,首次登录必填")
|
|
login.set_defaults(handler=lambda client, args: client.login(args.base_url), endpoint=LOGIN_PATH)
|
|
logout = commands.add_parser("logout", help="在服务端退出并清理本机 Token")
|
|
logout.set_defaults(handler=lambda client, _: client.logout(), endpoint=LOGOUT_PATH)
|
|
for group, (summary, prefix, operations) in GROUPS.items():
|
|
section = commands.add_parser(group, help=summary, description=summary)
|
|
actions = section.add_subparsers(required=True)
|
|
for operation in operations:
|
|
add_operation(actions, prefix, *operation)
|