Write a Trusted Pre-Commit Check
Define the contract
Our fictional garden project requires notes.txt to contain exactly one line: Water every 3 days, with a final newline. This is a deliberately narrow practice rule, not a general gardening validator. A commit should validate the snapshot in the index, not a newer unstaged edit. Use an isolated fixture, not a real project.
Create a minimal hook
The script below reads the stage-0 indexed blob, hashes the required bytes without writing an object, compares object IDs and reports failure if the file is missing or different. It uses Git itself to avoid command substitution losing trailing newlines in file content. The fixed path and text belong only to this fixture. Exit 0 permits the commit to proceed; exit 1 blocks it. Save this reviewed script as pre-commit in the lab hook directory and make it executable.
#!/bin/shactual=$(git rev-parse --verify :notes.txt) || exit 1expected=$(printf 'Water every 3 days\n' | git hash-object --stdin) || exit 1if [ "$actual" != "$expected" ]; then printf '%s\n' 'Stage the complete watering note.' >&2 exit 1fiexit 0Test failure before success
Stage Water every 3 without the unit, then make the working file correct without staging it. The hook must still reject the commit. Verify HEAD and the staged blob, stage the correction, and retry. Conversely, a valid staged blob can pass even when the working file contains an invalid unstaged edit. Avoid automatic staging inside hooks: it can silently alter the intended snapshot.
git status --shortgit show :notes.txtgit diff --cached -- notes.txtgit diff -- notes.txtCheck the evidence
Run the chapter laboratory from the extracted package. It verifies failed commits leave HEAD unchanged, validates exact staged bytes including the newline, and checks that the valid commit contains the intended note. Git must be installed; the lab uses POSIX shell and local repositories.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Write a Trusted Pre-Commit Check — knowledge check
Reason about Git hooks and automation safety.
Which version should a staged-content check inspect?
Invalid staged note and valid unstaged note: what should the fixture do?
Why compare hashes in this fixture?
What should the check do if the indexed file is missing?
What should learners verify after rejection?