Sub topic 2
Writing Your First Pre-commit Hook
Assume you know git add, git commit, and the difference between the staging area and the working tree. A Git hook is an executable script that Git runs at a defined point in a local workflow. A pre-commit hook runs after you create the commit message but before Git creates the commit.
Write a pre-commit hook
Create .git/hooks/pre-commit:
#!/bin/sh
# Reject whitespace errors and unresolved conflict markers.
if ! git diff --cached --check; then
echo "pre-commit: fix the staged changes first." >&2
exit 1
fi
exit 0Make the file executable:
chmod +x .git/hooks/pre-commitThe hook checks the index, which is Git’s name for the staging area. An exit status of 0 allows the commit. Any non-zero status stops it. The --check option reports whitespace errors and conflict markers in staged changes.
Check what is actually being committed
A modified file can differ between your working tree and the staged version. A pre-commit hook should normally check the staged version, because that is what the commit will contain.
For example, git diff --cached --check reads staged changes. A command such as shellcheck script.sh reads the working-tree file instead, which may contain unstaged edits. To inspect staged shell files, stream each staged blob with git show ":path" and check that stream.
Share hooks with the team
The .git/hooks directory is local and normally untracked. Store shared hooks in a tracked directory, then configure Git to use it:
mkdir -p .githooks
cp .git/hooks/pre-commit .githooks/pre-commit
chmod +x .githooks/pre-commit
git config core.hooksPath .githooks
git add .githooksEach contributor must run the configuration command. Hook managers such as pre-commit, Husky, and lefthook can automate installation and provide staged-file handling.
Bypass hooks and use CI
A contributor can skip client-side hooks with:
git commit --no-verify -m "Emergency fix"This can be useful when recovering from a broken local environment, but it also means hooks cannot enforce project rules by themselves. Run required tests and policy checks in continuous integration (CI), where every proposed change is checked on a controlled server.
Exercise
Why should a pre-commit hook inspect the index instead of only running a linter on the working-tree file?
Show answer
The index contains the exact content that the commit will contain, while the working tree may include unstaged changes.