"""Prepare a tagged Planet release on the publishing workstation.""" from __future__ import annotations import hashlib import json import os import re import shutil import subprocess import sys import tarfile import tempfile from contextlib import contextmanager from pathlib import Path if __package__: from .production_registry import ( REPO, SERVER, SERVICES, image_name, resolve_image, tag_commit, version, ) else: from production_registry import ( REPO, SERVER, SERVICES, image_name, resolve_image, tag_commit, version, ) def git(*args, cwd=None): return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip() def verified_tag(tag): commit = tag_commit(tag) if git("rev-parse", "--verify", f"{commit}^{{commit}}") != commit: raise RuntimeError("The remote release commit is not available locally") if git("show", f"{commit}:VERSION") != tag[1:]: raise ValueError("Tagged VERSION differs from the published tag") return commit def docker_config(): config = os.environ.get("PLANET_RELEASE_DOCKER_CONFIG") if config: return Path(config).expanduser() return ( Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "planet" / "registry" ) def ensure_images(source, tag, commit): for service in SERVICES: pin = resolve_image(service, tag, commit) if not pin: context = source / "frontend" if service == "admin" else source dockerfile = ( context / "Dockerfile" if service == "admin" else source / service / "Dockerfile" ) cmd = [ "docker", "--config", str(docker_config()), "buildx", "build", "--platform", "linux/amd64", "--provenance=false", "--file", str(dockerfile), "--label", f"org.opencontainers.image.revision={commit}", "--label", f"org.opencontainers.image.version={tag[1:]}", "--label", f"org.opencontainers.image.source={SERVER}/{REPO}", ] if service == "admin": cmd += [ "--build-arg", "PLANET_FRONTEND_TARGET=admin", "--label", "planet.frontend.target=admin", ] uv_config = Path.home() / ".config/uv/uv.toml" if service != "admin" and uv_config.is_file(): cmd += ["--secret", f"id=planet_uv_config,src={uv_config}"] cmd += [ "--output", f"type=image,name={image_name(service)}:{tag},push=true,compression=gzip,force-compression=true", str(context), ] subprocess.run(cmd, check=True) pin = resolve_image(service, tag, commit) if not pin: raise RuntimeError(f"Pushed image is not visible: {service}:{tag}") print(f"Verified {pin}", flush=True) def select_packages(directory, tag, suffixes): number = re.compile(rf"(? 8192: raise ValueError("Invalid hotfix package metadata") if json.load(archive.extractfile(member)).get("version") != tag[1:]: raise ValueError("Hotfix contents do not match the release tag") return paths @contextmanager def local_release_lock(path): with path.open("a+b") as lock: if os.name == "nt": import msvcrt lock.seek(0) msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) yield def package_hash(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def cached_packages(source, supplied, cache, tag, suffixes): if not cache.exists(): if supplied is None: subprocess.run(["./planet.sh", "bundle", "--all"], cwd=source, check=True) supplied = source / "client/release" packages = select_packages(supplied, tag, suffixes) if not packages: raise RuntimeError(f"Missing tagged desktop clients or Earth hotfix in {supplied}") with tempfile.TemporaryDirectory(dir=cache.parent) as tmp: stage = Path(tmp) / "assets" stage.mkdir() for package in packages: shutil.copy2(package, stage / package.name) sums = {p.name: package_hash(p) for p in stage.iterdir()} (stage / "checksums.json").write_text(json.dumps(sums)) os.rename(stage, cache) packages = select_packages(cache, tag, suffixes) expected = json.loads((cache / "checksums.json").read_text()) if not packages or {p.name: package_hash(p) for p in packages} != expected: raise ValueError("The saved release artifacts differ from the original build") return packages @contextmanager def prepare(tag, assets_dir, suffixes, *, already_published=False): version(tag) commit = verified_tag(tag) state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") state = state / "planet-releases" / tag / "publisher" state.mkdir(mode=0o700, parents=True, exist_ok=True) cache = state / commit with ( local_release_lock(state / "lock"), tempfile.TemporaryDirectory(prefix="planet-publish-") as tmp, ): worktree = Path(tmp) / "src" subprocess.run( ["git", "worktree", "add", "--quiet", "--detach", str(worktree), commit], check=True ) try: ensure_images(worktree, tag, commit) stage = Path(tmp) / "assets" stage.mkdir() if not already_published: for package in cached_packages(worktree, assets_dir, cache, tag, suffixes): try: os.link(package, stage / package.name) except OSError: shutil.copy2(package, stage / package.name) yield stage, worktree / "docs/CHANGELOG.md" # The verified public release now holds these bytes. Keep the cache on upload failure. if cache.exists(): shutil.rmtree(cache) finally: # This detached checkout and its generated build files are private to this invocation. subprocess.run(["git", "worktree", "remove", "--force", str(worktree)], check=True) if __name__ == "__main__": if len(sys.argv) != 2: sys.exit("Usage: production_release.py vX.Y.Z") release_tag = sys.argv[1] revision = verified_tag(release_tag) if git("rev-parse", "HEAD") != revision or git("status", "--porcelain", "--untracked-files=no"): sys.exit("Image-only CI jobs require a clean checkout at the tagged commit") ensure_images(Path.cwd(), release_tag, revision)