Skip to content

Commit 3cbbf5c

Browse files
fix(hooks): resolve CI mypy error, wrap hook in posix shell, and preserve git status comments
1 parent bc0745f commit 3cbbf5c

3 files changed

Lines changed: 88 additions & 11 deletions

File tree

‎src/gitmate/cli.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,25 @@ def _stub(name: str, milestone: str) -> None:
3333
@app.command()
3434
def commit(
3535
yes: bool = typer.Option(False, "--yes", "-y", help="Commit without interactive confirmation."),
36+
hook_mode: bool = typer.Option(
37+
False,
38+
"--hook-mode",
39+
help="Non-interactive hook mode (writes directly to commit message file).",
40+
),
41+
commit_msg_file: Path | None = typer.Argument( # noqa: B008
42+
None, help="Path to the commit message file in hook mode."
43+
),
3644
) -> None:
3745
"""Generate a commit message for the staged diff and review before committing."""
46+
if hook_mode:
47+
if commit_msg_file is None:
48+
err_console.print("[red]error:[/red] --hook-mode requires a commit message file path.")
49+
raise typer.Exit(1)
50+
from gitmate.hooks import _run_worker
51+
52+
_run_worker([str(commit_msg_file)])
53+
return
54+
3855
from gitmate.committer import commit_flow
3956

4057
code = commit_flow(yes=yes, console=console, secret_store=secret_store)

‎src/gitmate/hooks.py‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,19 @@
1212
HOOK_TIMEOUT_SECONDS = 4
1313
HOOK_MARKER = "# Installed by gitmate; managed by `gitmate install-hook`."
1414

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-
15+
HOOK_SCRIPT = f"""#!/bin/sh
16+
{HOOK_MARKER}
17+
# Crash-safe launcher for gitmate's prepare-commit-msg worker.
18+
PYTHON="{sys.executable}"
19+
if [ ! -x "$PYTHON" ]; then
20+
if command -v python3 >/dev/null 2>&1; then
21+
PYTHON="python3"
22+
else
23+
exit 0
24+
fi
25+
fi
26+
exec "$PYTHON" -c '
27+
import subprocess, sys
2128
try:
2229
subprocess.run(
2330
[sys.executable, "-m", "gitmate.hooks", "--worker", *sys.argv[1:]],
@@ -28,8 +35,9 @@
2835
)
2936
except BaseException:
3037
pass
31-
raise SystemExit(0)
32-
'''
38+
sys.exit(0)
39+
' "$@"
40+
"""
3341

3442

3543
class HookError(Exception):
@@ -135,7 +143,13 @@ def _run_worker(args: list[str]) -> None:
135143
console=None,
136144
command="commit-hook",
137145
)
138-
_replace_message(message_file, result.text.rstrip() + "\n")
146+
existing = message_file.read_text(encoding="utf-8", errors="replace")
147+
generated = result.text.rstrip()
148+
if existing.strip():
149+
new_message = f"{generated}\n\n{existing.lstrip()}"
150+
else:
151+
new_message = f"{generated}\n"
152+
_replace_message(message_file, new_message)
139153

140154

141155
def _replace_message(message_file: Path, message: str) -> None:

‎tests/test_hooks.py‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ def test_install_is_executable_idempotent_and_uninstallable(tmp_path: Path) -> N
7373
path = install_hook(repo)
7474
original = path.read_text(encoding="utf-8")
7575
assert path.stat().st_mode & 0o111
76-
assert original.startswith(f"#!{sys.executable}\n")
76+
assert original.startswith("#!/bin/sh\n")
77+
assert sys.executable in original
7778
assert HOOK_MARKER in original
7879

7980
assert install_hook(repo) == path
@@ -133,7 +134,7 @@ def fake_run(command: list[str], **kwargs: object) -> None:
133134
monkeypatch.setattr(sys, "argv", ["gitmate-hook", str(message_file)])
134135
monkeypatch.setenv("PRE_COMMIT_COMMIT_MSG_SOURCE", "message")
135136
monkeypatch.setenv("PRE_COMMIT_COMMIT_OBJECT_NAME", "deadbeef")
136-
monkeypatch.setattr(hooks_mod.subprocess, "run", fake_run)
137+
monkeypatch.setattr("gitmate.hooks.subprocess.run", fake_run)
137138

138139
assert hooks_mod.main() == 0
139140
assert commands[0][-3:] == [str(message_file), "message", "deadbeef"]
@@ -238,3 +239,48 @@ def test_worker_failure_and_timeout_do_not_block_real_commit(
238239
assert result.returncode == 0, result.stderr
239240
assert _git(repo, "log", "-1", "--format=%s").stdout.strip() == "Use the repository template"
240241
assert elapsed < 8
242+
243+
244+
def test_commit_preserves_template_and_prepends_message(
245+
tmp_path: Path, hook_env: dict[str, str]
246+
) -> None:
247+
repo = tmp_path / "repo"
248+
_init_repo(repo)
249+
install_hook(repo)
250+
template = tmp_path / "commit-template.txt"
251+
template.write_text("Ticket: JIRA-123\nReviewed-by: Lead\n", encoding="utf-8")
252+
_git(repo, "config", "commit.template", str(template))
253+
254+
(repo / "auth.py").write_text("def auth(): pass\n", encoding="utf-8")
255+
_git(repo, "add", "auth.py")
256+
257+
result = _commit(repo, env=hook_env)
258+
assert result.returncode == 0, result.stderr
259+
full_message = _git(repo, "log", "-1", "--format=%B").stdout
260+
assert full_message.startswith("feat: add auth.py")
261+
assert "Ticket: JIRA-123" in full_message
262+
assert "Reviewed-by: Lead" in full_message
263+
264+
265+
def test_cli_commit_hook_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
266+
repo = tmp_path / "repo"
267+
_init_repo(repo)
268+
monkeypatch.chdir(repo)
269+
270+
(repo / "new_module.py").write_text("val = 100\n", encoding="utf-8")
271+
_git(repo, "add", "new_module.py")
272+
273+
msg_file = tmp_path / "COMMIT_EDITMSG"
274+
msg_file.write_text("# Please enter the commit message\n# On branch main\n", encoding="utf-8")
275+
276+
runner = CliRunner()
277+
res = runner.invoke(app, ["commit", "--hook-mode", str(msg_file)])
278+
assert res.exit_code == 0, res.output
279+
content = msg_file.read_text(encoding="utf-8")
280+
assert content.startswith("feat: add new_module.py")
281+
assert "# Please enter the commit message" in content
282+
283+
# Missing file argument returns error
284+
res_err = runner.invoke(app, ["commit", "--hook-mode"])
285+
assert res_err.exit_code == 1
286+
assert "error" in res_err.output.lower()

0 commit comments

Comments
 (0)