Sub topic 3
Validating Commit Messages and Choosing Hook Stages
Assume you know git add, git commit, and git push, and understand the staging area. A Git hook is an executable script that Git runs at a defined point in a local workflow.
Validating messages with `commit-msg`
The commit-msg hook runs after Git creates a temporary file containing the proposed commit message. Git passes that file path as the hook's first argument, $1. A zero exit status accepts the message. Any non-zero status stops the commit.
Create .git/hooks/commit-msg:
#!/bin/sh
if ! head -n 1 "$1" | grep -Eq '^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+'; then
echo "Use type(scope): summary" >&2
exit 1
fiMake it executable with chmod +x .git/hooks/commit-msg. This checks a message such as fix(parser): reject empty input.
Hook managers
The .git/hooks directory is local and normally untracked. Hook managers install and maintain hooks from project configuration.
| Tool | Typical configuration | Strength |
|---|---|---|
| pre-commit | `.pre-commit-config.yaml` | Language-independent file checks |
| Husky | Project scripts, common in Node.js | Simple JavaScript project setup |
| lefthook | `lefthook.yml` | Parallel and grouped commands |
Choose a plain script for a small, stable check. Choose a manager when the team needs repeatable installation, multiple tools, or staged-file filtering.
Speed and stage selection
Keep pre-commit checks fast. Run format checks, basic linting, and tests for changed files there. Use pre-push for slower unit or integration tests. Keep authoritative checks in CI because local hooks can be skipped or misconfigured.
A user can bypass local hooks with git commit --no-verify or git push --no-verify. Treat this as an escape hatch, not enforcement.
Debugging and cross-platform pitfalls
Check that the hook has the executable bit and the exact expected filename. Run it directly with a sample message file. Use portable POSIX shell syntax, quote paths, and avoid assumptions about Bash, GNU-only commands, or Windows shell behavior. A manager may also require a setup command after cloning.
Exercise
Which stage should usually run a slow integration test, and why?
Show answer
Use pre-push for local feedback, then repeat the test in CI because either local hook can be skipped.