Repository navigation
Expand file tree
/
Copy pathsync_plugin.py
More file actions
290 lines (263 loc) · 13.8 KB
/
Copy pathsync_plugin.py
File metadata and controls
290 lines (263 loc) · 13.8 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# -*- coding: utf-8 -*-
"""把仓库根的运行时文件同步进 plugins/zcode-token-usage-statusbar/(插件打包副本),
并集中校验 6 处分发/运行文件清单的一致性。
插件要能脱离仓库独立安装(marketplace 缓存目录里只有 plugins/<name>/ 子树),
所以插件包里必须带一份 zusage.py 等文件的副本。改了根目录文件后跑一次:
python3 sync_plugin.py
副本与根文件不一致或 6 处分发清单存在漂移时退出码 1(CI 可用作漂移检查;加 --check 只查不改)。
"""
import ast
import filecmp
import importlib.util
import json
import re
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).parent.resolve()
PLUGIN_NAME = "zcode-token-usage-statusbar"
PLUGIN_PREFIX = f"plugins/{PLUGIN_NAME}/"
PLUGIN = ROOT / "plugins" / PLUGIN_NAME
# 1. 仓库根同步到 plugins/zcode-token-usage-statusbar/ 的正本文件(单点事实源)
FILES = [
"usage_mcp.py",
"zusage.py",
"patch_install.py",
"install_monitor.py",
"inject-main.cjs",
"account-core.cjs", "account-quota.cjs", # 账号管家引擎(vendored,冷文件:变更需重启客户端)
"account-remote.cjs", # 远控身份桥(移动端远程控制,冷文件:变更需重启客户端)
"plugin-updater.cjs",
"plugin-release.cjs",
"plugin-storage.cjs",
"quota-client.cjs",
"model-puller.cjs",
"engine-patch.cjs",
"mobile-relay.cjs",
"sysmon-client.cjs",
"python-runtime.cjs",
"pet-library.cjs",
"fastfetch-manager.cjs",
"release_unpack.py",
"runtime_lock.py", "usage_stats.py", "turn-stats.js",
"overlay.js", "token_rate.py", "renderer_bridge.py", "token_pricing.py",
"pending_zip_patch.py", "resmon_tool.py",
]
# 仅存在于插件目录内、随 Release ZIP 一起分发的文件
PLUGIN_ONLY_FILES = (
"overlay_install.py",
"plugin_auto_update.py",
"restart_notice.py",
".mcp.json",
"README.md",
".zcode-plugin/plugin.json",
".claude-plugin/plugin.json",
"hooks/hooks.json",
"hooks/session-start.py",
"hooks/prompt-submit.py",
"commands/context.md",
"commands/usage.md",
"commands/install-overlay.md",
"commands/uninstall-overlay.md",
"commands/zusage-doctor.md",
"commands/resource-monitor.md",
"extension-main.cjs",
"extension-view-context.js",
"extension-view-insights.js",
"extension-market.cjs",
"extension-view-market.js",
"market-engine.cjs",
"market_mcp.py",
"assets_query.py",
"extension-assets.cjs",
"extension-view-assets.js",
"skills/zcode-token-usage/SKILL.md",
)
# 派生清单契约(对应 docs/rules/install-release.md §1 的 6 处登记点):
# - install.py 独立链运行目录:与 FILES 相同(独立链的 MCP 也从运行目录跑 usage_mcp.py)
STANDALONE_RUNTIME_FILES = tuple(FILES)
# - overlay_install.py 插件链运行目录:FILES 去掉从插件目录直跑的 usage_mcp.py
PLUGIN_RUNTIME_FILES = tuple(f for f in FILES if f != "usage_mcp.py")
# - 主进程冷文件(变更后需完全退出并重启客户端;热主模块也在内:旧 loader 上与 hot_reload:false 时都只能重启生效)
COLD_FILES = (
"inject-main.cjs",
"account-core.cjs", "account-quota.cjs",
"account-remote.cjs",
"plugin-updater.cjs",
"plugin-release.cjs",
"plugin-storage.cjs",
"quota-client.cjs",
"model-puller.cjs",
"engine-patch.cjs",
"sysmon-client.cjs",
"python-runtime.cjs",
"pet-library.cjs",
)
# - 关闭热重载时同样只能重启生效的热文件(overlay_install.py 的 hot_reload:false 分支与
# plugin-updater.cjs recordRestart 的条件分支同款)
HOT_RELOAD_OFF_COLD_FILES = ("overlay.js", "zusage.py", "mobile-relay.cjs", "fastfetch-manager.cjs")
# - restart_notice.py 允许记录 hash 的文件集合(冷文件 + 禁用热重载时的热文件)
RESTART_HASH_FILES = (*COLD_FILES, *HOT_RELOAD_OFF_COLD_FILES)
# - Release ZIP 内的插件文件与完整条目
RELEASE_PLUGIN_FILES = (*FILES, *PLUGIN_ONLY_FILES)
RELEASE_ZIP_FILES = tuple(sorted((
"LICENSE",
"marketplace.json",
*(PLUGIN_PREFIX + p for p in RELEASE_PLUGIN_FILES),
)))
def _load_module(name, path):
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def check_manifests(root=ROOT):
"""校验 6 处分发清单是否与本模块定义的派生契约完全一致,返回错误描述列表。"""
root = Path(root).resolve()
plugin_dir = root / "plugins" / PLUGIN_NAME
errors = []
# (1) release_tool.py: SYNC_FILES / SOURCES / NAMES
rt = _load_module("sync_check_release_tool", root / "release_tool.py")
if set(rt.SYNC_FILES) != set(FILES) or len(rt.SYNC_FILES) != len(FILES):
errors.append("release_tool.SYNC_FILES 与 sync_plugin.FILES 不一致")
if set(rt.SOURCES) != set(RELEASE_PLUGIN_FILES) or len(rt.SOURCES) != len(RELEASE_PLUGIN_FILES):
errors.append("release_tool.SOURCES 与 sync_plugin.RELEASE_PLUGIN_FILES 不一致")
if tuple(rt.NAMES) != RELEASE_ZIP_FILES:
errors.append("release_tool.NAMES 与 sync_plugin.RELEASE_ZIP_FILES 不一致")
# (2) release_unpack.py: PLUGIN_FILES / ALLOWED_FILES
ru = _load_module("sync_check_release_unpack", root / "release_unpack.py")
if set(ru.PLUGIN_FILES) != set(RELEASE_PLUGIN_FILES) or len(ru.PLUGIN_FILES) != len(RELEASE_PLUGIN_FILES):
errors.append("release_unpack.PLUGIN_FILES 与 sync_plugin.RELEASE_PLUGIN_FILES 不一致")
if set(ru.ALLOWED_FILES) != set(RELEASE_ZIP_FILES):
errors.append("release_unpack.ALLOWED_FILES 与 sync_plugin.RELEASE_ZIP_FILES 不一致")
# (3) install.py: RUNTIME_FILES
inst = _load_module("sync_check_install", root / "install.py")
if set(inst.RUNTIME_FILES) != set(STANDALONE_RUNTIME_FILES) or len(inst.RUNTIME_FILES) != len(STANDALONE_RUNTIME_FILES):
errors.append("install.RUNTIME_FILES 与 sync_plugin.STANDALONE_RUNTIME_FILES 不一致")
# (4) overlay_install.py: RUNTIME_FILES & cold_files
ov = _load_module("sync_check_overlay_install", plugin_dir / "overlay_install.py")
if set(ov.RUNTIME_FILES) != set(PLUGIN_RUNTIME_FILES) or len(ov.RUNTIME_FILES) != len(PLUGIN_RUNTIME_FILES):
errors.append("overlay_install.RUNTIME_FILES 与 sync_plugin.PLUGIN_RUNTIME_FILES 不一致")
ov_src = (plugin_dir / "overlay_install.py").read_text(encoding="utf-8")
cold_matches = re.findall(r"cold_files = (\{[^}]+\})", ov_src)
if len(cold_matches) != 1:
errors.append(f"overlay_install.py 中 cold_files 字面量数量异常(期望 1 处,实际 {len(cold_matches)} 处)")
else:
parsed_cold = ast.literal_eval(cold_matches[0])
if set(parsed_cold) != set(COLD_FILES):
errors.append("overlay_install.py cold_files 与 sync_plugin.COLD_FILES 不一致")
off_matches = re.findall(r"cold_files\.update\(\(([^)]*)\)\)", ov_src)
if len(off_matches) != 1:
errors.append(f"overlay_install.py 中 cold_files.update 数量异常(期望 1 处,实际 {len(off_matches)} 处)")
else:
parsed_off = ast.literal_eval("(" + off_matches[0] + ")")
if set(parsed_off) != set(HOT_RELOAD_OFF_COLD_FILES) or len(parsed_off) != len(HOT_RELOAD_OFF_COLD_FILES):
errors.append("overlay_install.py hot_reload:false 增补清单与 sync_plugin.HOT_RELOAD_OFF_COLD_FILES 不一致")
# (5) restart_notice.py: RESTART_HASH_FILES
rn = _load_module("sync_check_restart_notice", plugin_dir / "restart_notice.py")
rn_files = getattr(rn, "RESTART_HASH_FILES", ())
if set(rn_files) != set(RESTART_HASH_FILES) or len(rn_files) != len(RESTART_HASH_FILES):
errors.append("restart_notice.RESTART_HASH_FILES 与 sync_plugin.RESTART_HASH_FILES 不一致")
# (5b) plugin-updater.cjs: 旧 loader 兜底记录重启用的清单(唯一手抄在 JS 里的一份)= 常冷 + hot_reload:false 时追加的三项
pu_src = (root / "plugin-updater.cjs").read_text(encoding="utf-8")
cold_expr = re.search(r"const cold = changed\.filter\((.*?)\);", pu_src, re.S)
legacy_cold = re.findall(r'f === "([^"]+)"', cold_expr.group(1)) if cold_expr else []
if set(legacy_cold) != set(RESTART_HASH_FILES) or len(legacy_cold) != len(RESTART_HASH_FILES):
errors.append("plugin-updater.cjs 旧 loader 兜底清单与 sync_plugin.RESTART_HASH_FILES 不一致")
# 常冷集与 hot_reload:false 增补集分开核对:只比并集会把「常冷清单漏列、条件分支兜底」的漂移拍平
split_at = cold_expr.group(1).find("hot_reload === false && (") if cold_expr else -1
legacy_always = re.findall(r'f === "([^"]+)"', cold_expr.group(1)[:split_at] if split_at >= 0 else "")
legacy_off = re.findall(r'f === "([^"]+)"', cold_expr.group(1)[split_at:] if split_at >= 0 else "")
if set(legacy_always) != set(COLD_FILES) or len(legacy_always) != len(COLD_FILES):
errors.append("plugin-updater.cjs 常冷清单与 sync_plugin.COLD_FILES 不一致")
if set(legacy_off) != set(HOT_RELOAD_OFF_COLD_FILES) or len(legacy_off) != len(HOT_RELOAD_OFF_COLD_FILES):
errors.append("plugin-updater.cjs hot_reload:false 增补清单与 sync_plugin.HOT_RELOAD_OFF_COLD_FILES 不一致")
# (6) .zcode-plugin/plugin.json & .claude-plugin/plugin.json: packageLayout.files
for rel in (".zcode-plugin/plugin.json", ".claude-plugin/plugin.json"):
mpath = plugin_dir / rel
manifest = json.loads(mpath.read_text(encoding="utf-8"))
layout_files = (manifest.get("packageLayout") or {}).get("files")
if not isinstance(layout_files, list) or tuple(sorted(layout_files)) != RELEASE_ZIP_FILES or len(layout_files) != len(RELEASE_ZIP_FILES):
errors.append(f"{rel} packageLayout.files 与 sync_plugin.RELEASE_ZIP_FILES 不一致")
return errors
_BUNDLE_BUILDERS = (
("build_overlay.py", "sync_build_overlay"),
("build_quota.py", "sync_build_quota"),
("build_puller.py", "sync_build_puller"),
("build_sysmon.py", "sync_build_sysmon"),
("build_pet.py", "sync_build_pet"),
("build_market.py", "sync_build_market"), # 市场行情引擎:产物在插件目录,六层子目录拼接
)
def _maybe_build_bundles(root=ROOT, check_only=False):
"""构建桌面、额度、模型拉取、系统状态采样、宠物素材库与市场行情引擎产物;油猴脚本产物不入库,由独立脚本在发版时构建。
缺构建脚本一律跳过(残缺树只构建存在的产物);「--check 必须六构建器齐全」的严格性在 main() 的
check_only 路径上,不在这里——独立安装器夹具等局部检出会直接调本函数。"""
for script_name, mod_name in _BUNDLE_BUILDERS:
builder = Path(root) / "scripts" / script_name
if not builder.is_file():
continue
mod = _load_module(mod_name, builder)
rc = mod.main(["--check"] if check_only else [], root=root)
if rc != 0:
# 点名是哪个构建器没过:scripts/check_all.py 经本命令一次完成六个构建校验,靠这一行给出独立失败名
print(f"构建校验失败: scripts/{script_name}" + (" --check" if check_only else ""))
return False
return True
def main(check_only=False, verify_manifests=False):
if verify_manifests:
errors = check_manifests(ROOT)
for err in errors:
print("清单漂移:", err)
if errors:
return 1
print("6 处分发清单一致。")
return 0
if check_only:
# check_all 的五个构建校验都经 sync_plugin.py --check 进程内跑:缺构建脚本必须失败并点名,
# 静默跳过会让校验在构建器缺失时假绿(普通同步不走这里,残缺树照旧只构建存在的产物)
missing = next((name for name, _ in _BUNDLE_BUILDERS if not (ROOT / "scripts" / name).is_file()), None)
if missing is not None:
print(f"缺少构建脚本: scripts/{missing}")
return 1
if not _maybe_build_bundles(ROOT, check_only=check_only):
return 1
missing = [f for f in FILES if not (ROOT / f).is_file()]
if missing:
print("根文件缺失:", ", ".join(missing))
return 1
manifest_errors = check_manifests(ROOT)
if manifest_errors:
for err in manifest_errors:
print("清单漂移:", err)
return 1
if not check_only:
PLUGIN.mkdir(parents=True, exist_ok=True)
drift = []
copies = [(name, name) for name in FILES]
for name, destination in copies:
src, dst = ROOT / name, PLUGIN / destination
if dst.is_file() and filecmp.cmp(src, dst, shallow=False):
continue
drift.append(name)
if not check_only:
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
print(f"已同步 {name}")
if check_only:
if drift:
print("插件副本过期:", ", ".join(drift), "(运行 python3 sync_plugin.py 更新)")
return 1
print("插件副本与根文件一致。")
elif not drift:
print("无需更新,副本已一致。")
return 0
if __name__ == "__main__":
argv = sys.argv[1:]
unknown = [a for a in argv if a not in ("--check", "--verify-manifests")]
if unknown:
# 未知参数(含漏横线/多余位置参数)必须响:静默忽略会退化为写入同步
# (--verify-manifests 幽灵旗标事故的根因)。刻意不提供「跳过构建校验」之类的通道。
print("未知参数: " + ", ".join(unknown)
+ "(支持:--check 只读检查、--verify-manifests 只校验 6 处分发清单;"
"与 --check 同传时仅校验清单)", file=sys.stderr)
sys.exit(2)
sys.exit(main(check_only="--check" in argv, verify_manifests="--verify-manifests" in argv))