Pourquoi des hooks pre-commit
L'endroit le moins cher pour attraper une erreur de lint est sur la machine du développeur, avant même que le commit ne se forme.
Le hook le plus simple
# .git/hooks/pre-commit
#!/usr/bin/env bash
set -e
npm run lint --silent
npm run format:check --silent
chmod +x .git/hooks/pre-commit
Linter seulement les fichiers changés
#!/usr/bin/env bash
set -e
files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\\.(js|ts|tsx)$' || true)
if [ -z "$files" ]; then
exit 0
fi
echo "$files" | xargs npx eslint --max-warnings=0
echo "$files" | xargs npx prettier --check
Husky pour les projets Node
npm install --save-dev husky lint-staged
npx husky init
# .husky/pre-commit
npx lint-staged
# package.json
"lint-staged": {
"*.{js,ts,tsx}": ["eslint --fix", "prettier --write"]
}
Le framework pre-commit (écosystème Python)
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-merge-conflict
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.5.0
hooks:
- id: ruff
- id: ruff-format
pip install pre-commit
pre-commit install
Partager les hooks via core.hooksPath
git config core.hooksPath .githooks
Contourner si nécessaire
git commit --no-verify -m "WIP"
Vérifications pre-commit courantes
- Lint et format.
- Type checks.
- Trailing whitespace.
- Marqueurs de conflit de merge.
- Détection de secrets.
- Limites de taille de fichier.