Skip to content

Commit 69478e5

Browse files
Merge pull request #13 from getdownandcode/feat
feat: add crash-safe prepare-commit-msg hooks
2 parents 16323ed + 59e2bde commit 69478e5

16 files changed

Lines changed: 823 additions & 28 deletions

‎.pre-commit-hooks.yaml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
- id: gitmate-prepare-commit-msg
2+
name: Generate a commit message with gitmate
3+
description: Safely generate a commit message before the editor opens.
4+
entry: gitmate-hook
5+
language: python
6+
stages: [prepare-commit-msg]
7+
pass_filenames: true

‎README.md‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ uv sync --extra dev
2121
uv run pytest
2222
```
2323

24-
## Usage (Phases 0–4)
24+
## Usage
2525

2626
```bash
2727
uv run gitmate --help
@@ -37,15 +37,53 @@ uv run gitmate config set cache_dir /path/to/cache # custom prompt cache d
3737
uv run gitmate debug-diff # staged diff: per-file table + cleaned patch
3838
uv run gitmate debug-diff --summary # per-file stats table only, no patch text
3939
uv run gitmate debug-diff --base main # branch-vs-main diff (PR path)
40+
uv run gitmate commit # review, edit, accept, or cancel a message
41+
uv run gitmate pr-summary --base main
42+
uv run gitmate changelog --from v1.0.0 --to v1.1.0
43+
uv run gitmate stats
44+
uv run gitmate install-hook # optional local prepare-commit-msg hook
45+
uv run gitmate uninstall-hook # remove the local hook
4046
```
4147

4248
Phase 4 introduces versioned prompt templates (`src/gitmate/templates/`: `commit_conventional.txt`,
4349
`commit_plain.txt`, `pr_summary.txt`) and deterministic template-based fallback degradation
4450
(`fallback.py`). When the LLM backend is offline, rate-limited, unauthenticated, or fails retries,
4551
`generate_commit_message` warns the user (`⚠ API unavailable, using template fallback`) and
4652
derives a clean commit message directly from diff metadata without making an LLM call.
47-
`commit`, `pr-summary`, `changelog`, and `doc` remain stubbed until their phases
48-
land — see `AGENTS.md` and the phased roadmap for details.
53+
`doc` is an unscheduled stub; commit, PR summary, changelog, stats, and hook
54+
commands are implemented.
55+
56+
### Automatic commit message generation
57+
58+
For a personal checkout, run `gitmate install-hook`. It installs a local
59+
`prepare-commit-msg` hook; Git opens the usual editor with the generated message
60+
so you can review or change it before saving. The hook never runs `git commit`
61+
and has a four-second generation timeout. If generation fails or times out, it
62+
leaves Git's existing message in place and exits successfully so the commit is
63+
not blocked. It only generates when the source is `template` or absent; explicit
64+
`git commit -m`/`-F` messages (`message`), merge messages (`merge`), squash
65+
messages (`squash`), and other source values are left alone. Existing hooks are
66+
refused rather than overwritten; `gitmate uninstall-hook` removes only the
67+
gitmate-managed hook. Both commands work with Git's configured `core.hooksPath`.
68+
69+
For teams using the `pre-commit` framework, add this to `.pre-commit-config.yaml`
70+
and run `pre-commit install --hook-type prepare-commit-msg`:
71+
72+
```yaml
73+
repos:
74+
- repo: https://github.com/getdownandcode/gitmate
75+
rev: <gitmate-version>
76+
hooks:
77+
- id: gitmate-prepare-commit-msg
78+
```
79+
80+
The repository's `.pre-commit-hooks.yaml` declares the `prepare-commit-msg`
81+
stage and `language: python`, so pre-commit installs gitmate into its isolated
82+
environment for each adopting checkout. `keyring` still uses the user's OS
83+
credential store from that environment; the API key is not copied into the
84+
repository or the pre-commit environment. The `gitmate install-hook` route is
85+
local-only because `.git/hooks` is not version controlled; the pre-commit route
86+
lets a team version the hook declaration for everyone who opts in.
4987

5088
## Diagrams
5189

‎plan.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,10 +142,13 @@ the loop. Goal: something you actually run every day, not just a portfolio repo.
142142

143143
**Goal:** stop having to remember to run the tool at all.
144144

145-
- Ship a `prepare-commit-msg` git hook script that calls `gitmate commit --hook-mode` (non-interactive generate, writes to the commit message file git already opens in your editor — so you review inside your normal `git commit` flow, no extra step).
146-
- Also provide a `.pre-commit-hooks.yaml` so people using the `pre-commit` framework can add it with one config line.
145+
- Ship an optional local `prepare-commit-msg` hook. It calls only the generation pipeline, writes the message for Git's normal editor, and never runs `git commit` or the interactive accept/edit/regenerate loop.
146+
- Fail open: the launcher catches failures and exits 0; the generation worker has a four-second timeout and uses Phase 4 fallback when available. Message writes are atomic so a failed write leaves Git's original message intact.
147+
- Generate only when the source is `template` or absent. Leave `message` (explicit `-m`/`-F`), `merge`, `squash`, and all other source values untouched.
148+
- Refuse to overwrite an existing hook, support idempotent install and managed-hook uninstall, and honor Git's configured hooks path.
149+
- Also provide `.pre-commit-hooks.yaml` with `language: python` and `stages: [prepare-commit-msg]` for team adoption. The local `.git/hooks` installer is for one developer; the versioned pre-commit declaration is for teams. Its isolated environment still uses the user's OS credential store through keyring.
147150

148-
**Deliverables:** `gitmate install-hook` command that symlinks/writes the hook into `.git/hooks/`, documented `pre-commit` config snippet.
151+
**Deliverables:** `gitmate install-hook` and `gitmate uninstall-hook`, crash/timeout safe real-repository tests, and a documented pre-commit config snippet.
149152

150153
**Tech:** `pre-commit` framework config format, plain shell/Python hook script.
151154

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ dev = [
3232

3333
[project.scripts]
3434
gitmate = "gitmate.cli:app"
35+
gitmate-hook = "gitmate.hooks:main"
3536

3637
[tool.ruff]
3738
line-length = 100

‎src/gitmate/cli.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,34 @@ def commit(
4242
raise typer.Exit(code)
4343

4444

45+
@app.command("install-hook")
46+
def install_hook() -> None:
47+
"""Install gitmate's local prepare-commit-msg hook in this repository."""
48+
from gitmate.hooks import HookError
49+
from gitmate.hooks import install_hook as install
50+
51+
try:
52+
path = install()
53+
except HookError as exc:
54+
err_console.print(f"[red]error:[/red] {exc}")
55+
raise typer.Exit(1) from None
56+
console.print(f"[green]Installed prepare-commit-msg hook:[/green] {path}")
57+
58+
59+
@app.command("uninstall-hook")
60+
def uninstall_hook() -> None:
61+
"""Remove gitmate's local prepare-commit-msg hook."""
62+
from gitmate.hooks import HookError
63+
from gitmate.hooks import uninstall_hook as uninstall
64+
65+
try:
66+
path = uninstall()
67+
except HookError as exc:
68+
err_console.print(f"[red]error:[/red] {exc}")
69+
raise typer.Exit(1) from None
70+
console.print(f"[green]Removed gitmate prepare-commit-msg hook:[/green] {path}")
71+
72+
4573
@app.command()
4674
def stats(
4775
days: int | None = typer.Option(None, "--days", "-d", help="Limit stats to the last N days."),

‎src/gitmate/config.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,11 @@ def get_context_window(cfg: GitmateConfig) -> int:
132132
return cfg.max_context_tokens
133133
if cfg.model in DEFAULT_MODEL_CONTEXT_WINDOWS:
134134
return DEFAULT_MODEL_CONTEXT_WINDOWS[cfg.model]
135+
model_name = cfg.model.lower()
136+
if model_name.startswith("gemini"):
137+
return 1_048_576
138+
if model_name.startswith("claude"):
139+
return 200_000
135140
raise UnknownModelError(
136141
f"unknown model {cfg.model!r} with no context window configured. "
137142
"Set 'max_context_tokens' in config.toml or use a known model."

‎src/gitmate/fallback.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,8 @@ def generate_commit_message(
262262
console: Console | None = None,
263263
secret_store: config_mod.SecretStore | None = None,
264264
bypass_cache: bool = False,
265+
command: str | None = None,
266+
hook_mode: bool = False,
265267
) -> GenerationResult:
266268
"""Orchestrate commit message generation with graceful fallback on provider failure."""
267269
return run_generation_pipeline(
@@ -270,6 +272,8 @@ def generate_commit_message(
270272
template_name=cfg.commit_style,
271273
fallback_generator=lambda: generate_fallback_message(diffs, style=cfg.commit_style),
272274
empty_diff_message="No changes staged for commit.",
275+
command=command,
276+
hook_mode=hook_mode,
273277
provider=provider,
274278
counter=counter,
275279
console=console,

‎src/gitmate/hooks.py‎

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
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

Comments
 (0)