Git Hook vs Branch Protection
People think a pre-commit hook keeps bad code off main, and it does not. A Git hook runs on one person's computer. A clone does not copy it, and git commit --no-verify skips it. Branch protection runs on the Git host. It locks main until reviews and tests pass, and nobody can skip it unless they are allowed to.
Git Hook
A script Git runs on its own, like a check just before each commit.
A Git hook is a script Git runs by itself at a set moment. The pre-commit hook runs just before a commit is made. If it ends with an error, Git stops and the commit is not made. Other hooks run when a message is written or before a push. Hooks live in the .git/hooks folder, so each person's copy has its own.
Branch Protection
Rules that keep changes off a branch until reviews and tests pass.
Branch protection is a set of rules a code host puts on a branch, usually main. It can require a pull request before anything is merged. It can require an approving review and passing tests. On GitHub, it blocks force pushes and deleting the branch by default. Nobody can then push broken code to main by mistake.
In one line
- Git Hook
- A script Git runs on its own, like a check just before each commit.
- Branch Protection
- Rules that keep changes off a branch until reviews and tests pass.