patterngitTip
Git hooks: pre-commit and pre-push for local quality gates
Viewed 0 times
git hookspre-commit hookpre-push hookhuskylocal quality gatelint on commit
Error Messages
Problem
Developers commit broken code or push without running tests because there are no local guards. CI catches it, but only after the push.
Solution
Use Git hooks to enforce quality locally:
# Create a pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
npm run lint --silent || exit 1
EOF
chmod +x .git/hooks/pre-commit
# Create a pre-push hook to run tests
cat > .git/hooks/pre-push << 'EOF'
#!/bin/sh
npm test || exit 1
EOF
chmod +x .git/hooks/pre-push
For team-wide hooks, use a tool like husky (Node) or pre-commit (Python) that commits hook config to the repo.
# Create a pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
npm run lint --silent || exit 1
EOF
chmod +x .git/hooks/pre-commit
# Create a pre-push hook to run tests
cat > .git/hooks/pre-push << 'EOF'
#!/bin/sh
npm test || exit 1
EOF
chmod +x .git/hooks/pre-push
For team-wide hooks, use a tool like husky (Node) or pre-commit (Python) that commits hook config to the repo.
Why
Git hooks are shell scripts in .git/hooks/ that run at specific points in the git workflow. Exiting with non-zero code aborts the operation. They run locally before the operation completes.
Gotchas
- .git/hooks/ is not committed to the repo — each developer must set them up, or use husky/pre-commit to manage this
- Hooks can be bypassed with
git commit --no-verify— this is a developer override, not a security mechanism - pre-push hooks receive remote and URL via stdin in a specific format — test carefully
Code Snippets
Setting up pre-commit and pre-push hooks
# Create and enable a pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
npx eslint --ext .js,.ts src/ || exit 1
EOF
chmod +x .git/hooks/pre-commit
# Using husky for team-wide hooks (Node projects)
npx husky init
echo 'npm test' > .husky/pre-pushContext
Setting up local developer experience to catch issues before they reach CI
Revisions (0)
No revisions yet.