#!/usr/bin/env python3 """Create and atomically commit a reviewed local Git patch candidate.""" from __future__ import annotations import argparse from contextlib import contextmanager import fcntl import hashlib import json import os from pathlib import Path, PurePosixPath import re import subprocess import sys import tempfile import time STARTED = time.monotonic() class Blocked(RuntimeError): pass def debug(message: str) -> None: if os.environ.get("OPENCODE_COMMIT_DEBUG") == "1" or os.environ.get("DEBUG") == "1": print(f"[commit-helper +{time.monotonic() - STARTED:.3f}s] {message}", file=sys.stderr, flush=True) def git(root: Path, *args: str, env: dict[str, str] | None = None, check: bool = True, input_data: bytes | None = None) -> subprocess.CompletedProcess[bytes]: started = time.monotonic() result = subprocess.run(["git", "-C", str(root), *args], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, input=input_data, check=False) debug(f"git {' '.join(args)}: status={result.returncode} duration={time.monotonic() - started:.3f}s") if check and result.returncode: raise Blocked(result.stderr.decode("utf-8", "replace").strip() or f"git {' '.join(args)} failed") return result def repository_root() -> Path: result = subprocess.run(["git", "rev-parse", "--show-toplevel"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) if result.returncode: raise Blocked("current directory is not a Git repository") return Path(result.stdout.decode().strip()).resolve() def candidate_directory(root: Path) -> Path: configured = os.environ.get("OPENCODE_COMMIT_CANDIDATE_DIR") if configured: directory = Path(configured) else: identity = hashlib.sha256(str(root).encode("utf-8")).hexdigest() directory = Path("/tmp/opencode/commit-candidates") / identity directory.mkdir(mode=0o700, parents=True, exist_ok=True) os.chmod(directory, 0o700) return directory.resolve() def git_path(root: Path, name: str) -> Path: path = Path(git(root, "rev-parse", "--git-path", name).stdout.decode().strip()) return (path if path.is_absolute() else root / path).resolve() def git_common_directory(root: Path) -> Path: path = Path(git(root, "rev-parse", "--git-common-dir").stdout.decode().strip()) return (path if path.is_absolute() else root / path).resolve() def forbidden_path(path: str) -> bool: name = PurePosixPath(path).name return (name == ".env" or (name.startswith(".env.") and name != ".env.example") or name in { ".secret", ".npmrc", ".vault-password", "credentials.json", "credentials.yaml", "credentials.yml", "id_ed25519", "id_rsa", "private.pem", "server.pem", "secrets.json", "secrets.yaml", "secrets.yml", "secrets.toml", "token.txt", } or name.endswith((".key", ".p12", ".pfx", ".secret"))) def normalize_pathspecs(root: Path, raw: list[str]) -> list[str]: if not raw: raise Blocked("at least one explicit path is required") paths: list[str] = [] for value in raw: if not value or "\n" in value or "\0" in value: raise Blocked("empty paths and paths containing newline or NUL are forbidden") if value.startswith(":") or any(character in value for character in "*?["): raise Blocked(f"Git pathspec magic and globs are forbidden: {value}") path = PurePosixPath(value.removeprefix("./")) if path.is_absolute() or ".." in path.parts or not path.parts or path.parts[0] == ".git": raise Blocked(f"unsafe path: {value}") clean = path.as_posix() if clean not in paths: paths.append(clean) for path in paths: if forbidden_path(path): raise Blocked(f"secret-bearing path is forbidden: {path}") ignored = git(root, "check-ignore", "-q", "--", path, check=False) if ignored.returncode == 0: raise Blocked(f"ignored path is forbidden: {path}") if ignored.returncode not in {0, 1}: raise Blocked(f"failed to check ignore rules for: {path}") return paths def require_clean_index(root: Path) -> None: result = git(root, "diff", "--cached", "--quiet", "--exit-code", check=False) if result.returncode == 1: raise Blocked("pre-existing staged changes must be resolved first") if result.returncode: raise Blocked("failed to inspect the Git index") def all_changed_paths(root: Path) -> list[str]: tracked = git(root, "diff", "--name-only", "--no-renames", "-z", "HEAD").stdout untracked = git(root, "ls-files", "--others", "--exclude-standard", "-z").stdout paths: list[str] = [] for item in (tracked + untracked).split(b"\0"): if item: path = item.decode("utf-8", "surrogateescape") if path not in paths: paths.append(path) return paths def candidate_patch(root: Path, pathspecs: list[str]) -> tuple[bytes, list[str], str, str]: directory = candidate_directory(root) descriptor, index_name = tempfile.mkstemp(prefix="index-", dir=directory) os.close(descriptor) os.unlink(index_name) environment = os.environ.copy() environment["GIT_INDEX_FILE"] = index_name try: git(root, "read-tree", "HEAD", env=environment) git(root, "add", "-A", "--", *pathspecs, env=environment) check = git(root, "diff", "--cached", "--check", env=environment, check=False) if check.returncode: raise Blocked((check.stdout + check.stderr).decode("utf-8", "replace").strip() or "candidate diff check failed") patch = git(root, "diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "--no-color", "HEAD", env=environment).stdout names = [item.decode("utf-8", "surrogateescape") for item in git(root, "diff", "--cached", "--name-only", "-z", "HEAD", env=environment).stdout.split(b"\0") if item] status = git(root, "diff", "--cached", "--name-status", "HEAD", env=environment).stdout.decode("utf-8", "replace").rstrip() stat = git(root, "diff", "--cached", "--stat", "HEAD", env=environment).stdout.decode("utf-8", "replace").rstrip() return patch, names, status, stat finally: try: os.unlink(index_name) except FileNotFoundError: pass def patch_hash(patch: bytes) -> str: return hashlib.sha256(patch).hexdigest() def metadata_path(root: Path, identifier: str) -> Path: if not re.fullmatch(r"[0-9a-f]{64}", identifier): raise Blocked("invalid candidate identifier") return candidate_directory(root) / f"{identifier}.json" def save_candidate(root: Path, data: dict[str, object], patch: bytes) -> str: encoded = json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") identifier = hashlib.sha256(encoded).hexdigest() destination = metadata_path(root, identifier) with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=destination.parent, delete=False) as handle: temporary = Path(handle.name) os.chmod(temporary, 0o600) json.dump(data, handle, ensure_ascii=False, sort_keys=True) handle.write("\n") os.replace(temporary, destination) os.chmod(destination, 0o600) with tempfile.NamedTemporaryFile("wb", dir=destination.parent, delete=False) as handle: temporary_patch = Path(handle.name) os.chmod(temporary_patch, 0o600) handle.write(patch) os.replace(temporary_patch, destination.with_suffix(".patch")) os.chmod(destination.with_suffix(".patch"), 0o600) return identifier def inspect_command(paths: list[str], show_patch: bool) -> int: root = repository_root() require_clean_index(root) selection = "explicit" if not paths: paths, selection = all_changed_paths(root), "all-worktree" pathspecs = normalize_pathspecs(root, paths) head = git(root, "rev-parse", "HEAD").stdout.decode().strip() patch, changed_paths, name_status, stat = candidate_patch(root, pathspecs) if not patch: raise Blocked("selected paths contain no changes") forbidden = next((path for path in changed_paths if forbidden_path(path)), None) if forbidden: raise Blocked(f"candidate contains secret-bearing path: {forbidden}") data: dict[str, object] = {"version": 1, "repository": str(root), "head": head, "pathspecs": pathspecs, "changed_paths": changed_paths, "patch_sha256": patch_hash(patch), "selection": selection} identifier = save_candidate(root, data, patch) status = git(root, "status", "--short", "--branch").stdout.decode("utf-8", "replace").rstrip() records = len([item for item in git(root, "status", "--porcelain=v1", "-z").stdout.split(b"\0") if item]) print(f"COMMIT_CANDIDATE {identifier}") print(f"head={head[:12]} candidate_paths={len(changed_paths)} worktree_records={records} selection={selection} diff_check=ok") print(f"patch_file={metadata_path(root, identifier).with_suffix('.patch')}") print("--- worktree status ---\n" + status + "\n--- candidate files ---\n" + name_status + "\n--- diff stat ---\n" + stat) if show_patch: print("--- candidate patch ---") sys.stdout.flush() sys.stdout.buffer.write(patch + (b"" if patch.endswith(b"\n") else b"\n")) return 0 def load_candidate(root: Path, identifier: str) -> tuple[Path, Path, dict[str, object], bytes]: path = metadata_path(root, identifier) try: data = json.loads(path.read_text(encoding="utf-8")) patch = path.with_suffix(".patch").read_bytes() except FileNotFoundError as error: raise Blocked("candidate does not exist or was already consumed") from error encoded = json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") if data.get("version") != 1 or hashlib.sha256(encoded).hexdigest() != identifier: raise Blocked("candidate metadata changed; inspect a new candidate") if patch_hash(patch) != data.get("patch_sha256"): raise Blocked("candidate patch storage changed; inspect a new candidate") return path, path.with_suffix(".patch"), data, patch def consume(metadata: Path, patch: Path) -> None: metadata.unlink(missing_ok=True) patch.unlink(missing_ok=True) @contextmanager def commit_lock(root: Path): lock_path = git_common_directory(root) / "opencode-commit-candidate.lock" with open(lock_path, "a", encoding="utf-8") as handle: os.chmod(lock_path, 0o600) try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as error: raise Blocked("another commit helper is active for this repository") from error yield def file_content(path: Path) -> bytes | None: try: return path.read_bytes() except FileNotFoundError: return None def selected_worktree_changed(root: Path, paths: list[str]) -> bool: tracked = git(root, "diff", "--quiet", "--exit-code", "HEAD", "--", *paths, check=False) if tracked.returncode == 1: return True if tracked.returncode != 0: raise Blocked("failed to recheck selected worktree paths") return bool(git(root, "ls-files", "--others", "--exclude-standard", "-z", "--", *paths).stdout) def synchronize_index(root: Path, head: str, before: bytes | None, paths: list[str]) -> str: index = git_path(root, "index") lock = Path(f"{index}.lock") try: descriptor = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) except FileExistsError: return "skipped-concurrent-index-lock" try: if file_content(index) != before: return "skipped-concurrent-index-change" descriptor2, temporary = tempfile.mkstemp(prefix="synced-index-", dir=candidate_directory(root)) if before is None: os.close(descriptor2) os.unlink(temporary) else: with os.fdopen(descriptor2, "wb") as handle: handle.write(before) environment = os.environ.copy() environment["GIT_INDEX_FILE"] = temporary try: if before is None: git(root, "read-tree", head, env=environment) else: git(root, "reset", "-q", head, "--", *paths, env=environment) content = Path(temporary).read_bytes() finally: Path(temporary).unlink(missing_ok=True) with os.fdopen(descriptor, "wb", closefd=False) as handle: handle.write(content) handle.flush() os.fsync(handle.fileno()) os.close(descriptor) descriptor = -1 os.replace(lock, index) return "ok" finally: if descriptor >= 0: os.close(descriptor) lock.unlink(missing_ok=True) @contextmanager def reviewed_index(root: Path, head: str, patch: bytes): descriptor, name = tempfile.mkstemp(prefix="commit-index-", dir=candidate_directory(root)) os.close(descriptor) os.unlink(name) environment = os.environ.copy() environment["GIT_INDEX_FILE"] = name try: git(root, "read-tree", head, env=environment) git(root, "apply", "--cached", "--whitespace=nowarn", env=environment, input_data=patch) yield environment finally: Path(name).unlink(missing_ok=True) def commit_command(identifier: str) -> int: root = repository_root() metadata, patch_file, data, patch = load_candidate(root, identifier) message = sys.stdin.read().removesuffix("\n") if not message or "\n" in message or "\0" in message: raise Blocked("commit message must be one non-empty line on stdin") if data.get("repository") != str(root): raise Blocked("candidate belongs to another repository") if data.get("selection") == "all-worktree" and os.environ.get("OPENCODE_COMMIT_ALLOW_ALL_WORKTREE") != "1": raise Blocked("all-worktree candidate requires explicit paths or OPENCODE_COMMIT_ALLOW_ALL_WORKTREE=1") paths = [str(item) for item in data.get("pathspecs", [])] with commit_lock(root): require_clean_index(root) before_head = git(root, "rev-parse", "HEAD").stdout.decode().strip() if before_head != data.get("head"): consume(metadata, patch_file) raise Blocked("HEAD changed; inspect a new candidate") current, _, _, _ = candidate_patch(root, paths) if patch_hash(current) != data.get("patch_sha256"): consume(metadata, patch_file) raise Blocked("candidate patch changed; inspect a new candidate") real_index = file_content(git_path(root, "index")) with reviewed_index(root, before_head, patch) as environment: staged = git(root, "diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "--no-color", "HEAD", env=environment).stdout if patch_hash(staged) != data.get("patch_sha256"): consume(metadata, patch_file) raise Blocked("temporary index differs from the reviewed candidate") check = git(root, "diff", "--cached", "--check", env=environment, check=False) if check.returncode: consume(metadata, patch_file) raise Blocked((check.stdout + check.stderr).decode("utf-8", "replace").strip() or "candidate diff check failed") expected_tree = git(root, "write-tree", env=environment).stdout.decode().strip() result = git(root, "commit", "-m", message, env=environment, check=False) after = git(root, "rev-parse", "HEAD", check=False) if after.returncode or after.stdout.decode().strip() == before_head: consume(metadata, patch_file) raise Blocked((result.stdout + result.stderr).decode("utf-8", "replace").strip() or "git commit failed") after_head = after.stdout.decode().strip() consume(metadata, patch_file) try: parent = git(root, "rev-parse", f"{after_head}^").stdout.decode().strip() tree = git(root, "rev-parse", f"{after_head}^{{tree}}").stdout.decode().strip() if parent != before_head or tree != expected_tree: print(f"COMMIT_CREATED_VERIFICATION_FAILED {after_head} parent-or-tree-mismatch") return 2 index_sync = synchronize_index(root, after_head, real_index, paths) changed_after = selected_worktree_changed(root, paths) short = git(root, "rev-parse", "--short", after_head).stdout.decode().strip() subject = git(root, "show", "-s", "--format=%s", after_head).stdout.decode().strip() remaining = len([item for item in git(root, "status", "--porcelain=v1", "-z").stdout.split(b"\0") if item]) except Exception as error: print(f"COMMIT_CREATED_VERIFICATION_FAILED {after_head} {type(error).__name__}: {error}") return 2 if changed_after: print(f"COMMIT_CREATED_WORKTREE_CHANGED {short} {subject}") print(f"files={len(data.get('changed_paths', []))} worktree_records={remaining} index_sync={index_sync} git_commit_status={result.returncode}") return 2 label = "COMMIT_OK" if result.returncode == 0 else "COMMIT_CREATED_HOOK_FAILED" print(f"{label} {short} {subject}") print(f"files={len(data.get('changed_paths', []))} worktree_records={remaining} index_sync={index_sync} git_commit_status={result.returncode}") return 0 if result.returncode == 0 else 2 def main() -> int: parser = argparse.ArgumentParser() commands = parser.add_subparsers(dest="command", required=True) inspect = commands.add_parser("inspect") inspect.add_argument("paths", nargs="*") inspect.add_argument("--paths-stdin", action="store_true") inspect.add_argument("--show-patch", action="store_true") commit = commands.add_parser("commit") candidate_source = commit.add_mutually_exclusive_group(required=True) candidate_source.add_argument("--candidate") candidate_source.add_argument("--candidate-env", action="store_true") commit.add_argument("--message-stdin", action="store_true", required=True) arguments = parser.parse_args() try: if arguments.command == "inspect": paths = arguments.paths if arguments.paths_stdin: if paths: raise Blocked("paths must come either from arguments or stdin") paths = sys.stdin.read().splitlines() return inspect_command(paths, arguments.show_patch) identifier = os.environ.get("OPENCODE_COMMIT_CANDIDATE", "") if arguments.candidate_env else arguments.candidate if not identifier: raise Blocked("candidate is required") return commit_command(identifier) except Blocked as error: print(f"COMMIT_BLOCKED {error}") return 1 if __name__ == "__main__": raise SystemExit(main())