"""Classify repository changes into scoped Planet release targets.""" from __future__ import annotations import json import re import subprocess from dataclasses import dataclass from pathlib import Path from typing import Iterable VALID_SERVICES = ("aiprovider", "backend", "admin") VALID_CLIENT_MODES = ("none", "hotfix", "full") CLIENT_MODE_RANK = {"none": 0, "hotfix": 1, "full": 2} METADATA_EXACT = frozenset( { "AGENTS.md", "CODEMAP.md", "README.md", "VERSION", ".editorconfig", ".gitattributes", ".gitignore", "project_context.md", "rules.md", } ) METADATA_PREFIXES = ( ".codex/", ".gitea/", ".github/", "client/tests/", "docs/", "scripts/harness/", ) RELEASE_TOOLING_FILES = frozenset( { "client/scripts/dist-target.mjs", "planet.sh", "scripts/production_deploy.py", "scripts/production_registry.py", "scripts/production_release.py", "scripts/release_publish.py", "scripts/release_scope.py", } ) BACKEND_RUNTIME_FILES = frozenset( { "pyproject.toml", "uv.lock", "config/earth-boundary-pov-policy.china-v1.json", "resources/earth/boundary-pov-geometry.china-v1.json", "scripts/build_earth_boundary_china_pov_geojson.py", "scripts/build_earth_boundary_pmtiles.py", "scripts/db_migrate.py", "scripts/earth_boundary_policy.py", } ) VERSION_ONLY_FILES = frozenset( { "client/package.json", "frontend/package.json", "pyproject.toml", "uv.lock", } ) EARTH_CARDS_MANIFEST = "frontend/public/earth/assets/cards/manifest.json" @dataclass(frozen=True) class ReleaseScope: """Resolved container build targets and desktop client delivery mode.""" services: tuple[str, ...] client_mode: str components: tuple[str, ...] previous_tag: str | None = None changed_paths: tuple[str, ...] = () def to_dict(self) -> dict[str, object]: return { "services": list(self.services), "client_mode": self.client_mode, "components": list(self.components), "previous_tag": self.previous_tag, "changed_paths": list(self.changed_paths), } def _git(args: list[str], cwd: Path | None = None) -> str: return subprocess.check_output(["git", *args], cwd=cwd, text=True) def _git_show(revision: str, path: str, cwd: Path | None = None) -> str | None: try: return _git(["show", f"{revision}:{path}"], cwd=cwd) except subprocess.CalledProcessError: return None def _parse_stable_version(tag: str) -> tuple[int, int, int] | None: match = re.fullmatch(r"v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)", tag.strip()) if not match: return None return (int(match.group(1)), int(match.group(2)), int(match.group(3))) def previous_stable_tag(tag: str, tags: Iterable[str]) -> str | None: """Return the highest stable release tag strictly lower than ``tag``.""" target = _parse_stable_version(tag) if target is None: return None candidates: list[tuple[tuple[int, int, int], str]] = [] for raw in tags: ver = _parse_stable_version(raw) if ver is not None and ver < target: candidates.append((ver, raw.strip())) if not candidates: return None candidates.sort() return candidates[-1][1] def _normalize_package_json(raw: str) -> object | None: try: data = json.loads(raw) except json.JSONDecodeError: return None if not isinstance(data, dict): return None return {k: v for k, v in data.items() if k != "version"} def _normalize_pyproject(raw: str) -> str: return re.sub(r'(?m)^version\s*=\s*["\'][^"\']*["\']\s*$', "version = ", raw) def _normalize_uv_lock(raw: str) -> str: return re.sub( r'(\[\[package\]\]\s*\nname\s*=\s*"planet"\s*\nversion\s*=\s*)"[^"]+"', r'\1""', raw, count=1, ) def is_version_only_change(prev_ref: str, commit: str, path: str, cwd: Path | None = None) -> bool: """Return True when a version-bearing manifest only bumped the root Planet version.""" if path not in VERSION_ONLY_FILES: return False before = _git_show(prev_ref, path, cwd=cwd) after = _git_show(commit, path, cwd=cwd) if before is None or after is None: return False if path in ("client/package.json", "frontend/package.json"): norm_before = _normalize_package_json(before) norm_after = _normalize_package_json(after) return norm_before is not None and norm_before == norm_after if path == "pyproject.toml": return _normalize_pyproject(before) == _normalize_pyproject(after) if path == "uv.lock": return _normalize_uv_lock(before) == _normalize_uv_lock(after) return False def _is_metadata_or_tooling(path: str) -> bool: return ( path in METADATA_EXACT or path in RELEASE_TOOLING_FILES or any(path.startswith(prefix) for prefix in METADATA_PREFIXES) ) def _derive_components(services: set[str], client_mode: str) -> tuple[str, ...]: ordered: list[str] = [svc for svc in VALID_SERVICES if svc in services] if client_mode == "hotfix": ordered.append("earth-hotfix") elif client_mode == "full": ordered.append("client-shell") if not ordered: ordered.append("metadata") return tuple(ordered) def classify_changed_paths( paths: Iterable[str], *, previous_tag: str | None = None, ) -> ReleaseScope: """Classify changed repository paths into service image builds and client mode.""" normalized_paths = tuple( sorted({p.strip().lstrip("./").replace("\\", "/") for p in paths if p and p.strip()}) ) services: set[str] = set() client_mode = "none" for path in normalized_paths: if _is_metadata_or_tooling(path): continue if path.startswith("aiprovider/"): services.add("aiprovider") continue if path.startswith(("backend/", "alembic/")) or path in BACKEND_RUNTIME_FILES: services.add("backend") continue if path.startswith("frontend/public/earth/"): if CLIENT_MODE_RANK["hotfix"] > CLIENT_MODE_RANK[client_mode]: client_mode = "hotfix" if path == EARTH_CARDS_MANIFEST: services.add("backend") continue if path.startswith("frontend/"): services.add("admin") continue if path.startswith("client/"): client_mode = "full" continue # Infra/compose/root or unknown paths fall back to rebuilding all services safely. services.update(VALID_SERVICES) ordered_services = tuple(svc for svc in VALID_SERVICES if svc in services) return ReleaseScope( services=ordered_services, client_mode=client_mode, components=_derive_components(services, client_mode), previous_tag=previous_tag, changed_paths=normalized_paths, ) def parse_scope_override(raw: str | None, *, previous_tag: str | None = None) -> ReleaseScope | None: """Parse an explicit ``--scope`` value, or return None for auto-detection.""" if raw is None: return None text = raw.strip().lower() if not text or text == "auto": return None if text == "full": return ReleaseScope( services=VALID_SERVICES, client_mode="full", components=_derive_components(set(VALID_SERVICES), "full"), previous_tag=previous_tag, ) services: set[str] = set() client_mode = "none" for token in (part.strip() for part in text.split(",") if part.strip()): if token in VALID_SERVICES: services.add(token) elif token in ("hotfix", "earth", "earth-hotfix"): if CLIENT_MODE_RANK["hotfix"] > CLIENT_MODE_RANK[client_mode]: client_mode = "hotfix" elif token in ("client", "client-shell", "desktop"): client_mode = "full" elif token in ("none", "metadata", "docs"): continue else: raise ValueError( f"Unsupported release scope token {token!r}; expected auto, full, none, " "aiprovider, backend, admin, hotfix, or client-shell" ) ordered_services = tuple(svc for svc in VALID_SERVICES if svc in services) return ReleaseScope( services=ordered_services, client_mode=client_mode, components=_derive_components(services, client_mode), previous_tag=previous_tag, ) def resolve_release_scope( tag: str, commit: str, *, override: str | None = None, cwd: Path | None = None, ) -> ReleaseScope: """Determine scoped release targets from git history unless explicitly overridden.""" all_tags = _git(["tag", "--list", "v*"], cwd=cwd).splitlines() prev_tag = previous_stable_tag(tag, all_tags) explicit = parse_scope_override(override, previous_tag=prev_tag) if explicit is not None: return explicit if prev_tag is None: return ReleaseScope( services=VALID_SERVICES, client_mode="full", components=_derive_components(set(VALID_SERVICES), "full"), previous_tag=None, ) raw_paths = _git(["diff", "--name-only", f"{prev_tag}..{commit}"], cwd=cwd).splitlines() effective_paths = [ path for path in raw_paths if path.strip() and not is_version_only_change(prev_tag, commit, path.strip(), cwd=cwd) ] return classify_changed_paths(effective_paths, previous_tag=prev_tag)