bashintermediate
Git Hooks — Pre-Commit Lint and Format
Set up pre-commit hooks to automatically lint, format, and validate code before every commit.
bashPress ⌘/Ctrl + Shift + C to copy
#!/usr/bin/env bash
# .git/hooks/pre-commit (make executable: chmod +x)
set -euo pipefail
echo "🔍 Running pre-commit checks..."
# Get staged files only
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACMR)
# 1. Lint TypeScript/JavaScript files
TS_FILES=$(echo "$STAGED_FILES" | grep -E '\.(ts|tsx|js|jsx)$' || true)
if [[ -n "$TS_FILES" ]]; then
echo "Linting TypeScript/JavaScript..."
echo "$TS_FILES" | xargs npx eslint --fix
echo "$TS_FILES" | xargs git add # re-stage after fix
fi
# 2. Format with Prettier
FMT_FILES=$(echo "$STAGED_FILES" | grep -E '\.(ts|tsx|js|jsx|json|md|css)$' || true)
if [[ -n "$FMT_FILES" ]]; then
echo "Formatting with Prettier..."
echo "$FMT_FILES" | xargs npx prettier --write
echo "$FMT_FILES" | xargs git add
fi
# 3. Check for secrets / sensitive data
if echo "$STAGED_FILES" | xargs grep -lE '(AKIA|sk-|password\s*=)' 2>/dev/null; then
echo "❌ Potential secrets detected! Aborting commit."
exit 1
fi
# 4. Run type check
echo "Type-checking..."
npx tsc --noEmit
echo "✅ All pre-commit checks passed!"Sponsored
GitHub Copilot
Use Cases
- Enforcing code quality before commits
- Preventing secrets from entering the repo
- Automating formatting across the team
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
bashintermediate
Git Hooks Pre-Commit Example
Git pre-commit and commit-msg hooks to enforce linting, tests, and commit message conventions.
Best for: Enforcing code quality before commits
#git#hooks
bashintermediate
Git Hooks Pre Commit
Git workflow: git-hooks-pre-commit
Best for: version control
#git#version-control
bashadvanced
Git Hooks Post Commit
Git workflow: git-hooks-post-commit
Best for: version control
#git#version-control
bashadvanced
Git Lfs Large Files
Git workflow: git-lfs-large-files
Best for: version control
#git#version-control