|
| 1 | +"""Crash-safe prepare-commit-msg hook installation and execution.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import os |
| 6 | +import stat |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import tempfile |
| 10 | +import time |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +HOOK_TIMEOUT_SECONDS = 4 |
| 14 | +HOOK_MARKER = "# Installed by gitmate; managed by `gitmate install-hook`." |
| 15 | + |
| 16 | +HOOK_SCRIPT = f"""#!/bin/sh |
| 17 | +{HOOK_MARKER} |
| 18 | +# Crash-safe launcher for gitmate's prepare-commit-msg worker. |
| 19 | +PYTHON="{sys.executable}" |
| 20 | +if [ ! -x "$PYTHON" ]; then |
| 21 | + if command -v python3 >/dev/null 2>&1; then |
| 22 | + PYTHON="python3" |
| 23 | + else |
| 24 | + exit 0 |
| 25 | + fi |
| 26 | +fi |
| 27 | +exec "$PYTHON" -c ' |
| 28 | +import subprocess, sys |
| 29 | +try: |
| 30 | + subprocess.run( |
| 31 | + [sys.executable, "-m", "gitmate.hooks", "--worker", *sys.argv[1:]], |
| 32 | + timeout={HOOK_TIMEOUT_SECONDS}, |
| 33 | + check=False, |
| 34 | + stdout=subprocess.DEVNULL, |
| 35 | + stderr=subprocess.DEVNULL, |
| 36 | + ) |
| 37 | +except BaseException: |
| 38 | + pass |
| 39 | +sys.exit(0) |
| 40 | +' "$@" |
| 41 | +""" |
| 42 | + |
| 43 | + |
| 44 | +class HookError(Exception): |
| 45 | + """Raised when a hook cannot be safely installed or removed.""" |
| 46 | + |
| 47 | + |
| 48 | +def _hook_path(cwd: Path | None = None) -> Path: |
| 49 | + """Resolve the repository's active prepare-commit-msg hook path.""" |
| 50 | + repo = cwd if cwd is not None else Path.cwd() |
| 51 | + try: |
| 52 | + result = subprocess.run( |
| 53 | + ["git", "rev-parse", "--git-path", "hooks/prepare-commit-msg"], |
| 54 | + cwd=repo, |
| 55 | + capture_output=True, |
| 56 | + text=True, |
| 57 | + timeout=2, |
| 58 | + check=True, |
| 59 | + ) |
| 60 | + except (OSError, subprocess.SubprocessError) as exc: |
| 61 | + raise HookError(f"cannot locate the prepare-commit-msg hook: {exc}") from exc |
| 62 | + path = Path(result.stdout.strip()) |
| 63 | + return path if path.is_absolute() else (repo / path).resolve() |
| 64 | + |
| 65 | + |
| 66 | +def install_hook(cwd: Path | None = None) -> Path: |
| 67 | + """Install the crash-safe hook, refusing to replace user-owned hooks.""" |
| 68 | + path = _hook_path(cwd) |
| 69 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 70 | + if path.exists(): |
| 71 | + content = path.read_text(encoding="utf-8", errors="replace") |
| 72 | + if HOOK_MARKER not in content: |
| 73 | + raise HookError(f"{path} already exists; move or remove it before installing gitmate.") |
| 74 | + path.write_text(HOOK_SCRIPT, encoding="utf-8") |
| 75 | + path.chmod(path.stat().st_mode | 0o111) |
| 76 | + return path |
| 77 | + |
| 78 | + |
| 79 | +def uninstall_hook(cwd: Path | None = None) -> Path: |
| 80 | + """Remove the gitmate hook while preserving hooks owned by other tools.""" |
| 81 | + path = _hook_path(cwd) |
| 82 | + if not path.exists(): |
| 83 | + return path |
| 84 | + content = path.read_text(encoding="utf-8", errors="replace") |
| 85 | + if HOOK_MARKER not in content: |
| 86 | + raise HookError(f"{path} is not a gitmate-managed hook; it was left untouched.") |
| 87 | + path.unlink() |
| 88 | + return path |
| 89 | + |
| 90 | + |
| 91 | +def main() -> int: |
| 92 | + """Run the hook worker with a hard timeout and unconditional success status.""" |
| 93 | + args = sys.argv[1:] |
| 94 | + if args and args[0] == "--worker": |
| 95 | + try: |
| 96 | + _run_worker(args[1:]) |
| 97 | + except BaseException: # noqa: BLE001, S110 |
| 98 | + pass |
| 99 | + return 0 |
| 100 | + |
| 101 | + if args: |
| 102 | + source = os.environ.get("PRE_COMMIT_COMMIT_MSG_SOURCE") |
| 103 | + commit_hash = os.environ.get("PRE_COMMIT_COMMIT_OBJECT_NAME") |
| 104 | + if len(args) == 1 and source: |
| 105 | + args.append(source) |
| 106 | + if len(args) == 2 and commit_hash: |
| 107 | + args.append(commit_hash) |
| 108 | + |
| 109 | + try: |
| 110 | + subprocess.run( |
| 111 | + [sys.executable, "-m", "gitmate.hooks", "--worker", *args], |
| 112 | + timeout=HOOK_TIMEOUT_SECONDS, |
| 113 | + check=False, |
| 114 | + stdout=subprocess.DEVNULL, |
| 115 | + stderr=subprocess.DEVNULL, |
| 116 | + ) |
| 117 | + except BaseException: # noqa: BLE001, S110 |
| 118 | + pass |
| 119 | + return 0 |
| 120 | + |
| 121 | + |
| 122 | +def _run_worker(args: list[str]) -> None: |
| 123 | + """Generate a message for supported Git hook sources without committing.""" |
| 124 | + if not args or len(args) > 3: |
| 125 | + return |
| 126 | + message_file = Path(args[0]) |
| 127 | + source = args[1] if len(args) > 1 else "" |
| 128 | + if source not in ("", "template") or not message_file.is_file(): |
| 129 | + return |
| 130 | + |
| 131 | + from gitmate import config as config_mod |
| 132 | + from gitmate.diff_extractor import DiffExtractor |
| 133 | + from gitmate.fallback import generate_commit_message, generate_fallback_message |
| 134 | + from gitmate.orchestrator import BudgetCapExceededError, safe_record_telemetry |
| 135 | + |
| 136 | + cfg = config_mod.load_config() |
| 137 | + diffs = DiffExtractor(extra_ignores=cfg.ignore_globs).staged() |
| 138 | + if not diffs: |
| 139 | + return |
| 140 | + started = time.perf_counter() |
| 141 | + try: |
| 142 | + result = generate_commit_message( |
| 143 | + diffs=diffs, |
| 144 | + cfg=cfg, |
| 145 | + console=None, |
| 146 | + command="commit-hook", |
| 147 | + hook_mode=True, |
| 148 | + ) |
| 149 | + generated = result.text.rstrip() |
| 150 | + except BudgetCapExceededError: |
| 151 | + generated = generate_fallback_message(diffs, style=cfg.commit_style) |
| 152 | + safe_record_telemetry( |
| 153 | + command="commit-hook", |
| 154 | + model=cfg.model, |
| 155 | + tokens_in=None, |
| 156 | + tokens_out=None, |
| 157 | + cache_hit=False, |
| 158 | + latency_ms=int((time.perf_counter() - started) * 1000), |
| 159 | + fallback_used=True, |
| 160 | + estimated_cost_usd=0.0, |
| 161 | + free_tier=cfg.free_tier, |
| 162 | + ) |
| 163 | + existing = message_file.read_text(encoding="utf-8", errors="replace") |
| 164 | + if existing.strip(): |
| 165 | + new_message = f"{generated}\n\n{existing.lstrip()}" |
| 166 | + else: |
| 167 | + new_message = f"{generated}\n" |
| 168 | + _replace_message(message_file, new_message) |
| 169 | + |
| 170 | + |
| 171 | +def _replace_message(message_file: Path, message: str) -> None: |
| 172 | + """Atomically replace Git's message file so write failures preserve its contents.""" |
| 173 | + cutoff = time.time() - HOOK_TIMEOUT_SECONDS |
| 174 | + for stale in message_file.parent.glob(f".{message_file.name}.*"): |
| 175 | + try: |
| 176 | + if stale.is_file() and stale.stat().st_mtime < cutoff: |
| 177 | + stale.unlink() |
| 178 | + except OSError: |
| 179 | + continue |
| 180 | + |
| 181 | + mode = stat.S_IMODE(message_file.stat().st_mode) |
| 182 | + temp_path: Path | None = None |
| 183 | + try: |
| 184 | + with tempfile.NamedTemporaryFile( |
| 185 | + mode="w", |
| 186 | + encoding="utf-8", |
| 187 | + dir=message_file.parent, |
| 188 | + prefix=f".{message_file.name}.", |
| 189 | + delete=False, |
| 190 | + ) as temp_file: |
| 191 | + temp_path = Path(temp_file.name) |
| 192 | + temp_file.write(message) |
| 193 | + temp_path.chmod(mode) |
| 194 | + os.replace(temp_path, message_file) |
| 195 | + finally: |
| 196 | + if temp_path is not None and temp_path.exists(): |
| 197 | + temp_path.unlink() |
| 198 | + |
| 199 | + |
| 200 | +if __name__ == "__main__": |
| 201 | + raise SystemExit(main()) |
0 commit comments