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