Git·19 questions

How to set up git hooks for automation?

Answer

Git hooks are scripts that run automatically on certain Git events. They help automate code checks, formatting, and tests.

Where hooks are stored: every repository has a .git/hooks folder with sample hooks having a .sample extension. To activate a hook, remove the .sample extension and make the file executable: chmod +x .git/hooks/pre-commit. Hooks are not versioned — they're local to each developer. For shared hooks, use Husky or similar tools.

Client-side hooks: pre-commit runs before a commit. If it returns a non-zero code — the commit is canceled. Use for linting, formatting, secret checking. prepare-commit-msg — before the message editor opens, can generate a template. pre-push — before push, can run tests.

Server-side hooks: pre-receive, update, post-receive — on the server (GitHub, GitLab). Used for permission checks, rejecting pushes that violate rules. On GitHub, configured via GitHub Actions or Branch Protection Rules.

Husky — a popular tool for shared client-side hooks. Installation: npm install --save-dev husky, npx husky init. This creates a .husky/ folder with hooks that are versioned in the repository. All developers get the same hooks automatically. Example .husky/pre-commit: npx lint-staged — runs the linter only for staged files.

lint-staged — a companion for Husky. Configuration in package.json: "lint-staged": {"*.js": "eslint --fix", "*.ts": "tsc --noEmit", "*.css": "prettier --write"}. Runs tools only for files in the index, not the entire project — fast.

pre-commit framework — an alternative to Husky, multilingual. Installation: pip install pre-commit, pre-commit install. Configuration in .pre-commit-config.yaml. Supports hooks in Python, Node, Go, Rust. Has built-in hooks: trailing-whitespace, end-of-file-fixer, check-yaml.

Practical pre-commit hook: check for absence of console.log, check formatting, check for secrets (git-secrets, trufflehog), run unit tests for touched files. If the hook fails — the commit is canceled, the developer sees errors and fixes them.

Tip: don't make hooks too slow. pre-commit should run in seconds, otherwise developers will bypass it (--no-verify). Heavy checks (integration tests, full analysis) — in CI/CD, not in hooks.

Was this answer helpful?

More questions in this topic

Related questions from other topics