Files
headroom/tests/test_install_git_hooks_script.py
Kenneth WongandKenneth Wong cbcf8d8d9b fix(scripts): skip ci-precheck in the pre-push hook when a push only deletes refs (#4702)
## Description

The pre-push hook that `make install-git-hooks` writes runs the full
`make ci-precheck` (cargo fmt, clippy and the workspace tests, plus the
Python suite) even when a push only deletes branches. Its loop over the
refs on stdin skips deleted refs with `continue`, but the precheck runs
after the loop regardless, so `git push origin --delete <branch>` waits
several minutes for checks on code it doesn't send.

This PR tracks whether any ref in the push is an update, and exits 0
when none is.

No tracking issue.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `scripts/install-git-hooks.sh` (the generated pre-push hook): set
`has_update=1` for every non-delete ref and `exit 0` after the loop when
no ref was an update. A push that mixes a delete with an update still
runs the precheck.
- The delete check now matches an all-zero sha of any length (`^0+$`),
so SHA-256 repositories (64-zero null id) are also recognised. The old
check compared against exactly 40 zeros.
- Removed the hook comment about gating only "main tracking branches";
the hook has no such pattern.
- `tests/test_install_git_hooks_script.py`: three end-to-end tests that
install the hooks into a temp repo and push to a bare remote with `make`
stubbed to log its calls. A branch update runs `make ci-precheck`; a
delete-only push does not (and the remote branch is gone); a push that
mixes a delete and an update runs it once.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`) (not run: no `headroom/`
code changed; the pre-commit mypy hook passed on the changed test file)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest -q tests/test_install_git_hooks_script.py            # this branch
.......                                                         [100%]
7 passed in 3.97s

$ pytest -q tests/test_install_git_hooks_script.py            # same tests, origin/main's script
E   AssertionError: assert ['ci-precheck'] == []
FAILED tests/test_install_git_hooks_script.py::test_pre_push_skips_ci_precheck_for_a_delete_only_push
1 failed, 6 passed in 3.40s

$ ruff check tests/test_install_git_hooks_script.py
All checks passed!
$ ruff format --check tests/test_install_git_hooks_script.py
1 file already formatted
$ shellcheck -s bash scripts/install-git-hooks.sh
(no output)
$ npx commitlint --from origin/main --to HEAD
(exit 0)
```

pre-commit (ruff, ruff format, mypy, commitlint) passed on the commit.

## Real Behavior Proof

- Environment: macOS 27.2 arm64, git 2.x, bash 5; hooks installed by
each version of `scripts/install-git-hooks.sh` into a throwaway repo
with a bare remote; `make` stubbed to print instead of running the
precheck.
- Exact command / steps: install the hooks, push a `feature` branch with
`--no-verify`, then run `git push origin --delete feature` and `git push
origin HEAD:refs/heads/feature`, once with origin/main's script
(bb8d18a56) and once with this branch's.
- Observed result: origin/main runs `make ci-precheck` for the delete;
this branch skips it and still runs it for the branch push:

```text
== origin/main bb8d18a56
$ git push origin --delete feature
  [make ci-precheck] would run the full Rust + Python precheck
$ git push origin HEAD:refs/heads/feature
── pre-push: running 'make ci-precheck' before pushing HEAD → refs/heads/feature
  [make ci-precheck] would run the full Rust + Python precheck
== this branch
$ git push origin --delete feature
$ git push origin HEAD:refs/heads/feature
── pre-push: running 'make ci-precheck' before pushing HEAD → refs/heads/feature
  [make ci-precheck] would run the full Rust + Python precheck
```

- Not tested: a SHA-256 repository end to end (the regex change is
covered by reading only); Windows (the hook test module skips without
bash and git, as before); the full `make ci-precheck` itself (pushed
with `--no-verify`, since this PR changes only the hook script and its
test, and the precheck's `pip install -e .` would overwrite the local
venv used for the tests above).

## Runtime Rollout Safety

- Rollout-managed feature(s): none; contributor git hook only.
- Minimum rollout channel: N/A (not shipped in the package).
- Stable/default behavior changed: only for delete-only pushes, which no
longer run `make ci-precheck`. Every push that sends commits behaves as
before.
- Kill switch / disable path: N/A; contributors re-run `make
install-git-hooks` to pick up the change.
- Unsafe override required: no.
- Qualification impact: none; CI does not use this hook.
- Rollback path: revert this commit and re-run `make install-git-hooks`.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Documentation: N/A. `CONTRIBUTING.md` says the pre-push hook runs
ci-precheck "on every push"; a push that only deletes branches sends no
code, so I left that wording alone. Happy to add a note if you prefer.

The three existing shellcheck SC2034 warnings in the hook body
(`remote`, `url`, `remote_sha` unused) are unchanged by this PR.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4702"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Co-authored-by: Kenneth Wong <17061293+KennethWKZ@users.noreply.github.com>
2026-11-09 12:24:49 -06:00

191 lines
6.1 KiB
Python

"""scripts/install-git-hooks.sh: install into the checkout that owns the script.
The script runs for real against temporary repositories, with fake
``pre-commit`` and ``npx`` on PATH, so ordinary checkouts, linked worktrees,
a source copy nested inside another repository, and a directory outside git
are exercised end to end without touching real hooks.
"""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "scripts" / "install-git-hooks.sh"
pytestmark = pytest.mark.skipif(
sys.platform == "win32" or not (shutil.which("bash") and shutil.which("git")),
reason="needs bash and git",
)
FAKE_PRE_COMMIT = """#!/usr/bin/env bash
hooks="$(git rev-parse --git-path hooks)"
case "$*" in
install) echo "#!/bin/sh" > "$hooks/pre-commit" ;;
"install --hook-type commit-msg") echo "#!/bin/sh" > "$hooks/commit-msg" ;;
esac
"""
def _git(cwd: Path, *args: str) -> str:
return subprocess.run(
["git", *args], cwd=cwd, check=True, capture_output=True, text=True
).stdout.strip()
def _checkout(path: Path) -> Path:
"""A repository containing scripts/install-git-hooks.sh and one commit."""
(path / "scripts").mkdir(parents=True)
shutil.copy(SCRIPT, path / "scripts" / "install-git-hooks.sh")
_git(path, "init", "-q")
_git(path, "add", ".")
_git(path, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init")
return path
def _env(tmp_path: Path) -> dict[str, str]:
bin_dir = tmp_path / "fake-bin"
bin_dir.mkdir(exist_ok=True)
for name, body in (("pre-commit", FAKE_PRE_COMMIT), ("npx", "#!/bin/sh\n")):
tool = bin_dir / name
tool.write_text(body)
tool.chmod(0o755)
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env.pop("VIRTUAL_ENV", None)
env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}"
env["GIT_CEILING_DIRECTORIES"] = str(tmp_path)
return env
def _run(script_root: Path, env: dict[str, str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["bash", str(script_root / "scripts" / "install-git-hooks.sh")],
cwd=script_root,
env=env,
capture_output=True,
text=True,
)
def _hooks(common_dir: Path) -> set[str]:
return {
p.name
for p in (common_dir / "hooks").iterdir()
if p.name in {"pre-push", "pre-commit", "commit-msg"}
}
def test_installs_hooks_in_an_ordinary_checkout(tmp_path: Path) -> None:
repo = _checkout(tmp_path / "repo")
result = _run(repo, _env(tmp_path))
assert result.returncode == 0, result.stderr
assert _hooks(repo / ".git") == {"pre-push", "pre-commit", "commit-msg"}
def test_installs_shared_hooks_from_a_linked_worktree(tmp_path: Path) -> None:
repo = _checkout(tmp_path / "repo")
worktree = tmp_path / "worktree"
_git(repo, "worktree", "add", "-q", str(worktree))
assert (worktree / ".git").is_file()
result = _run(worktree, _env(tmp_path))
assert result.returncode == 0, result.stderr
assert _hooks(repo / ".git") == {"pre-push", "pre-commit", "commit-msg"}
def test_refuses_a_source_copy_nested_in_another_repository(tmp_path: Path) -> None:
parent = tmp_path / "parent"
parent.mkdir()
_git(parent, "init", "-q")
nested = parent / "vendor" / "headroom"
(nested / "scripts").mkdir(parents=True)
shutil.copy(SCRIPT, nested / "scripts" / "install-git-hooks.sh")
result = _run(nested, _env(tmp_path))
assert result.returncode == 1
assert "not the root of a git checkout" in result.stderr
assert _hooks(parent / ".git") == set()
def _push_setup(tmp_path: Path) -> tuple[Path, dict[str, str], Path]:
"""A checkout with the hooks installed, a bare remote, and a fake ``make``
that logs each call instead of running ci-precheck."""
repo = _checkout(tmp_path / "repo")
env = _env(tmp_path)
assert _run(repo, env).returncode == 0
make_log = tmp_path / "make.log"
fake_make = tmp_path / "fake-bin" / "make"
fake_make.write_text(f'#!/bin/sh\necho "$*" >> "{make_log}"\n')
fake_make.chmod(0o755)
remote = tmp_path / "remote.git"
_git(tmp_path, "init", "-q", "--bare", str(remote))
_git(repo, "remote", "add", "origin", str(remote))
return repo, env, make_log
def _push(repo: Path, env: dict[str, str], *args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", "push", "-q", "origin", *args],
cwd=repo,
env=env,
capture_output=True,
text=True,
)
def _make_calls(make_log: Path) -> list[str]:
return make_log.read_text().splitlines() if make_log.exists() else []
def test_pre_push_runs_ci_precheck_for_a_branch_update(tmp_path: Path) -> None:
repo, env, make_log = _push_setup(tmp_path)
result = _push(repo, env, "HEAD:refs/heads/feature")
assert result.returncode == 0, result.stderr
assert _make_calls(make_log) == ["ci-precheck"]
def test_pre_push_skips_ci_precheck_for_a_delete_only_push(tmp_path: Path) -> None:
repo, env, make_log = _push_setup(tmp_path)
_git(repo, "push", "-q", "--no-verify", "origin", "HEAD:refs/heads/feature")
result = _push(repo, env, "--delete", "feature")
assert result.returncode == 0, result.stderr
assert _make_calls(make_log) == []
assert _git(repo, "ls-remote", "--heads", "origin", "feature") == ""
def test_pre_push_runs_ci_precheck_when_a_push_mixes_a_delete_and_an_update(
tmp_path: Path,
) -> None:
repo, env, make_log = _push_setup(tmp_path)
_git(repo, "push", "-q", "--no-verify", "origin", "HEAD:refs/heads/old")
result = _push(repo, env, ":old", "HEAD:refs/heads/new")
assert result.returncode == 0, result.stderr
assert _make_calls(make_log) == ["ci-precheck"]
def test_refuses_a_directory_outside_git(tmp_path: Path) -> None:
loose = tmp_path / "loose"
(loose / "scripts").mkdir(parents=True)
shutil.copy(SCRIPT, loose / "scripts" / "install-git-hooks.sh")
result = _run(loose, _env(tmp_path))
assert result.returncode == 1
assert "not the root of a git checkout" in result.stderr