from __future__ import annotations import argparse import hashlib import json import shutil import sys import zipfile from pathlib import Path from typing import Any def sha256_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: for chunk in iter(lambda: f.read(1024 * 1024), b""): h.update(chunk) return h.hexdigest() def iter_files(root: Path) -> dict[str, Path]: result: dict[str, Path] = {} for path in root.rglob("*"): if path.is_file(): result[path.relative_to(root).as_posix()] = path return result def build_delta_manifest(old_root: Path, new_root: Path, from_version: str, to_version: str) -> dict[str, Any]: old_files = iter_files(old_root) new_files = iter_files(new_root) changed: list[dict[str, Any]] = [] for rel, new_path in sorted(new_files.items()): new_hash = sha256_file(new_path) old_path = old_files.get(rel) if old_path is not None and sha256_file(old_path) == new_hash: continue changed.append( { "path": rel, "sha256": new_hash, "size": new_path.stat().st_size, } ) deleted = sorted(set(old_files) - set(new_files)) return { "schema": 1, "from_version": from_version.strip().lstrip("Vv"), "to_version": to_version.strip().lstrip("Vv"), "files": changed, "delete": deleted, } def create_delta_zip(old_root: Path, new_root: Path, out_path: Path, from_version: str, to_version: str) -> dict[str, Any]: old_root = old_root.resolve() new_root = new_root.resolve() if not old_root.is_dir(): raise FileNotFoundError(f"old root not found: {old_root}") if not new_root.is_dir(): raise FileNotFoundError(f"new root not found: {new_root}") manifest = build_delta_manifest(old_root, new_root, from_version, to_version) out_path.parent.mkdir(parents=True, exist_ok=True) tmp = out_path.with_suffix(out_path.suffix + ".tmp") if tmp.exists(): tmp.unlink() with zipfile.ZipFile(tmp, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf: zf.writestr( "manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"), ) for item in manifest["files"]: rel = item["path"] zf.write(new_root / rel, f"files/{rel}") if out_path.exists(): out_path.unlink() tmp.replace(out_path) manifest["delta_sha256"] = sha256_file(out_path) manifest["delta_size"] = out_path.stat().st_size return manifest def create_delta_zips( old_roots: list[Path], new_root: Path, out_dir: Path, *, to_version: str, ) -> list[dict[str, Any]]: manifests: list[dict[str, Any]] = [] for old_root in old_roots: from_version = infer_dist_version(old_root) out_path = out_dir / f"DouyinGuaji-{from_version}_to_{to_version.strip().lstrip('Vv')}_delta.zip" manifests.append( create_delta_zip( old_root, new_root, out_path, from_version, to_version, ) ) return manifests def infer_dist_version(path: Path) -> str: name = path.name for prefix in ("DouyinGuaji-", "douyin-guaji-", "douyin_guaji-"): if name.startswith(prefix): candidate = name[len(prefix):].strip().lstrip("Vv") if candidate: return candidate raise ValueError(f"cannot infer version from directory name: {path}") def apply_delta_zip(delta_path: Path, target_root: Path) -> dict[str, Any]: target_root = target_root.resolve() with zipfile.ZipFile(delta_path) as zf: manifest = json.loads(zf.read("manifest.json").decode("utf-8-sig")) for rel in manifest.get("delete") or []: target = (target_root / str(rel)).resolve() if target == target_root or target_root not in target.parents: raise ValueError(f"unsafe delete path: {rel}") if target.is_dir(): shutil.rmtree(target) elif target.exists(): target.unlink() for item in manifest.get("files") or []: rel = str(item["path"]) target = (target_root / rel).resolve() if target_root not in target.parents: raise ValueError(f"unsafe write path: {rel}") target.parent.mkdir(parents=True, exist_ok=True) data = zf.read(f"files/{rel}") expected = str(item["sha256"]).lower() actual = hashlib.sha256(data).hexdigest() if actual != expected: raise ValueError(f"hash mismatch in delta file: {rel}") target.write_bytes(data) return manifest def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Build or apply DouyinGuaji delta update packages.") sub = parser.add_subparsers(dest="cmd", required=True) build = sub.add_parser("build", help="Create a delta zip from two portable distributions.") build.add_argument("--old", required=True, type=Path) build.add_argument("--new", required=True, type=Path) build.add_argument("--out", required=True, type=Path) build.add_argument("--from-version", required=True) build.add_argument("--to-version", required=True) build_many = sub.add_parser("build-many", help="Create cumulative delta zips from multiple old distributions to one new distribution.") build_many.add_argument("--old", required=True, type=Path, nargs="+") build_many.add_argument("--new", required=True, type=Path) build_many.add_argument("--out-dir", required=True, type=Path) build_many.add_argument("--to-version", required=True) apply = sub.add_parser("apply", help="Apply a delta zip to a target directory for local verification.") apply.add_argument("--delta", required=True, type=Path) apply.add_argument("--target", required=True, type=Path) args = parser.parse_args(argv) if args.cmd == "build": manifest = create_delta_zip(args.old, args.new, args.out, args.from_version, args.to_version) print(json.dumps(manifest, ensure_ascii=False, indent=2)) return 0 if args.cmd == "build-many": manifests = create_delta_zips(args.old, args.new, args.out_dir, to_version=args.to_version) print(json.dumps({"deltas": manifests}, ensure_ascii=False, indent=2)) return 0 manifest = apply_delta_zip(args.delta, args.target) print(json.dumps({"ok": True, "from_version": manifest.get("from_version"), "to_version": manifest.get("to_version")}, ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))