Files
lightcore-cli/lightcore_cli/cli.py
T

86 lines
3.8 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.
import argparse
from pathlib import Path
import subprocess
import sys
from . import api, application_commands, media, media_commands, system_commands
from .system_client import SystemClient
from .transport import Client, ClientError, compact
def default_session(app):
cwd = Path.cwd()
for parent in (cwd, *cwd.parents):
if (parent / "scripts" / "lightcore_api.py").is_file():
return parent / ".work" / "lightcore-api" / app / ".env"
if (parent / "业务" / "README.md").is_file() and (parent / "工具" / "README.md").is_file():
sibling = parent.parent / "LightCore"
if (sibling / "scripts" / "lightcore_api.py").is_file():
return sibling / ".work" / "lightcore-api" / app / ".env"
return Path.home() / ".lightcore" / "lightcore-api" / app / ".env"
def login(client, args):
return client.login(args.base_url)
def preview_size(value):
size = int(value)
if not 1024 <= size <= 1000000:
raise argparse.ArgumentTypeError("预览长度范围为 1024–1000000")
return size
def app_options(parser, app):
parser.set_defaults(app=app)
parser.add_argument("--env-file", type=Path, help="本机会话文件路径")
parser.add_argument("--timeout", type=int, choices=range(1, 121), metavar="秒",
default=30, help="HTTP 超时,1–120 秒,默认 30")
parser.add_argument("--max-chars", type=preview_size, metavar="字符",
default=6000, help="业务响应预览上限,默认 6000")
return parser.add_subparsers(required=True)
def parser():
root = argparse.ArgumentParser(prog="lightcore", description="LightCore 应用命令行工具")
apps = root.add_subparsers(dest="command", required=True)
raw = apps.add_parser("api", help="调用应用后台接口,支持登录、JSON、上传和下载")
api.add_arguments(raw)
raw.set_defaults(api_parser=raw)
app = apps.add_parser("media", help="Media 后台操作")
commands = app_options(app, "media")
auth = commands.add_parser("login", help="交互登录并保存本机 Media 会话",
description="执行 lightcore media login 后输入后台账号和密码。")
auth.add_argument("--base-url", help="Media 服务地址,默认 https://api.zhecent.com")
auth.set_defaults(handler=login, endpoint="/auth/login")
media_commands.add_commands(commands, media.add_file_commands(commands))
system = apps.add_parser("system", help="System 后台操作")
system_commands.add_commands(app_options(system, "system"))
for name, (description, _) in application_commands.APPLICATIONS.items():
app = apps.add_parser(name, help=description)
application_commands.add_commands(app_options(app, name), name)
return root
def main(argv=None):
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8")
args = parser().parse_args(argv)
if args.env_file is None:
args.env_file = default_session(args.app)
if args.command == "api":
return api.run(args, args.api_parser, Path.cwd() / ".work" / "lightcore" / args.app)
client = (SystemClient(args.env_file, args.timeout) if args.app == "system"
else Client(args.app, args.env_file, args.timeout))
try:
result = args.handler(client, args)
except ClientError as error:
result = {"ok": False, "message": str(error), **error.details}
except (OSError, ValueError, EOFError, subprocess.SubprocessError):
result = {"ok": False, "message": "无法读取会话或处理本机文件,请核对路径和权限。"}
except KeyboardInterrupt:
result = {"ok": False, "message": "操作已取消。"}
print(client.redact(compact(result)))
return 0 if result["ok"] else 1