qqbot-cli 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- qqbot_cli/__init__.py +16 -0
- qqbot_cli/cli.py +514 -0
- qqbot_cli/fetch.py +351 -0
- qqbot_cli/paths.py +209 -0
- qqbot_cli/py.typed +0 -0
- qqbot_cli/runner.py +152 -0
- qqbot_cli/uninstall.py +260 -0
- qqbot_cli/wizard.py +192 -0
- qqbot_cli-1.0.0.dist-info/METADATA +148 -0
- qqbot_cli-1.0.0.dist-info/RECORD +14 -0
- qqbot_cli-1.0.0.dist-info/WHEEL +5 -0
- qqbot_cli-1.0.0.dist-info/entry_points.txt +2 -0
- qqbot_cli-1.0.0.dist-info/licenses/LICENSE +661 -0
- qqbot_cli-1.0.0.dist-info/top_level.txt +1 -0
qqbot_cli/fetch.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""从 GitHub Release 取主程序文件。
|
|
3
|
+
|
|
4
|
+
**为什么单独复制一份下载逻辑,而不是 import 主程序的 `core.updater`**:
|
|
5
|
+
启动器的作用是在主程序还不存在的时候把它拉下来 —— 那时根本没有 `core` 可导入。
|
|
6
|
+
所以这里保留一份精简但同样严格的实现:主机白名单、大小上限、成员数上限、
|
|
7
|
+
拒绝绝对路径/`..`/链接文件。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import tarfile
|
|
17
|
+
import tempfile
|
|
18
|
+
import zipfile
|
|
19
|
+
from typing import Callable, Dict, List, Optional, Tuple
|
|
20
|
+
from urllib.parse import urlparse
|
|
21
|
+
|
|
22
|
+
from . import paths
|
|
23
|
+
|
|
24
|
+
# 压缩包上限:程序本体约 1~2 MB,给足余量但不允许无限大
|
|
25
|
+
MAX_ARCHIVE_BYTES = 64 * 1024 * 1024
|
|
26
|
+
MAX_MEMBERS = 5000
|
|
27
|
+
MAX_TOTAL_BYTES = 256 * 1024 * 1024
|
|
28
|
+
|
|
29
|
+
USER_AGENT = "qqbot-cli/1.0 (+https://github.com/L-web666/QQBotMerged)"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class FetchError(RuntimeError):
|
|
33
|
+
"""下载/解压过程中的可预期错误(会打印给用户看)。"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------- HTTP
|
|
37
|
+
def _requests():
|
|
38
|
+
try:
|
|
39
|
+
import requests
|
|
40
|
+
except ImportError: # pragma: no cover
|
|
41
|
+
raise FetchError("缺少依赖 requests,请先 pip install requests")
|
|
42
|
+
return requests
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _check_host(url: str) -> None:
|
|
46
|
+
parsed = urlparse(str(url or ""))
|
|
47
|
+
if parsed.scheme not in ("https", "http"):
|
|
48
|
+
raise FetchError("只允许 http/https 地址:%s" % url)
|
|
49
|
+
host = (parsed.hostname or "").lower()
|
|
50
|
+
if host not in paths.ALLOWED_HOSTS:
|
|
51
|
+
raise FetchError("拒绝从非白名单主机下载:%s" % host)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def list_releases(timeout: int = 30) -> List[Dict]:
|
|
55
|
+
"""取发布列表(新的在前)。"""
|
|
56
|
+
requests = _requests()
|
|
57
|
+
_check_host(paths.RELEASES_API)
|
|
58
|
+
try:
|
|
59
|
+
response = requests.get(paths.RELEASES_API, timeout=timeout,
|
|
60
|
+
headers={"User-Agent": USER_AGENT,
|
|
61
|
+
"Accept": "application/vnd.github+json"})
|
|
62
|
+
except Exception as exc:
|
|
63
|
+
raise FetchError("连不上 GitHub:%s" % exc)
|
|
64
|
+
if response.status_code == 404:
|
|
65
|
+
raise FetchError("仓库不存在或没有发布过版本")
|
|
66
|
+
if response.status_code != 200:
|
|
67
|
+
raise FetchError("GitHub 返回 %s(可能是网络受限或接口限流)"
|
|
68
|
+
% response.status_code)
|
|
69
|
+
try:
|
|
70
|
+
data = response.json()
|
|
71
|
+
except Exception:
|
|
72
|
+
raise FetchError("GitHub 返回的内容不是 JSON")
|
|
73
|
+
if not isinstance(data, list):
|
|
74
|
+
raise FetchError("GitHub 返回的数据格式不对")
|
|
75
|
+
out = []
|
|
76
|
+
for item in data:
|
|
77
|
+
tag = str(item.get("tag_name") or "").strip()
|
|
78
|
+
if not tag:
|
|
79
|
+
continue
|
|
80
|
+
out.append({
|
|
81
|
+
"tag": tag,
|
|
82
|
+
"name": item.get("name") or tag,
|
|
83
|
+
"prerelease": bool(item.get("prerelease")),
|
|
84
|
+
"draft": bool(item.get("draft")),
|
|
85
|
+
"published": item.get("published_at") or "",
|
|
86
|
+
"tarball": item.get("tarball_url") or "",
|
|
87
|
+
"zipball": item.get("zipball_url") or "",
|
|
88
|
+
"html": item.get("html_url") or "",
|
|
89
|
+
"body": item.get("body") or "",
|
|
90
|
+
})
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _stable(release: Dict) -> bool:
|
|
95
|
+
"""正式版:非草稿、非预发布,且版本号形如 1.2.3。"""
|
|
96
|
+
if release.get("draft") or release.get("prerelease"):
|
|
97
|
+
return False
|
|
98
|
+
return bool(re.match(r"^v?\d+\.\d+\.\d+$", release.get("tag") or ""))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def pick_latest(releases: List[Dict]) -> Optional[Dict]:
|
|
102
|
+
"""挑最新的正式版;都没有就挑第一个非草稿的。"""
|
|
103
|
+
for release in releases:
|
|
104
|
+
if _stable(release):
|
|
105
|
+
return release
|
|
106
|
+
for release in releases:
|
|
107
|
+
if not release.get("draft"):
|
|
108
|
+
return release
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---------------------------------------------------------------- 下载
|
|
113
|
+
def download(url: str, target: str, timeout: int = 60,
|
|
114
|
+
progress: Optional[Callable[[int, int], None]] = None) -> str:
|
|
115
|
+
"""把 url 下载到 target,返回 sha256。超过上限立即中止。"""
|
|
116
|
+
requests = _requests()
|
|
117
|
+
_check_host(url)
|
|
118
|
+
try:
|
|
119
|
+
response = requests.get(url, timeout=timeout, stream=True,
|
|
120
|
+
headers={"User-Agent": USER_AGENT})
|
|
121
|
+
except Exception as exc:
|
|
122
|
+
raise FetchError("下载失败:%s" % exc)
|
|
123
|
+
if response.status_code != 200:
|
|
124
|
+
raise FetchError("下载失败:HTTP %s" % response.status_code)
|
|
125
|
+
|
|
126
|
+
declared = response.headers.get("Content-Length")
|
|
127
|
+
try:
|
|
128
|
+
total = int(declared) if declared else 0
|
|
129
|
+
except (TypeError, ValueError):
|
|
130
|
+
total = 0
|
|
131
|
+
if total > MAX_ARCHIVE_BYTES:
|
|
132
|
+
raise FetchError("压缩包太大(%d 字节),已拒绝" % total)
|
|
133
|
+
|
|
134
|
+
digest = hashlib.sha256()
|
|
135
|
+
written = 0
|
|
136
|
+
temp_path = target + ".part"
|
|
137
|
+
try:
|
|
138
|
+
with open(temp_path, "wb") as handle:
|
|
139
|
+
for block in response.iter_content(256 * 1024):
|
|
140
|
+
if not block:
|
|
141
|
+
continue
|
|
142
|
+
written += len(block)
|
|
143
|
+
if written > MAX_ARCHIVE_BYTES:
|
|
144
|
+
raise FetchError("压缩包超过 %d 字节,已中止" % MAX_ARCHIVE_BYTES)
|
|
145
|
+
digest.update(block)
|
|
146
|
+
handle.write(block)
|
|
147
|
+
if progress:
|
|
148
|
+
progress(written, total)
|
|
149
|
+
os.replace(temp_path, target)
|
|
150
|
+
except FetchError:
|
|
151
|
+
_quiet_remove(temp_path)
|
|
152
|
+
raise
|
|
153
|
+
except Exception as exc:
|
|
154
|
+
_quiet_remove(temp_path)
|
|
155
|
+
raise FetchError("写入文件失败:%s" % exc)
|
|
156
|
+
return digest.hexdigest()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _quiet_remove(path: str) -> None:
|
|
160
|
+
try:
|
|
161
|
+
if os.path.exists(path):
|
|
162
|
+
os.remove(path)
|
|
163
|
+
except OSError:
|
|
164
|
+
pass
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ---------------------------------------------------------------- 解压
|
|
168
|
+
def _safe_member(name: str) -> str:
|
|
169
|
+
"""把压缩包成员名规范化成相对路径;不安全的返回空串。"""
|
|
170
|
+
raw = str(name or "").replace("\\", "/")
|
|
171
|
+
if not raw or raw.startswith("/") or raw.startswith("~"):
|
|
172
|
+
return ""
|
|
173
|
+
if re.match(r"^[A-Za-z]:", raw):
|
|
174
|
+
return ""
|
|
175
|
+
parts = [part for part in raw.split("/") if part not in ("", ".")]
|
|
176
|
+
if any(part == ".." for part in parts):
|
|
177
|
+
return ""
|
|
178
|
+
return "/".join(parts)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _strip_root(names: List[str]) -> str:
|
|
182
|
+
"""识别 GitHub 压缩包的顶层壳目录(如 `L-web666-QQBotMerged-abc123/`)。
|
|
183
|
+
|
|
184
|
+
判断依据是**目录条目**(`name` 以 `/` 结尾,且这条只表示那个顶层目录本身),
|
|
185
|
+
而不是"所有路径的第一段" —— 后者在**没有壳目录**的包里会把 `core/` 之类
|
|
186
|
+
的普通子目录误当成壳目录,结果 `run.py` 被留下来、`core/` 却被剥掉一层。
|
|
187
|
+
|
|
188
|
+
返回空串表示"没有壳目录,原样解压"。
|
|
189
|
+
"""
|
|
190
|
+
tops = set()
|
|
191
|
+
for name in names:
|
|
192
|
+
if not name or not name.endswith("/"):
|
|
193
|
+
continue
|
|
194
|
+
# 只接受"顶层那一层"的目录条目:去掉结尾 / 后不能再含 /
|
|
195
|
+
if "/" in name[:-1]:
|
|
196
|
+
continue
|
|
197
|
+
tops.add(name[:-1])
|
|
198
|
+
if len(tops) > 1:
|
|
199
|
+
return ""
|
|
200
|
+
if len(tops) != 1:
|
|
201
|
+
return ""
|
|
202
|
+
root = tops.pop()
|
|
203
|
+
# 再确认一遍:除了这条目录条目,其它路径都应该在这个目录下
|
|
204
|
+
for name in names:
|
|
205
|
+
if not name or name == root + "/":
|
|
206
|
+
continue
|
|
207
|
+
if not name.startswith(root + "/"):
|
|
208
|
+
return ""
|
|
209
|
+
return root
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def extract(archive: str, target_dir: str) -> None:
|
|
213
|
+
"""安全解压到 target_dir(会自动剥掉 GitHub 的顶层壳目录)。"""
|
|
214
|
+
os.makedirs(target_dir, exist_ok=True)
|
|
215
|
+
if zipfile.is_zipfile(archive):
|
|
216
|
+
_extract_zip(archive, target_dir)
|
|
217
|
+
else:
|
|
218
|
+
_extract_tar(archive, target_dir)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _extract_tar(archive: str, target_dir: str) -> None:
|
|
222
|
+
total = 0
|
|
223
|
+
seen = 0
|
|
224
|
+
try:
|
|
225
|
+
with tarfile.open(archive, "r:*") as tar:
|
|
226
|
+
members = []
|
|
227
|
+
for info in tar:
|
|
228
|
+
seen += 1
|
|
229
|
+
if seen > MAX_MEMBERS:
|
|
230
|
+
raise FetchError("压缩包内文件过多(超过 %d 个)" % MAX_MEMBERS)
|
|
231
|
+
raw = str(info.name or "").replace("\\", "/")
|
|
232
|
+
name = _safe_member(raw)
|
|
233
|
+
if not name:
|
|
234
|
+
continue
|
|
235
|
+
# `_safe_member` 会去掉末尾的 /,这里把它补回去 ——
|
|
236
|
+
# 否则 `_strip_root` 认不出"顶层目录条目"(它靠结尾的 / 判断),
|
|
237
|
+
# 壳目录就剥不掉,所有东西会被解到 `xxx-<sha>/` 下面。
|
|
238
|
+
if raw.endswith("/") or info.isdir():
|
|
239
|
+
name = name + "/"
|
|
240
|
+
members.append((name, info))
|
|
241
|
+
total += max(0, int(info.size or 0))
|
|
242
|
+
if total > MAX_TOTAL_BYTES:
|
|
243
|
+
raise FetchError("解压后体积过大,已拒绝")
|
|
244
|
+
root = _strip_root([name for name, _ in members])
|
|
245
|
+
for name, info in members:
|
|
246
|
+
if root and name == root + "/":
|
|
247
|
+
relative = ""
|
|
248
|
+
elif root and name.startswith(root + "/"):
|
|
249
|
+
relative = name[len(root) + 1:]
|
|
250
|
+
else:
|
|
251
|
+
relative = name
|
|
252
|
+
relative = relative.rstrip("/")
|
|
253
|
+
if not relative:
|
|
254
|
+
continue
|
|
255
|
+
destination = os.path.join(target_dir, *relative.split("/"))
|
|
256
|
+
if info.isdir():
|
|
257
|
+
os.makedirs(destination, exist_ok=True)
|
|
258
|
+
continue
|
|
259
|
+
if not info.isfile():
|
|
260
|
+
# 软链/硬链/设备文件一律跳过:发布包里不该有这些
|
|
261
|
+
continue
|
|
262
|
+
os.makedirs(os.path.dirname(destination) or target_dir, exist_ok=True)
|
|
263
|
+
source = tar.extractfile(info)
|
|
264
|
+
if source is None:
|
|
265
|
+
continue
|
|
266
|
+
with source, open(destination, "wb") as handle:
|
|
267
|
+
shutil.copyfileobj(source, handle, 1024 * 1024)
|
|
268
|
+
except FetchError:
|
|
269
|
+
raise
|
|
270
|
+
except Exception as exc:
|
|
271
|
+
raise FetchError("解压失败:%s" % exc)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _extract_zip(archive: str, target_dir: str) -> None:
|
|
275
|
+
total = 0
|
|
276
|
+
seen = 0
|
|
277
|
+
try:
|
|
278
|
+
with zipfile.ZipFile(archive) as bundle:
|
|
279
|
+
infos = []
|
|
280
|
+
for info in bundle.infolist():
|
|
281
|
+
seen += 1
|
|
282
|
+
if seen > MAX_MEMBERS:
|
|
283
|
+
raise FetchError("压缩包内文件过多(超过 %d 个)" % MAX_MEMBERS)
|
|
284
|
+
name = _safe_member(info.filename)
|
|
285
|
+
if not name:
|
|
286
|
+
continue
|
|
287
|
+
infos.append((name, info))
|
|
288
|
+
total += max(0, int(info.file_size or 0))
|
|
289
|
+
if total > MAX_TOTAL_BYTES:
|
|
290
|
+
raise FetchError("解压后体积过大,已拒绝")
|
|
291
|
+
root = _strip_root([name for name, _ in infos])
|
|
292
|
+
for name, info in infos:
|
|
293
|
+
relative = name[len(root) + 1:] if root and name.startswith(root + "/") else name
|
|
294
|
+
if not relative:
|
|
295
|
+
continue
|
|
296
|
+
destination = os.path.join(target_dir, *relative.split("/"))
|
|
297
|
+
if info.is_dir():
|
|
298
|
+
os.makedirs(destination, exist_ok=True)
|
|
299
|
+
continue
|
|
300
|
+
os.makedirs(os.path.dirname(destination) or target_dir, exist_ok=True)
|
|
301
|
+
with bundle.open(info) as source, open(destination, "wb") as handle:
|
|
302
|
+
shutil.copyfileobj(source, handle, 1024 * 1024)
|
|
303
|
+
except FetchError:
|
|
304
|
+
raise
|
|
305
|
+
except Exception as exc:
|
|
306
|
+
raise FetchError("解压失败:%s" % exc)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# ---------------------------------------------------------------- 安装
|
|
310
|
+
def install_release(release: Dict, install_dir: str,
|
|
311
|
+
progress: Optional[Callable[[str, int, int], None]] = None) -> Dict:
|
|
312
|
+
"""下载并解压某个发布到 install_dir。返回 {tag, sha256, commit}。"""
|
|
313
|
+
archive_url = release.get("tarball") or release.get("zipball") or ""
|
|
314
|
+
if not archive_url:
|
|
315
|
+
raise FetchError("这个发布没有提供源码包")
|
|
316
|
+
os.makedirs(install_dir, exist_ok=True)
|
|
317
|
+
# **下载缓冲放在安装目录里,而不是系统临时目录**:
|
|
318
|
+
# 有些环境(企业机器、容器、受限的 %TEMP%)临时目录不可写,
|
|
319
|
+
# 用临时目录会让安装直接失败;安装目录我们能确定是可写的。
|
|
320
|
+
temp_dir = os.path.join(install_dir, ".qqbot-download")
|
|
321
|
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
322
|
+
try:
|
|
323
|
+
os.makedirs(temp_dir, exist_ok=True)
|
|
324
|
+
except OSError:
|
|
325
|
+
# 实在不行再退回系统临时目录
|
|
326
|
+
temp_dir = tempfile.mkdtemp(prefix="qqbot-dl-")
|
|
327
|
+
try:
|
|
328
|
+
archive = os.path.join(temp_dir, "program.tar.gz")
|
|
329
|
+
if progress:
|
|
330
|
+
progress("downloading", 0, 0)
|
|
331
|
+
|
|
332
|
+
def _tick(done: int, total: int) -> None:
|
|
333
|
+
if progress:
|
|
334
|
+
progress("downloading", done, total)
|
|
335
|
+
|
|
336
|
+
digest = download(archive_url, archive, progress=_tick)
|
|
337
|
+
if progress:
|
|
338
|
+
progress("extracting", 0, 0)
|
|
339
|
+
extract(archive, install_dir)
|
|
340
|
+
return {"tag": release.get("tag") or "", "sha256": digest, "commit": ""}
|
|
341
|
+
finally:
|
|
342
|
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def verify_sha256(path: str) -> str:
|
|
346
|
+
"""算文件 sha256(用于校验已下载的包)。"""
|
|
347
|
+
digest = hashlib.sha256()
|
|
348
|
+
with open(path, "rb") as handle:
|
|
349
|
+
for block in iter(lambda: handle.read(1024 * 1024), b""):
|
|
350
|
+
digest.update(block)
|
|
351
|
+
return digest.hexdigest()
|
qqbot_cli/paths.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""启动器自己的路径与常量。
|
|
3
|
+
|
|
4
|
+
**刻意不导入主程序的 `core`**:主程序在 GitHub 上随时可能变,启动器要是
|
|
5
|
+
依赖它的模块结构,一次重构就把老用户卡住了。这里只用最小上限度的信息。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
# GitHub 仓库与接口(和主程序 core/version.py 里的一致,但这里独立维护)
|
|
12
|
+
REPO_SLUG = "L-web666/QQBotMerged"
|
|
13
|
+
RELEASES_API = "https://api.github.com/repos/%s/releases?per_page=20" % REPO_SLUG
|
|
14
|
+
TAGS_API = "https://api.github.com/repos/%s/tags?per_page=20" % REPO_SLUG
|
|
15
|
+
|
|
16
|
+
# 只从这些主机下载(和主程序的允许清单一致,防止被指向任意地址)
|
|
17
|
+
ALLOWED_HOSTS = (
|
|
18
|
+
"api.github.com",
|
|
19
|
+
"github.com",
|
|
20
|
+
"codeload.github.com",
|
|
21
|
+
"objects.githubusercontent.com",
|
|
22
|
+
"raw.githubusercontent.com",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
# 安装目录里认这个文件来判断"这里已经装过了"
|
|
26
|
+
MARKER_FILE = ".qqbot-install.json"
|
|
27
|
+
|
|
28
|
+
# 虚拟环境目录名(放在安装目录下)
|
|
29
|
+
VENV_DIR = ".venv"
|
|
30
|
+
|
|
31
|
+
# 主程序需要的依赖(和主程序 requirements.txt 保持一致;
|
|
32
|
+
# 启动器自己只需要 requests)
|
|
33
|
+
PROGRAM_REQUIRES = (
|
|
34
|
+
"flask>=2.0",
|
|
35
|
+
"Werkzeug>=3.1.9",
|
|
36
|
+
"requests>=2.28.0",
|
|
37
|
+
"websocket-client>=1.5.0",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# 最低 Python 版本:Werkzeug 3.1.9 要求 >=3.9
|
|
41
|
+
MIN_PYTHON = (3, 9)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def default_install_dir() -> str:
|
|
45
|
+
"""默认安装目录:`~/QQBotMerged`。"""
|
|
46
|
+
return os.path.join(os.path.expanduser("~"), "QQBotMerged")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def expand_dir(value: str) -> str:
|
|
50
|
+
"""把用户输入(可能带 ~ 或环境变量)展开成绝对路径。"""
|
|
51
|
+
text = str(value or "").strip().strip('"').strip("'")
|
|
52
|
+
if not text:
|
|
53
|
+
return default_install_dir()
|
|
54
|
+
text = os.path.expandvars(os.path.expanduser(text))
|
|
55
|
+
return os.path.abspath(text)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _platform() -> str:
|
|
59
|
+
"""当前平台(集中一处判断,方便测试时替换)。
|
|
60
|
+
|
|
61
|
+
返回 "windows" / "macos" / "linux" / 其它 `sys.platform` 值。
|
|
62
|
+
**不要把 `os.name` / `sys.platform` 散落在各处**:所有平台分支都走这里,
|
|
63
|
+
测试里只要替换这一个函数就能验证另一套逻辑。
|
|
64
|
+
"""
|
|
65
|
+
override = os.environ.get("QQBOT_CLI_FORCE_PLATFORM")
|
|
66
|
+
if override:
|
|
67
|
+
return override
|
|
68
|
+
if os.name == "nt":
|
|
69
|
+
return "windows"
|
|
70
|
+
if sys.platform == "darwin":
|
|
71
|
+
return "macos"
|
|
72
|
+
if sys.platform.startswith("linux"):
|
|
73
|
+
return "linux"
|
|
74
|
+
return sys.platform
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def is_windows() -> bool:
|
|
78
|
+
return _platform() == "windows"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def is_linux() -> bool:
|
|
82
|
+
return _platform() == "linux"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_macos() -> bool:
|
|
86
|
+
return _platform() == "macos"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def platform_label() -> str:
|
|
90
|
+
"""给人看的平台名(提示信息里用)。"""
|
|
91
|
+
table = {"windows": "Windows", "macos": "macOS", "linux": "Linux"}
|
|
92
|
+
return table.get(_platform(), _platform())
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def install_help_command(install_dir: str) -> str:
|
|
96
|
+
"""打印「怎么进安装目录」时要给的命令(Windows 用 cd /d 才能跨盘符)。"""
|
|
97
|
+
if is_windows():
|
|
98
|
+
return 'cd /d "%s"' % install_dir
|
|
99
|
+
return 'cd "%s"' % install_dir
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def venv_activate_hint(install_dir: str) -> str:
|
|
103
|
+
"""怎么手动激活虚拟环境(排错时有用)。"""
|
|
104
|
+
if is_windows():
|
|
105
|
+
return r'%s\.venv\Scripts\activate.bat' % install_dir
|
|
106
|
+
return 'source "%s/.venv/bin/activate"' % install_dir
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def venv_python(install_dir: str) -> str:
|
|
110
|
+
"""虚拟环境里的 python 可执行文件路径。"""
|
|
111
|
+
if is_windows():
|
|
112
|
+
return os.path.join(install_dir, VENV_DIR, "Scripts", "python.exe")
|
|
113
|
+
return os.path.join(install_dir, VENV_DIR, "bin", "python")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def current_python() -> str:
|
|
117
|
+
"""当前解释器(用于创建 venv)。"""
|
|
118
|
+
return sys.executable
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# ---------------------------------------------------------------- 记住装在哪
|
|
122
|
+
def _state_files(install_dir: str = "") -> list:
|
|
123
|
+
"""启动器记住"装到哪"的几个候选位置,按优先级排列。
|
|
124
|
+
|
|
125
|
+
**为什么要好几个**:`%APPDATA%` / `$XDG_CONFIG_HOME` 在有些环境里不可写
|
|
126
|
+
(受限的用户目录、容器、CI);用户主目录也可能只读(只读家目录、企业策略)。
|
|
127
|
+
只记一处,用户在向导里选的目录下次就找不到 —— `qqbot` 会默默回落到默认目录,
|
|
128
|
+
看起来像"装丢了"。
|
|
129
|
+
|
|
130
|
+
所以依次尝试几个位置,任何一处写成功就够用:
|
|
131
|
+
① 用户配置目录(最"正规"的位置)
|
|
132
|
+
② 用户主目录下的隐藏文件(配置目录写不了时的兜底)
|
|
133
|
+
③ **当前工作目录**下的隐藏文件(前两处都写不了时用;用户一般在自己
|
|
134
|
+
常用的目录里运行 `qqbot`,下次也在那儿跑,所以找得回来)
|
|
135
|
+
"""
|
|
136
|
+
home = os.path.expanduser("~")
|
|
137
|
+
if os.name == "nt":
|
|
138
|
+
base = os.environ.get("APPDATA") or home
|
|
139
|
+
else:
|
|
140
|
+
base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
|
|
141
|
+
candidates = [
|
|
142
|
+
os.path.join(base, "qqbot-cli", "state.json"),
|
|
143
|
+
os.path.join(home, ".qqbot-cli.json"),
|
|
144
|
+
]
|
|
145
|
+
try:
|
|
146
|
+
cwd = os.getcwd()
|
|
147
|
+
except OSError:
|
|
148
|
+
cwd = ""
|
|
149
|
+
if cwd:
|
|
150
|
+
candidates.append(os.path.join(cwd, ".qqbot-cli.json"))
|
|
151
|
+
if install_dir:
|
|
152
|
+
parent = os.path.dirname(os.path.abspath(install_dir).rstrip("/\\")) or "."
|
|
153
|
+
marker = os.path.join(parent, ".qqbot-cli.json")
|
|
154
|
+
if marker not in candidates:
|
|
155
|
+
candidates.append(marker)
|
|
156
|
+
return candidates
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _state_file() -> str:
|
|
160
|
+
"""主状态文件路径(读的时候会依次尝试 `_state_files()`)。"""
|
|
161
|
+
return _state_files()[0]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def remember_install_dir(install_dir: str) -> bool:
|
|
165
|
+
"""记下这次装到了哪,下次 `qqbot` 不带参数就能直接启动。
|
|
166
|
+
|
|
167
|
+
返回是否至少有一处写成功(写失败不影响本次使用,只是下次要带 --dir)。
|
|
168
|
+
"""
|
|
169
|
+
import json
|
|
170
|
+
payload = {"install_dir": install_dir}
|
|
171
|
+
written = False
|
|
172
|
+
for path in _state_files(install_dir):
|
|
173
|
+
try:
|
|
174
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
175
|
+
with open(path, "w", encoding="utf-8") as handle:
|
|
176
|
+
json.dump(payload, handle, ensure_ascii=False, indent=2)
|
|
177
|
+
written = True
|
|
178
|
+
except OSError:
|
|
179
|
+
continue
|
|
180
|
+
return written
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def remembered_install_dir(install_dir: str = "") -> str:
|
|
184
|
+
"""读回上次装的目录;没有就返回空串。多个位置依次尝试。"""
|
|
185
|
+
import json
|
|
186
|
+
for path in _state_files(install_dir):
|
|
187
|
+
try:
|
|
188
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
189
|
+
data = json.load(handle)
|
|
190
|
+
value = str((data or {}).get("install_dir") or "")
|
|
191
|
+
if value and os.path.isdir(value):
|
|
192
|
+
return value
|
|
193
|
+
except Exception:
|
|
194
|
+
continue
|
|
195
|
+
return ""
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def resolve_install_dir(cli_value: str = "", hint: str = "") -> str:
|
|
199
|
+
"""确定要操作的安装目录。
|
|
200
|
+
|
|
201
|
+
优先级:命令行 --dir > 上次记住的位置 > 默认目录
|
|
202
|
+
(`hint` 用于让"记住的位置"多查一个候选项,比如上次的安装目录)
|
|
203
|
+
"""
|
|
204
|
+
if str(cli_value or "").strip():
|
|
205
|
+
return expand_dir(cli_value)
|
|
206
|
+
remembered = remembered_install_dir(hint)
|
|
207
|
+
if remembered:
|
|
208
|
+
return remembered
|
|
209
|
+
return default_install_dir()
|
qqbot_cli/py.typed
ADDED
|
File without changes
|