Repository navigation
Expand file tree
/
Copy pathrelease_tool.py
More file actions
792 lines (718 loc) · 45.8 KB
/
Copy pathrelease_tool.py
File metadata and controls
792 lines (718 loc) · 45.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
#!/usr/bin/env python3
"""Build/verify local release assets; publishing requires two explicit approvals."""
import argparse
import base64
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import stat
import subprocess
import sys
import tempfile
import urllib.error
import urllib.parse
import urllib.request
import zipfile
PLUGIN = "zcode-token-usage-statusbar"
PREFIX = f"plugins/{PLUGIN}/"
PLUGIN_ID = f"{PLUGIN}@zusage-marketplace"
SEMVER = r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
MAX_FILE = 8 * 1024 * 1024
MAX_ASSET = 16 * 1024 * 1024
MAX_MANIFEST = 256 * 1024
MAX_TOTAL = 64 * 1024 * 1024
# 油猴脚本产物不入库(specs/mobile-userscript-build.md):publish 按发布源码现建,随 Release 作为资产分发。
# 构建输入因此与 NAMES 一样必须已提交且与 HEAD 逐字节一致。
USCRIPT_NAMES = ("zusage-mobile.user.js", "zusage-mobile.debug.user.js")
USCRIPT_BUILDER = "scripts/build_mobile_userscript.py"
USCRIPT_SOURCES = (USCRIPT_BUILDER, "scripts/build_overlay.py", "src/mobile", "src/overlay")
SYNC_FILES = ("usage_mcp.py", "zusage.py", "patch_install.py", "install_monitor.py",
"inject-main.cjs", "plugin-updater.cjs", "runtime_lock.py", "usage_stats.py", "turn-stats.js", "overlay.js",
"plugin-release.cjs", "plugin-storage.cjs", "quota-client.cjs", "model-puller.cjs", "engine-patch.cjs", "mobile-relay.cjs", "sysmon-client.cjs", "release_unpack.py", "token_rate.py", "renderer_bridge.py", "token_pricing.py",
"pending_zip_patch.py", "resmon_tool.py")
# Enumerated source paths, never a recursive glob that could collect local usage data.
SOURCES = (*SYNC_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",
"skills/zcode-token-usage/SKILL.md")
NAMES = tuple(sorted(("LICENSE", "marketplace.json", *(PREFIX + p for p in SOURCES))))
RELEVANT = ("LICENSE", "marketplace.json", "plugins", "release_tool.py", "sync_plugin.py", *SYNC_FILES,
*USCRIPT_SOURCES)
class ReleaseError(ValueError):
pass
def require(condition, message):
if not condition:
raise ReleaseError(message)
def repository(value):
require(isinstance(value, str) and re.fullmatch(
r"[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9][A-Za-z0-9._-]*", value),
"repository must be explicit owner/repo (GitHub only)")
return value
def read_file(path, limit=MAX_FILE):
require(not path.is_symlink() and path.is_file(), f"not a regular source file: {path}")
require(path.stat().st_size <= limit, f"oversize file: {path}")
return path.read_bytes()
def write_lf(path, text):
"""按 UTF-8 + LF 落盘。Path.write_text 走平台文本模式,Windows 上把 \\n 写成 \\r\\n(它的 newline=
参数要 Python 3.10):渠道清单经 git hash-object --stdin 原样进渠道分支,跨平台对账比的也是字节。"""
path.write_bytes(text.encode("utf-8"))
def identities(data, expected=None):
market = json.loads(data["marketplace.json"])
manifest = json.loads(data[PREFIX + ".zcode-plugin/plugin.json"])
compatibility = json.loads(data[PREFIX + ".claude-plugin/plugin.json"])
require(all(isinstance(value, dict) for value in (market, manifest, compatibility)),
"project manifests must be JSON objects")
version = manifest.get("version")
require(isinstance(version, str) and re.fullmatch(SEMVER, version), "stable SEMVER required")
require(manifest == compatibility and manifest.get("name") == PLUGIN,
"plugin manifests/name disagree")
require(market.get("name") == "zusage-marketplace", "marketplace name disagrees")
entries = market.get("plugins", [])
require(isinstance(entries, list) and len(entries) == 1, "unexpected marketplace plugins")
entry = entries[0]
require(isinstance(entry, dict), "marketplace entry must be an object")
require(entry.get("name") == PLUGIN and entry.get("version") == version and
entry.get("source") == "./plugins/" + PLUGIN, "marketplace version/name/source disagrees")
require(manifest.get("commands") == "commands" and manifest.get("skills") == "skills",
"plugin component paths disagree")
require(expected is None or expected == version, "requested version disagrees")
return version
def require_layout(data):
# Older in-the-field unpackers (<= v1.4.5) treat a ZIP without a declared
# layout as "must exactly match my own historical file set"; any added or
# removed file then fails the update with "ZIP is missing required release
# files". Both plugin manifests must therefore always declare the full ZIP
# file set, kept in lockstep with NAMES.
manifest = json.loads(data[PREFIX + ".zcode-plugin/plugin.json"])
layout = manifest.get("packageLayout")
require(isinstance(layout, dict) and type(layout.get("schemaVersion")) is int and
layout["schemaVersion"] == 1 and isinstance(layout.get("files"), list) and
all(isinstance(name, str) for name in layout["files"]) and
len(layout["files"]) == len(set(layout["files"])) and
set(layout["files"]) == set(NAMES),
"plugin manifest packageLayout disagrees with packaged files; declare the full ZIP "
"file set in both plugin manifests (see .zcode/skills/zcode-github-release/references/release-contract.md)")
def source_data(root, expected=None):
plugin = root / "plugins" / PLUGIN
require(plugin.is_dir() and not plugin.is_symlink() and not (root / "plugins").is_symlink(),
"missing or symlink plugin source directory")
for directory, dirs, files in os.walk(plugin, followlinks=False):
for name in dirs + files:
require(not (Path(directory) / name).is_symlink(), "symlink in plugin tree")
data = {name: read_file(root / name) for name in NAMES}
require(sum(map(len, data.values())) <= MAX_TOTAL, "oversize source tree")
identities(data, expected)
require_layout(data)
for name in SYNC_FILES:
require(read_file(root / name) == data[PREFIX + name], f"runtime copy drift: {name}")
return data
def zip_name(version):
return f"{PLUGIN}-v{version}.zip"
def build(root, repo, out, version=None):
repo = repository(repo)
data = source_data(root, version)
version = identities(data, version)
require(not out.exists() and not out.is_symlink(), "output directory already exists")
out.mkdir(parents=True, exist_ok=False)
asset = out / zip_name(version)
# 成员一律 DEFLATE-9:在野解包器自 v1.4.0 起接受该压缩方式,体积约为不压缩时的三分之一。
# 压缩字节可能随打包机的 zlib 实现变化,补推对账因此按内容比(reconcile),不按字节比。
with zipfile.ZipFile(asset, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
for name in NAMES:
info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.create_system = 3
info.external_attr = (stat.S_IFREG | 0o644) << 16
archive.writestr(info, data[name], compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
payload = read_file(asset, MAX_ASSET)
manifest = {"schemaVersion": 1, "repository": repo, "version": version, "tag": "v" + version,
"pluginId": PLUGIN_ID, "asset": {"name": asset.name, "size": len(payload),
"sha256": hashlib.sha256(payload).hexdigest()}}
path = out / "release-manifest.json"
write_lf(path, json.dumps(manifest, indent=2, sort_keys=True) + "\n")
verify(asset, path, repo)
catalog = json.loads(data["marketplace.json"])
catalog["plugins"][0]["source"] = {
"source": "url", "type": "zip", "url":
f"https://github.com/{repo}/releases/download/v{version}/{asset.name}",
"sha256": manifest["asset"]["sha256"], "path": "plugins/" + PLUGIN, "stripRoot": False}
catalog_path = out / "marketplace-release.json"
write_lf(catalog_path, json.dumps(catalog, indent=2, sort_keys=True) + "\n")
return {"zip": str(asset.resolve()), "manifest": str(path.resolve()),
"catalog": str(catalog_path.resolve()), **manifest}
def verify(asset, manifest_path, repo=None):
require(asset.name != manifest_path.name and manifest_path.name == "release-manifest.json",
"expected separate release-manifest.json")
manifest = json.loads(read_file(manifest_path, MAX_MANIFEST))
require(isinstance(manifest, dict), "release manifest must be a JSON object")
repository(manifest.get("repository"))
require(repo is None or repository(repo) == manifest["repository"], "repository disagrees")
version = manifest.get("version")
require(isinstance(version, str) and re.fullmatch(SEMVER, version), "stable SEMVER required")
require(type(manifest.get("schemaVersion")) is int and manifest["schemaVersion"] == 1 and
manifest.get("tag") == "v" + version and manifest.get("pluginId") == PLUGIN_ID,
"release manifest identity disagrees")
record = manifest.get("asset", {})
require(isinstance(record, dict), "asset record must be a JSON object")
payload = read_file(asset, MAX_ASSET)
require(asset.name == record.get("name") == zip_name(version) and
type(record.get("size")) is int and record["size"] == len(payload) and
record.get("sha256") == hashlib.sha256(payload).hexdigest(), "asset name/size/hash disagrees")
# Check bounded compression/resources before our ZIP reads; never import ZIP code.
helper_path = Path(__file__).resolve().with_name("release_unpack.py")
read_file(helper_path)
spec = importlib.util.spec_from_file_location("release_tool_unpack", helper_path)
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
with tempfile.TemporaryDirectory(prefix="zusage-release-verify-") as temporary:
try:
helper.unpack(asset.absolute(), manifest_path.absolute(), manifest["repository"], version,
Path(temporary) / "marketplace")
except (ValueError, OSError, TypeError, RuntimeError, EOFError, RecursionError,
zipfile.BadZipFile, zipfile.LargeZipFile, helper.zlib.error) as error:
raise ReleaseError(f"release unpack validation failed: {error}") from error
with zipfile.ZipFile(asset) as archive:
members = archive.infolist()
require(len(members) == len(NAMES), "unexpected ZIP entries or duplicate names")
data = {}
total = 0
for member in members:
name = member.filename
path = PurePosixPath(name)
mode = member.external_attr >> 16
require(name in NAMES and not path.is_absolute() and ".." not in path.parts and
"\\" not in name and ":" not in name and name not in data,
f"unsafe or non-source ZIP entry: {name}")
require(not member.is_dir() and stat.S_IFMT(mode) in (0, stat.S_IFREG) and
not member.flag_bits & 1 and member.compress_type in
(zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED), "non-regular/encrypted/unsupported ZIP entry")
total += member.file_size
require(member.file_size <= MAX_FILE and total <= MAX_TOTAL, "oversize ZIP contents")
data[name] = archive.read(member)
require(set(data) == set(NAMES), "missing ZIP source")
identities(data, version)
require_layout(data)
return manifest
def run(root, *args):
result = subprocess.run(args, cwd=root, capture_output=True, check=False)
require(result.returncode == 0, f"command failed: {' '.join(args)}\n" +
result.stderr.decode("utf-8", errors="replace"))
return result.stdout
def run_input(root, args, data):
result = subprocess.run(args, cwd=root, input=data, capture_output=True, check=False)
require(result.returncode == 0, f"command failed: {' '.join(args)}\n" +
result.stderr.decode("utf-8", errors="replace"))
return result.stdout
def zip_members(path):
with zipfile.ZipFile(io.BytesIO(read_file(path, MAX_ASSET))) as archive:
return [(member.filename, archive.read(member)) for member in archive.infolist()]
def release_catalog(repo, version, asset_name, sha256, marketplace):
catalog = json.loads(marketplace)
require(isinstance(catalog, dict) and isinstance(catalog.get("plugins"), list)
and len(catalog["plugins"]) == 1, "marketplace catalog shape disagrees")
catalog["plugins"][0]["source"] = {
"source": "url", "type": "zip", "url":
f"https://github.com/{repo}/releases/download/v{version}/{asset_name}",
"sha256": sha256, "path": "plugins/" + PLUGIN, "stripRoot": False}
return json.dumps(catalog, indent=2, sort_keys=True) + "\n"
def reconcile(repo, asset, manifest_path, published_asset, published_manifest_path, catalog_out):
"""补推前的对账(specs/release-channel-slim.md):重建包与线上发布包各自通过 verify 且身份
一致;字节相同直接通过,字节不同(打包机或压缩实现不同)时逐成员比对内容。渠道清单
必须指向真正托管的那份包,所以 sha256 恒取线上发布清单的值。"""
repo = repository(repo)
rebuilt = verify(asset, manifest_path, repo)
published = verify(published_asset, published_manifest_path, repo)
for key in ("repository", "version", "tag", "pluginId"):
require(rebuilt[key] == published[key], f"rebuilt release {key} disagrees with the published release")
require(rebuilt["asset"]["name"] == published["asset"]["name"], "rebuilt asset name disagrees")
rebuilt_bytes, published_bytes = read_file(asset, MAX_ASSET), read_file(published_asset, MAX_ASSET)
byte_identical = rebuilt_bytes == published_bytes
require(byte_identical or zip_members(asset) == zip_members(published_asset),
"rebuilt package differs from the published release")
catalog = release_catalog(repo, published["version"], published["asset"]["name"],
published["asset"]["sha256"], dict(zip_members(published_asset))["marketplace.json"])
write_lf(catalog_out, catalog)
return {"byteIdentical": byte_identical, "version": published["version"],
"sha256": published["asset"]["sha256"], "rebuiltSha256": rebuilt["asset"]["sha256"],
"catalog": str(catalog_out.resolve())}
def channel_commit(root, catalog_path, version, parent=None, orphan=False):
"""把渠道清单做成只含 marketplace.json 与 LICENSE 的提交对象(specs/release-channel-slim.md)。
不动工作区与索引、不推送:推送由发布技能按独立授权执行。已有分支必须给 parent——市场克隆按
快进跟进分支,孤儿 tip 会让它们静默卡在旧清单(issue #497);orphan=True 只用于首次创建分支。"""
root = Path(root).resolve()
require(isinstance(version, str) and re.fullmatch(SEMVER, version), "stable SEMVER required")
require(not (parent and orphan), "--parent and --orphan are mutually exclusive")
require(orphan or parent,
"channel-commit refuses to create an orphan commit: marketplace consumers fast-forward the "
"branch, an orphan tip silently strands them on the old manifest (issue #497); pass "
"--parent <remote tip> to build on the branch, or --orphan only when creating a new branch")
catalog = read_file(Path(catalog_path), MAX_MANIFEST)
parsed = json.loads(catalog)
plugins = parsed.get("plugins") if isinstance(parsed, dict) else None
entry = plugins[0] if isinstance(plugins, list) and plugins else None
require(isinstance(entry, dict) and entry.get("name") == PLUGIN and entry.get("version") == version,
"channel catalog plugin/version disagrees")
source = entry.get("source")
require(isinstance(source, dict) and re.fullmatch("[0-9a-f]{64}", str(source.get("sha256", "")))
and str(source.get("url", "")).startswith("https://"), "channel catalog asset disagrees")
parent_sha = None
if parent:
parent_sha = run(root, "git", "rev-parse", "--verify", "--quiet", parent + "^{commit}").decode().strip()
entries = {"LICENSE": read_file(root / "LICENSE", MAX_MANIFEST), "marketplace.json": catalog}
tree_lines = []
for name in sorted(entries):
oid = run_input(root, ["git", "hash-object", "-w", "--stdin"], entries[name]).decode().strip()
tree_lines.append(f"100644 blob {oid}\t{name}")
tree = run_input(root, ["git", "mktree"], ("\n".join(tree_lines) + "\n").encode("utf-8")).decode().strip()
command = ["git", "commit-tree", tree, "-m", f"chore: 更新渠道清单 {version}"]
if parent_sha:
command[3:3] = ["-p", parent_sha]
return {"commit": run(root, *command).decode().strip(), "tree": tree, "parent": parent_sha,
"files": sorted(entries), "version": version}
def gh_json(root, endpoint, *flags):
return json.loads(run(root, "gh", "api", endpoint, "--hostname", "github.com",
"--method", "GET", *flags))
GITCODE_API = "https://api.gitcode.com/api/v5"
# Asset hosts the updater may download GitCode release files from. Verified on the
# first real mirror upload; extend only together with plugin-release.cjs fetchBytes.
GITCODE_ASSET_HOSTS = ("gitcode.com", "raw.gitcode.com")
def gitcode_repository(value):
require(isinstance(value, str) and re.fullmatch(
r"[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9][A-Za-z0-9._-]*", value),
"--gitcode-repo must be explicit owner/repo")
return value
def gitcode_api(path, token=None, query=None, method="GET", body=None, headers=None, timeout=120):
# Returns (status, body) for every HTTP outcome so callers can branch on 404;
# never surface full URLs on failure: the access_token rides in the query string.
params = dict(query or {})
if token:
params["access_token"] = token
url = GITCODE_API + path + ("?" + urllib.parse.urlencode(params) if params else "")
request = urllib.request.Request(url, data=body, method=method, headers=headers or {})
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
with error:
return error.code, error.read()
except (urllib.error.URLError, OSError, TimeoutError) as error:
detail = error.reason if isinstance(error, urllib.error.URLError) else error
raise ReleaseError(f"gitcode api {method} {path} failed: {detail}") from None
class _TraceRedirects(urllib.request.HTTPRedirectHandler):
# Record every redirect hop so the observed host chain can be pinned in
# plugin-release.cjs fetchBytes; never log query strings (may carry tokens).
def __init__(self, hops):
self.hops = hops
def redirect_request(self, req, fp, code, msg, headers, newurl):
self.hops.append(urllib.parse.urlsplit(newurl)._replace(query=None).geturl())
return super().redirect_request(req, fp, code, msg, headers, newurl)
def download_traced(url, hops, timeout=120):
opener = urllib.request.build_opener(_TraceRedirects(hops))
request = urllib.request.Request(url, headers={"User-Agent": "zusage-release-tool"})
with opener.open(request, timeout=timeout) as response:
# 有界下载(输入侧 read_file 的 MAX_ASSET 同款上限):异常大响应先按上限截断,
# 后续 sha256 字节比对失败仍 fail-closed,但内存不被放大
return response.read(MAX_ASSET + 1), response.geturl()
def userscript_inputs(root):
"""油猴脚本的构建输入文件:两个构建脚本与 src/mobile 下的全部分片。src/overlay 整个目录登记在 RELEVANT
里做脏/未跟踪检查,其行尾差异由 NAMES 里逐字节比对的 overlay.js 兜住(两者由同一批分片构建)。
产物不入库,发布时现建,所以这些输入必须与 NAMES 同样已提交。"""
mobile = sorted(path for path in (root / "src" / "mobile").glob("*.js") if path.is_file())
require(mobile, "missing userscript sources under src/mobile")
return (USCRIPT_BUILDER, "scripts/build_overlay.py",
*(path.relative_to(root).as_posix() for path in mobile))
def build_userscripts(root, out_dir):
"""按被发布仓库自己的源码构建正式/调试两份油猴脚本到发布目录(specs/mobile-userscript-build.md)。
构建器取自该仓库:连同它的输入一起受 preflight 的「已提交且与 HEAD 一致」约束。"""
path = root / USCRIPT_BUILDER
read_file(path)
spec = importlib.util.spec_from_file_location("release_tool_userscript_builder", path)
builder = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(builder)
variants = builder.build(root)
except (getattr(builder, "BuildError", ()), ValueError, OSError) as error:
# 构建器自身的 BuildError,或桌面构建器的 ValueError / 分片读写失败:都是发布前可读的失败
raise ReleaseError(f"userscript build failed: {error}") from None
require([name for name, _ in variants] == list(USCRIPT_NAMES),
"userscript builder returned unexpected products")
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
paths = []
for name, data in variants:
require(0 < len(data) <= MAX_ASSET, "oversize userscript: " + name)
target = out_dir / name
target.write_bytes(data)
paths.append(target)
return paths
def upload_command(tag, paths, repo):
"""显式的资产列表:ZIP、release-manifest.json 与两份油猴脚本,不用下标切片拼参。"""
return ["gh", "release", "upload", tag, *(str(path) for path in paths), "--repo", "github.com/" + repo]
def assemble_overlay(root):
"""用被发布仓库自己的拼接脚本组装 src/overlay 分片——与油猴构建器同一入口(build_overlay.assemble_bytes)。"""
path = root / "scripts" / "build_overlay.py"
spec = importlib.util.spec_from_file_location("release_tool_overlay_builder", path)
builder = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(builder)
assembled, _ = builder.assemble_bytes(root / "src" / "overlay")
except (ValueError, OSError) as error: # 分片缺失、命名不符、非 UTF-8、闭包锚点缺失:构建器以这两类报错
raise ReleaseError(f"overlay assembly failed: {error}") from None
return assembled
def preflight(root, repo, manifest, asset):
data = source_data(root, manifest["version"])
with zipfile.ZipFile(asset) as archive:
require(all(archive.read(name) == content for name, content in data.items()),
"ZIP is not the current repository source")
top = run(root, "git", "rev-parse", "--show-toplevel").decode().strip()
require(Path(top).resolve() == root.resolve(), "--root must be the git repository root")
head = run(root, "git", "rev-parse", "--verify", "HEAD^{commit}").decode().strip()
require(not run(root, "git", "status", "--porcelain", "--untracked-files=all", "--", *RELEVANT),
"relevant git files are dirty or untracked")
for name in (*NAMES, *userscript_inputs(root)):
# 先比经 git 清洗过滤器(CRLF→LF 归一化)后的 blob OID,区分“内容未提交”;
# 再要求逐字节一致:发布包取的是工作区字节,Windows 的 CRLF 检出会让同一 tag
# 打出不同产物。.gitattributes 已固定 eol=lf,旧检出须按 maintaining.md 重新检出。
oid = run(root, "git", "hash-object", "--", name).decode().strip()
require(oid == run(root, "git", "rev-parse", f"HEAD:{name}").decode().strip(),
"source not committed in HEAD")
working = data[name] if name in data else read_file(root / name)
require(run(root, "git", "cat-file", "blob", "HEAD:" + name) == working,
f"line endings differ from HEAD: {name}; re-checkout with LF (see docs/maintaining.md)")
# 分片已提交但漏同步(改了 src/overlay 却没跑 sync_plugin.py 就提交):油猴脚本内嵌的是发布时现建的分片拼接,
# ZIP 里的是 overlay.js,两边会不一致。发布包取的是工作区字节,上面的循环已保证它与 HEAD 逐字节一致,
# 所以拿工作区的分片拼接结果比两份 overlay.js(根目录与插件副本)即可。
assembled = assemble_overlay(root)
for name in ("overlay.js", PREFIX + "overlay.js"):
require(assembled == (data[name] if name in data else read_file(root / name)),
"overlay.js does not match the assembled src/overlay shards; run sync_plugin.py and commit")
remotes = run(root, "git", "remote", "-v").decode().splitlines()
urls = [line.split()[1] for line in remotes if len(line.split()) >= 2]
require(any(re.fullmatch(r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)" +
re.escape(repo) + r"(?:\.git)?/?", url, re.I) for url in urls),
"explicit repository is not a configured GitHub remote")
tag = manifest["tag"]
require(run(root, "git", "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}").decode().strip()
== head, "local tag does not point to HEAD")
run(root, "gh", "auth", "status", "--hostname", "github.com")
info = gh_json(root, f"repos/{repo}")
require(info.get("full_name", "").lower() == repo.lower() and
info.get("permissions", {}).get("push") is True, "no push permission for explicit repo")
obj = gh_json(root, f"repos/{repo}/git/ref/tags/{tag}")["object"]
for _ in range(4):
if obj.get("type") == "commit":
break
require(obj.get("type") == "tag" and re.fullmatch(r"[0-9a-f]{40}", obj.get("sha", "")),
"invalid remote tag")
obj = gh_json(root, f"repos/{repo}/git/tags/{obj['sha']}")["object"]
require(obj.get("type") == "commit" and obj.get("sha") == head, "remote tag does not point to HEAD")
pages = gh_json(root, f"repos/{repo}/releases?per_page=100", "--paginate", "--slurp")
require(isinstance(pages, list) and all(isinstance(page, list) for page in pages),
"unexpected GitHub release listing")
require(not any(release.get("tag_name") == tag for page in pages for release in page),
"release already exists (including drafts); refusing overwrite")
return head
def gitcode_mirror(asset, manifest_path, manifest, notes, tag, gitcode_repo, out_dir, userscripts=()):
# Mirrors an already-verified GitHub release to GitCode and derives the GitCode
# channel catalog from the observed asset URLs. Runs only after --publish won.
token = (os.environ.get("GITCODE_TOKEN") or "").strip()
require(token, "GITCODE_TOKEN is required for --gitcode-repo")
version = manifest["version"]
uploads = (asset, manifest_path, *userscripts)
def asset_bytes(path):
# 清单按 JSON 上限读,ZIP 与两份油猴脚本按资产上限读
return read_file(path, MAX_MANIFEST if path.suffix == ".json" else MAX_ASSET)
# Lookups carry the token too: anonymous calls draw on a shared robot-account pool
# (HTTP 429 "Limited account:p_repoRobot" once it is exhausted), and this step runs
# only after the GitHub release is already public (specs/gitcode-mirror-auth.md).
status, payload = gitcode_api(f"/repos/{gitcode_repo}/releases/tags/{tag}", token=token)
if status == 200:
release = json.loads(payload)
require(isinstance(release, dict) and release.get("tag_name") == tag,
"existing GitCode release identity disagrees; refusing to reuse")
else:
require(status == 404, f"gitcode release lookup -> HTTP {status}")
body = json.dumps({"tag_name": tag, "name": tag, "body": notes}).encode("utf-8")
status, payload = gitcode_api(f"/repos/{gitcode_repo}/releases", token=token, method="POST",
body=body, headers={"Content-Type": "application/json"})
require(status in (200, 201), f"gitcode release create -> HTTP {status}")
release = json.loads(payload)
require(isinstance(release, dict) and release.get("tag_name") == tag,
"gitcode release tag disagrees after create")
for path in uploads:
status, payload = gitcode_api(f"/repos/{gitcode_repo}/releases/{tag}/upload_url", token=token,
query={"file_name": path.name})
require(status == 200, f"gitcode upload_url for {path.name} -> HTTP {status}")
ticket = json.loads(payload)
url, headers = ticket.get("url"), ticket.get("headers") or {}
require(isinstance(url, str) and url.startswith("https://") and isinstance(headers, dict),
"gitcode upload ticket disagrees")
request = urllib.request.Request(url, data=asset_bytes(path), method="PUT",
headers={str(key): str(value) for key, value in headers.items()})
try:
with urllib.request.urlopen(request, timeout=300) as response:
require(200 <= response.status < 300, f"gitcode asset upload -> HTTP {response.status}")
except urllib.error.HTTPError as error:
error.close()
raise ReleaseError(f"gitcode asset upload for {path.name} -> HTTP {error.code}") from None
except (urllib.error.URLError, OSError, TimeoutError) as error:
detail = error.reason if isinstance(error, urllib.error.URLError) else error
raise ReleaseError(f"gitcode asset upload for {path.name} failed: {detail}") from None
status, payload = gitcode_api(f"/repos/{gitcode_repo}/releases/tags/{tag}", token=token)
require(status == 200, f"gitcode release reread -> HTTP {status}")
release = json.loads(payload)
assets = release.get("assets") or []
require(isinstance(assets, list), "gitcode release assets disagree")
urls = {}
for path in uploads:
entry = next((a for a in assets if isinstance(a, dict) and a.get("name") == path.name), None)
require(isinstance(entry, dict) and isinstance(entry.get("browser_download_url"), str),
f"gitcode asset {path.name} missing after upload")
urls[path.name] = entry["browser_download_url"]
hops = []
for path in uploads:
url = urls[path.name]
require(urllib.parse.urlsplit(url).hostname in GITCODE_ASSET_HOSTS,
f"unexpected GitCode asset host for {path.name}; extend GITCODE_ASSET_HOSTS and "
"plugin-release.cjs fetchBytes together after verifying the real URL")
content, final = download_traced(url, hops)
require(content == asset_bytes(path), f"gitcode asset {path.name} bytes disagree after upload")
if path.suffix == ".zip":
require(hashlib.sha256(content).hexdigest() == manifest["asset"]["sha256"],
"gitcode zip sha256 disagrees")
zip_url = url
with zipfile.ZipFile(asset) as archive:
catalog = json.loads(archive.read("marketplace.json"))
require(isinstance(catalog, dict) and isinstance(catalog.get("plugins"), list)
and len(catalog["plugins"]) == 1, "marketplace catalog shape disagrees")
catalog["plugins"][0]["source"] = {
"source": "url", "type": "zip", "url": zip_url,
"sha256": manifest["asset"]["sha256"], "path": "plugins/" + PLUGIN, "stripRoot": False}
catalog_path = out_dir / "marketplace-release-gitcode.json"
write_lf(catalog_path, json.dumps(catalog, indent=2, sort_keys=True) + "\n")
return {"zipUrl": zip_url, "manifestUrl": urls[manifest_path.name],
"catalog": str(catalog_path.resolve()), "redirectHops": hops}
def channel_lag(root, repo, version):
# 渠道清单推送(阶段 E)是独立授权步骤,发布刚完成时清单停在旧版本是流程内常态;
# 但 v1.5.17 因此滞留十余小时、市场渠道注册用户收不到更新(issue #308)。发布验收
# 通过后只读回读 plugin-releases 清单版本,滞后时在计划与 stderr 双路亮警告;核对
# 失败降级为 unknown。发布已公开,这条建议性核对绝不反过来让 publish 报错,也不
# 由 publish 代推渠道(E 仍须单独授权)。
info = {"branch": "plugin-releases", "releaseVersion": version,
"manifestVersion": None, "lagging": None, "error": None}
try:
payload = gh_json(root, f"repos/{repo}/contents/marketplace.json",
"-f", "ref=plugin-releases")
require(isinstance(payload, dict) and payload.get("encoding") == "base64" and
isinstance(payload.get("content"), str), "channel manifest payload disagrees")
entry = json.loads(base64.b64decode(payload["content"]).decode("utf-8"))["plugins"][0]
require(isinstance(entry, dict) and isinstance(entry.get("version"), str),
"channel manifest entry disagrees")
info["manifestVersion"] = entry["version"]
info["lagging"] = entry["version"] != version
except (ReleaseError, OSError, ValueError, KeyError, IndexError, TypeError) as error:
info["error"] = str(error)
print("release_tool: channel lag check failed; channel state unknown: " + str(error),
file=sys.stderr)
return info
if info["lagging"]:
print("release_tool: WARNING channel manifest lags the release: plugin-releases serves "
"{} but this release is {}; registered users get no update until stage E pushes "
"the channel manifest "
"(.zcode/skills/zcode-github-release/references/post-release.md)"
.format(info["manifestVersion"], version), file=sys.stderr)
return info
def publish(root, repo, asset, manifest_path, approved=False, confirm=None, notes_file=None,
gitcode_repo=None):
repo = repository(repo)
if gitcode_repo is not None:
gitcode_repo = gitcode_repository(gitcode_repo)
if approved:
require((os.environ.get("GITCODE_TOKEN") or "").strip(),
"GITCODE_TOKEN is required for --gitcode-repo")
require(asset.name != manifest_path.name and manifest_path.name == "release-manifest.json",
"expected separate release-manifest.json")
asset_input, manifest_input = str(asset.resolve()), str(manifest_path.resolve())
# Verify, upload and compare only owned snapshots, never mutable input assets.
with tempfile.TemporaryDirectory(prefix="zusage-release-snapshot-") as temporary:
directory = Path(temporary)
asset_snapshot, manifest_snapshot = directory / asset.name, directory / manifest_path.name
asset_snapshot.write_bytes(read_file(asset, MAX_ASSET))
manifest_snapshot.write_bytes(read_file(manifest_path, MAX_MANIFEST))
asset, manifest_path = asset_snapshot, manifest_snapshot
manifest = verify(asset, manifest_path, repo)
tag = manifest["tag"]
require(not approved or confirm == f"{repo}/{tag}", "--publish requires --confirm owner/repo/vVERSION")
require(notes_file is not None, "publish requires --notes-file")
notes_file = Path(notes_file).absolute()
notes = read_file(notes_file, MAX_MANIFEST).decode("utf-8")
label = notes.strip().strip("#*_`").strip()
if len(label.splitlines()) == 1:
# Only unwrap inline link destinations for the placeholder check, not the notes.
parts, start = [], 0
for match in re.finditer(r"\[([^\[\]\r\n]+)\]\(", label):
if match.start() < start:
continue
end, depth, delimiter = match.end(), 1, None
while end < len(label) and depth:
char = label[end]
if char == "\\":
end += 2
continue
if delimiter:
if char == delimiter:
delimiter = None
elif char == "<":
delimiter = ">"
elif char in "\"'" and label[end - 1].isspace():
delimiter = char
elif char == "(":
depth += 1
elif char == ")":
depth -= 1
end += 1
if depth:
break # Preserve the unclosed suffix; never rescan it for nested links.
parts.extend((label[start:match.start()], match.group(1)))
start = end
label = ("".join(parts) + label[start:]).strip().strip("#*_`").strip()
require(label and label.lower() not in (PLUGIN, "zusage-marketplace") and not re.fullmatch(
rf"(?:(?:{re.escape(PLUGIN)}|zusage-marketplace|release)\s*[-:–—]?\s*)?v?"
+ re.escape(manifest["version"]), label, re.I), "release notes are empty or placeholder-only")
# 油猴脚本产物不入库(specs/mobile-userscript-build.md):预演与正式发布都按发布源码现建到发布目录
# (ZIP 与清单所在处),随后与 ZIP、清单同纪律——只上传、回读和比对自有快照,不碰可变的输入文件。
userscripts = build_userscripts(root, Path(manifest_input).parent)
uploads = [asset, manifest_path]
for path in userscripts:
snapshot = directory / path.name
snapshot.write_bytes(read_file(path, MAX_ASSET))
uploads.append(snapshot)
head = preflight(root, repo, manifest, asset)
commands = [
["gh", "release", "create", tag, "--repo", "github.com/" + repo, "--draft", "--verify-tag",
"--target", head, "--title", tag, "--notes-file", str(notes_file)],
upload_command(tag, (asset_input, manifest_input, *userscripts), repo),
["gh", "release", "edit", tag, "--repo", "github.com/" + repo, "--draft=false", "--verify-tag"],
]
plan = {"dryRun": not approved, "repository": repo, "tag": tag, "commit": head,
"zip": asset_input, "manifest": manifest_input,
"userscripts": [str(path) for path in userscripts], "commands": commands,
"notesFile": str(notes_file), "notes": notes,
"betweenUploadAndPublish": "verify draft identity, body and downloaded asset bytes"}
if gitcode_repo is not None:
plan["gitcode"] = {
"repository": gitcode_repo, "tag": tag, "approved": approved,
"steps": ["create or reuse release with the same tag and notes",
"upload the zip, release-manifest.json and both userscript attachments",
"reread and byte-compare all four assets",
f"write marketplace-release-gitcode.json next to {manifest_input}"]}
if not approved:
return plan
# gh reads the owned notes snapshot, never the input file again after review.
snapshot = directory / "release-notes.md"
snapshot.write_bytes(notes.encode("utf-8"))
run(root, *commands[0][:-1], str(snapshot))
run(root, *upload_command(tag, uploads, repo))
pages = gh_json(root, f"repos/{repo}/releases?per_page=100", "--paginate", "--slurp")
drafts = [r for page in pages for r in page if r.get("tag_name") == tag]
require(len(drafts) == 1, "remote draft missing/ambiguous; left unpublished")
draft = drafts[0]
require(draft.get("draft") is True and draft.get("prerelease") is False and
draft.get("tag_name") == tag, "remote draft identity disagrees; left unpublished")
require(isinstance(draft.get("body"), str) and
draft["body"].replace("\r\n", "\n").rstrip() == notes.replace("\r\n", "\n").rstrip(),
"remote draft body disagrees; draft left unpublished")
assets = draft.get("assets", [])
# 资产集合恰为上传的那四个名字:缺任何一份或多出一份都不转正。
require(len(assets) == len(uploads) and {a.get("name") for a in assets} == {path.name for path in uploads},
"remote assets disagree; draft left unpublished")
for path in uploads:
entry = next(a for a in assets if a.get("name") == path.name)
require(type(entry.get("id")) is int and entry.get("state") == "uploaded" and
entry.get("size") == path.stat().st_size, "remote asset metadata disagrees")
content = run(root, "gh", "api", f"repos/{repo}/releases/assets/{entry['id']}", "--hostname",
"github.com", "--method", "GET", "--header", "Accept: application/octet-stream")
require(content == read_file(path, MAX_TOTAL), "remote asset hash disagrees; draft left unpublished")
# Fail closed if the remote tag changed while the draft was uploaded.
remote = gh_json(root, f"repos/{repo}/commits/{tag}")
require(remote.get("sha") == head, "remote tag changed; draft left unpublished")
run(root, *commands[2])
published = gh_json(root, f"repos/{repo}/releases/tags/{tag}")
require(published.get("draft") is False and published.get("prerelease") is False and
published.get("tag_name") == tag and sorted(
(a.get("id"), a.get("name"), a.get("size"), a.get("state"))
for a in published.get("assets", [])) == sorted(
(a.get("id"), a.get("name"), a.get("size"), a.get("state")) for a in assets),
"published release state/assets disagree; inspect release manually")
require(isinstance(published.get("body"), str) and
published["body"].replace("\r\n", "\n").rstrip() == notes.replace("\r\n", "\n").rstrip(),
"published release body disagrees; inspect release manually")
if gitcode_repo is not None:
plan["gitcode"].update(gitcode_mirror(
asset, manifest_path, manifest, notes, tag, gitcode_repo,
Path(manifest_input).parent, uploads[2:]))
plan["channelLag"] = channel_lag(root, repo, manifest["version"])
return plan
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
for command in ("build", "verify", "publish"):
p = sub.add_parser(command)
p.add_argument("--root", type=Path, default=Path.cwd())
p.add_argument("--repo", required=True)
if command == "build":
p.add_argument("--out", type=Path, required=True, help="new output directory (must not exist)")
p.add_argument("--version")
else:
p.add_argument("--zip", dest="asset", type=Path, required=True)
p.add_argument("--manifest", type=Path, required=True)
if command == "publish":
p.add_argument("--notes-file", type=Path, required=True, help="UTF-8 release notes (not a placeholder)")
p.add_argument("--gitcode-repo", help="optional gitcode owner/repo; mirror the release "
"and emit marketplace-release-gitcode.json (needs GITCODE_TOKEN)")
group = p.add_mutually_exclusive_group()
group.add_argument("--publish", action="store_true")
group.add_argument("--dry-run", action="store_true")
p.add_argument("--confirm", help="exact owner/repo/vVERSION; required with --publish")
p = sub.add_parser("reconcile", help="compare a rebuilt package with the published release and "
"emit the channel catalog bound to the published asset")
p.add_argument("--repo", required=True)
for name in ("zip", "manifest", "published-zip", "published-manifest", "catalog-out"):
p.add_argument("--" + name, dest=name.replace("-", "_"), type=Path, required=True)
p = sub.add_parser("channel-commit", help="create a commit holding only marketplace.json and LICENSE "
"(never pushes, never touches the worktree)")
p.add_argument("--root", type=Path, default=Path.cwd())
p.add_argument("--catalog", type=Path, required=True)
p.add_argument("--version", required=True)
p.add_argument("--parent", help="commit to build on (required unless --orphan); use the branch's remote tip")
p.add_argument("--orphan", action="store_true",
help="create a parentless commit; only for creating a brand-new channel branch")
args = parser.parse_args(argv)
try:
if args.command == "build":
result = build(args.root.resolve(), args.repo, args.out, args.version)
elif args.command == "verify":
result = {"zip": str(args.asset.resolve()), "manifest": str(args.manifest.resolve()),
**verify(args.asset, args.manifest, args.repo)}
elif args.command == "reconcile":
result = reconcile(args.repo, args.zip, args.manifest, args.published_zip,
args.published_manifest, args.catalog_out)
elif args.command == "channel-commit":
result = channel_commit(args.root, args.catalog, args.version, args.parent, args.orphan)
else:
result = publish(args.root.resolve(), args.repo, args.asset, args.manifest, args.publish, args.confirm,
notes_file=args.notes_file, gitcode_repo=args.gitcode_repo)
print(json.dumps(result, indent=2, sort_keys=True))
return 0
except (ReleaseError, OSError, ValueError, KeyError, TypeError, zipfile.BadZipFile) as error:
print(f"release_tool: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())