Da Anonimo (non verificato) , 29 Aprile 2026

Perche gli hook pre-commit

Il posto piu economico per intercettare un errore di lint e sulla macchina dello sviluppatore, prima ancora che il commit si formi.

L'hook piu semplice

# .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

Lint solo dei file modificati

#!/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 per progetti 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"]
}

Il framework pre-commit

# .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

Condividere hook tramite core.hooksPath

git config core.hooksPath .githooks

Bypassare quando necessario

git commit --no-verify -m "WIP"

Check pre-commit comuni

  • Lint e format.
  • Type check.
  • Whitespace finale.
  • Marker di conflitto.
  • Rilevamento segreti.
  • Limiti dimensione file.

Tenere gli hook veloci

Un hook che impiega 30 secondi sara bypassato entro una settimana. Mirare a sotto i 5 secondi.