Peach: Local-first video metadata scraper and media manager.
fix(release): 拆分发行解析并校验公开索引
longmeidaof9c6633defe8
diff --git a/scripts/release_r2.py b/scripts/release_r2.pyindex df65fd911..2698a517f 100644--- a/scripts/release_r2.py+++ b/scripts/release_r2.py@@ -11,7 +11,6 @@ import shutilimport subprocessimport sysimport tempfile-from urllib.error import HTTPErrorfrom urllib.parse import quote, urlsplitfrom urllib.request import Request, urlopen@@ -115,7 +114,8 @@ def publish(root: Path, version: str, *, apply: bool = False) -> dict:listing = subprocess.check_output([executable, "lsjson", f"peach:{environment['PEACH_R2_BUCKET']}","--recursive", "--files-only", "--config", str(configuration)],env=environment, text=True, encoding="utf-8")- result["projected_bucket_bytes"] = require_capacity(json.loads(listing), items, tag,+ existing = json.loads(listing)+ result["projected_bucket_bytes"] = require_capacity(existing, items, tag,int(environment.get("PEACH_R2_MAX_BYTES", "8000000000")))sums = temporary / "SHA256SUMS.txt"sums.write_text("".join(f"{item['sha256']} {item['name']}\n" for item in items), encoding="utf-8")@@ -134,19 +134,21 @@ def publish(root: Path, version: str, *, apply: bool = False) -> dict:release_file = temporary / "release.json"release_file.write_text(json.dumps(release, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")upload(release_file, f"{prefix}/release.json")- try:- with urlopen(Request(base + "/releases.json", headers={"User-Agent": USER_AGENT}), timeout=60) as response:- releases = json.load(response)- except HTTPError as error:- if error.code != 404:- raise- releases = []+ releases = []+ if any(item["Path"] == "releases.json" for item in existing):+ releases = json.loads(subprocess.check_output(+ [executable, "cat", f"peach:{environment['PEACH_R2_BUCKET']}/releases.json",+ "--config", str(configuration)], env=environment, text=True, encoding="utf-8"))if not isinstance(releases, list):raise ValueError("公开版本索引格式无效")index = temporary / "releases.json"index.write_text(json.dumps([release, *(item for item in releases if item["tag_name"] != tag)][:30],ensure_ascii=False, indent=2) + "\n", encoding="utf-8")upload(index, f"peach:{environment['PEACH_R2_BUCKET']}/releases.json", immutable=False)+ with index.open("rb") as source:+ index_info = {"name": index.name, "size": index.stat().st_size,+ "sha256": hashlib.file_digest(source, "sha256").hexdigest()}+ verify_download(f"{base}/releases.json?release={tag}", index_info)return resultdiff --git a/src/peach/release_updates.py b/src/peach/release_updates.pyindex 3f438bf50..e74ac928b 100644--- a/src/peach/release_updates.py+++ b/src/peach/release_updates.py@@ -28,6 +28,36 @@ def _version(value: object) -> tuple[int, ...] | None:return tuple(map(int, value.removeprefix("v").split(".")))+def _release_candidates(rows: list, endpoint: str) -> list[tuple]:+ """从一个公开发行源选择完整包,并构造受信任的下载地址。"""+ releases = []+ for row in rows:+ if not isinstance(row, dict) or row.get("draft"):+ continue+ version = _version(row.get("tag_name"))+ if version is None:+ continue+ tag = row["tag_name"]+ assets = row.get("assets") or []+ prefix = f"Peach-{tag.removeprefix('v')}-windows-x64"+ uploaded = {a.get("name"): a for a in assets if isinstance(a, dict) and a.get("state") == "uploaded"}+ full = uploaded.get(prefix + ".zip")+ if full is None:+ continue+ complete_tools = all(prefix + f"-tools-{tool}.zip" in uploaded for tool in TOOL_PATHS)+ asset = uploaded.get(prefix + "-update.zip", full) if complete_tools else full+ if endpoint == DOWNLOADS_API:+ if not re.fullmatch(r"sha256:[0-9a-f]{64}", asset.get("digest") or ""):+ continue+ asset_url = f"{DOWNLOADS_BASE}/{tag}/{asset['name']}"+ release_url = f"{GITGUD_RELEASES}/{tag}"+ else:+ asset_url = f"{RELEASES_URL}/download/{tag}/{asset['name']}"+ release_url = f"{RELEASES_URL}/tag/{tag}"+ releases.append((version, tag, asset, full, asset_url, release_url))+ return releases++def check(*, transport=None) -> dict:result = snapshot()client = transport or HttpxTransport()@@ -46,30 +76,7 @@ def check(*, transport=None) -> dict:if not isinstance(rows, list):continueobtained = True- for row in rows:- if not isinstance(row, dict) or row.get("draft"):- continue- version = _version(row.get("tag_name"))- if version is None:- continue- tag = row["tag_name"]- assets = row.get("assets") or []- prefix = f"Peach-{tag.removeprefix('v')}-windows-x64"- uploaded = {a.get("name"): a for a in assets if isinstance(a, dict) and a.get("state") == "uploaded"}- full = uploaded.get(prefix + ".zip")- if full is None:- continue- complete_tools = all(prefix + f"-tools-{tool}.zip" in uploaded for tool in TOOL_PATHS)- asset = uploaded.get(prefix + "-update.zip", full) if complete_tools else full- if endpoint == DOWNLOADS_API:- if not re.fullmatch(r"sha256:[0-9a-f]{64}", asset.get("digest") or ""):- continue- asset_url = f"{DOWNLOADS_BASE}/{tag}/{asset['name']}"- release_url = f"{GITGUD_RELEASES}/{tag}"- else:- asset_url = f"{RELEASES_URL}/download/{tag}/{asset['name']}"- release_url = f"{RELEASES_URL}/tag/{tag}"- releases.append((version, tag, asset, full, asset_url, release_url))+ releases.extend(_release_candidates(rows, endpoint))except (OSError, ValueError, TypeError, TimeoutError, httpx.HTTPError):continueif not releases:diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 6713fe5e2..70722ce0f 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -4695,6 +4695,49 @@ class ScriptingConventionTests(unittest.TestCase):class R2ReleaseTests(unittest.TestCase):+ def test_publication_preserves_existing_index_and_verifies_published_metadata(self):+ module = load_script("release_r2")+ objects = {"releases.json": json.dumps([{"tag_name": "v1.0.0"}]).encode()}+ uploads = []++ def read(command, **_kwargs):+ if command[1] == "lsjson":+ return json.dumps([{"Path": key, "Size": len(value)} for key, value in objects.items()])+ self.assertEqual(command[1], "cat")+ return objects["releases.json"].decode()++ def upload(command, **_kwargs):+ key = command[3].split("peach:peach-releases/", 1)[1]+ objects[key] = Path(command[2]).read_bytes()+ uploads.append((key, "--immutable" in command))++ def verify(url, item):+ key = url.split("https://downloads.example/", 1)[1].split("?", 1)[0]+ content = objects[key]+ self.assertEqual(len(content), item["size"])+ self.assertEqual(hashlib.sha256(content).hexdigest(), item["sha256"])++ environment = {"PEACH_RCLONE": "rclone", "PEACH_R2_BUCKET": "peach-releases",+ "PEACH_R2_PUBLIC_BASE": "https://downloads.example", "CI_COMMIT_SHA": "a" * 40,+ "CI_COMMIT_TIMESTAMP": "2026-10-21T00:00:00Z"}+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary).resolve()+ names = [f"Peach-1.2.3-windows-x64{suffix}" for suffix in (".zip", "-setup.exe", "-lite-setup.exe", "-update.zip")]+ names += [f"Peach-1.2.3-macos-{arch}.dmg" for arch in ("arm64", "x86_64")]+ for name in names:+ (root / name).write_bytes(name.encode())+ with mock.patch.object(module, "rclone_environment", return_value=environment), \+ mock.patch.object(module.subprocess, "check_output", side_effect=read), \+ mock.patch.object(module.subprocess, "run", side_effect=upload), \+ mock.patch.object(module, "verify_download", side_effect=verify):+ module.publish(root, "1.2.3", apply=True)+ index = json.loads(objects["releases.json"])+ self.assertEqual([item["tag_name"] for item in index], ["v1.2.3", "v1.0.0"])+ self.assertEqual(index[0]["commit_sha"], "a" * 40)+ self.assertTrue(all(item["digest"] == "sha256:" + item["sha256"] for item in index[0]["assets"]))+ self.assertEqual(uploads[-1], ("releases.json", False))+ self.assertTrue(all(immutable for _key, immutable in uploads[:-1]))+def test_capacity_keeps_existing_versions_and_stops_before_upload(self):module = load_script("release_r2")existing = [{"Path": "v1.0.0/old.zip", "Size": 2_000_000}, {"Path": "v1.2.3/app.zip", "Size": 3_000_000}]