Git Hooks

Git hook locations, setup patterns, and reusable client-side hook snippets for linting, testing, policy, and automation.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Client-Side Hooks
Pre-commit hook path
.git/hooks/pre-commit

# Default path for pre-commit hook script.

Commit-msg hook path
.git/hooks/commit-msg

# Default path for commit-msg hook script.

Pre-push hook path
.git/hooks/pre-push

# Default path for pre-push hook script.

Make hook executable
chmod +x .git/hooks/pre-commit

# Hooks must be executable to run.

Use centralized hooks path
git config core.hooksPath .githooks

# Store hooks in a versioned directory.

## Hook Snippets
Pre-commit lint script
#!/usr/bin/env sh
npm run lint

# Run linting before commit and fail on error.

Pre-commit test script
#!/usr/bin/env sh
npm test

# Run tests before commit.

Commit-msg conventional commits validator
#!/usr/bin/env sh
grep -Eq "^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+" "$1"

# Reject non-conforming commit messages.

Block direct pushes to main
#!/usr/bin/env sh
branch="$(git symbolic-ref --short HEAD)"
[ "$branch" = "main" ] && echo "Direct pushes to main are blocked." && exit 1
exit 0

# Prevent accidental pushes to main.

Post-checkout regenerate assets
#!/usr/bin/env sh
npm install

# Run setup after checkout when needed.

## Hook Lifecycle Commands
Show hooksPath
git config --show-origin --get core.hooksPath

# See whether Git uses a non-default hook directory.

Skip client hooks for one commit
git commit --no-verify -m "Emergency commit"

# Bypass pre-commit and commit-msg hooks when necessary.

Skip pre-push hook
git push --no-verify

# Bypass pre-push hook for one push.

Debug shell hook with xtrace
set -x
# add near top of hook script

# Trace shell execution for debugging.