Repository navigation
Expand file tree
/
Copy pathenv_setup.py
More file actions
73 lines (63 loc) · 2.35 KB
/
Copy pathenv_setup.py
File metadata and controls
73 lines (63 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python
"""环境自检:Linux/macOS 下自动补全 tencent-channel-cli。"""
import asyncio
import shutil
import sys
from core.plugin.decorators import on_load
from .commands.shared import BASE_DIR, DATA_DIR, _cli_env, _resolve_cli
CLI_NAME = "tencent-channel-cli"
LOCAL_PREFIX = DATA_DIR / ".cli"
NPM_INSTALL_TIMEOUT = 600
async def _run_npm(npm: str, args: list) -> tuple:
proc = await asyncio.create_subprocess_exec(
npm,
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
env=_cli_env(),
)
try:
out, _ = await asyncio.wait_for(proc.communicate(), timeout=NPM_INSTALL_TIMEOUT)
except asyncio.TimeoutError:
proc.kill()
return None, b""
return proc.returncode, out or b""
async def _npm_install_cli() -> None:
npm = shutil.which("npm")
if not npm:
print(
f"[txpd] 未找到 npm,无法自动安装 {CLI_NAME};"
f"请安装 Node.js/npm,或将 {CLI_NAME}-linux-x64 二进制放入插件目录 {BASE_DIR}"
)
return
print(f"[txpd] 检测到 {CLI_NAME} 缺失,正在安装到 {LOCAL_PREFIX} ...")
attempts = [
["install", "--prefix", str(LOCAL_PREFIX), CLI_NAME],
["install", "-g", CLI_NAME],
]
for args in attempts:
try:
code, out = await _run_npm(npm, args)
except Exception as e:
print(f"[txpd] 执行 npm {' '.join(args)} 出错: {e}")
continue
if code is None:
print(f"[txpd] npm {' '.join(args)} 超时({NPM_INSTALL_TIMEOUT}s)")
continue
if code == 0 and _resolve_cli():
print(f"[txpd] {CLI_NAME} 安装成功: {_resolve_cli()}")
return
tail = out.decode("utf-8", "ignore").strip().splitlines()[-5:]
print(f"[txpd] npm {' '.join(args)} 失败 (exit={code}): " + " | ".join(tail))
print(
f"[txpd] {CLI_NAME} 自动安装失败;可手动执行 npm install -g {CLI_NAME},"
f"或将 {CLI_NAME}-linux-x64 二进制放入插件目录 {BASE_DIR}"
)
@on_load
async def ensure_cli_env():
"""插件加载时检测系统环境:非 Windows 且缺少 CLI 时后台自动补全。"""
if sys.platform.startswith("win"):
return
if _resolve_cli():
return
asyncio.create_task(_npm_install_cli())