Sub topic 1
What Git Hooks Are and Where They Live
Prerequisites
Assume you know git add, git commit, and git push. You should also understand the staging area, also called the index, and the working tree.
What Git Hooks Are and Where They Live
A Git hook is an executable program that Git runs at a defined point in a local workflow. Hooks can check files, validate commit messages, or run tests before an action continues.
Client-side hooks run on your machine. They are different from server-side hooks, which run in a repository hosted on a server and can enforce rules for everyone who pushes.
By default, Git looks for client-side hooks in .git/hooks. Example names include:
pre-commit, before Git creates a commitcommit-msg, after Git creates the message but before it creates the commitpre-push, before Git sends commits to a remote
Files in .git/hooks are normally local and are not committed with the project. A tracked directory plus core.hooksPath can provide shared hooks, but each clone still needs that configuration.
Client-Side Hooks and When Git Runs Them
Git invokes a hook only for the operation associated with its name. A pre-commit hook can reject a commit before the commit object exists. A commit-msg hook can inspect the proposed message. A pre-push hook is a better place for slower tests because it runs later.
The hook does not automatically check every file in the working tree. A well-designed pre-commit hook checks the content that the commit will contain.
How a Hook Runs
The hook file must have the expected name and executable permission. It receives arguments defined by Git. For example, commit-msg receives the message file path as its first argument. Git uses the program's exit status: zero allows the operation, while any non-zero status stops it.
#!/bin/sh
# .git/hooks/pre-commit
if ! git diff --cached --check; then
echo "Fix staged whitespace errors or conflict markers." >&2
exit 1
fi
exit 0Install and test this hook with:
chmod +x .git/hooks/pre-commit
git add path/to/file
git commit -m "Check staged content"Exercise
What does a non-zero exit status from a pre-commit hook do?
Show answer
It makes Git stop the commit and report the hook's output.