Sub topic 9
Hook managers: pre-commit, Husky and lefthook
This chapter assumes you can write a plain hook script and know what core.hooksPath does. It also assumes you know that a hook blocks a commit by exiting non-zero. If any of that is unfamiliar, review the earlier chapters on hook execution and sharing hooks first.
Why plain scripts stop scaling
A shell script in .githooks/ works well for one or two checks. As a project grows, you start to write the same supporting code again and again:
- Selecting only the staged files that match a pattern, such as
*.py. - Handling file names with spaces. The
for f in $(git diff ...)loop from the earlier chapter splits on whitespace and breaks on them. - Installing the tools each check needs, and pinning their versions so every developer runs the same ones.
- Running independent checks in parallel.
- Re-staging files that a formatter changed.
- Making installation work on Windows, macOS and Linux.
A hook manager is a tool that does this work for you. You describe the checks in a configuration file. The manager installs a small stub hook into Git, and the stub calls the manager at commit time. The manager reads the configuration, picks the staged files, runs each check and returns a combined exit status to Git.
How a manager plugs into Git
Every manager uses the mechanism you already know. Git only sees an executable file named pre-commit. The difference is what that file does.
The managers differ in where the stub lives:
| Manager | Written in | Config file | Where the stub goes |
|---|---|---|---|
| pre-commit | Python | `.pre-commit-config.yaml` | Writes `.git/hooks/pre-commit` |
| Husky | Node.js | Shell files in `.husky/` | Sets `core.hooksPath` to `.husky/_` |
| lefthook | Go (single binary) | `lefthook.yml` | Writes files into the hooks directory |
Because the stub is generated, it is not shared through the repository by itself. Each developer must run an install step once per clone. The three managers handle that step differently, as shown below.
The pre-commit framework
The pre-commit framework (the tool is named pre-commit, not to be confused with the hook of the same name) is language-agnostic and built around a catalog of reusable hooks published in Git repositories. You install it once per machine and enable it once per clone:
pip install pre-commit
pre-commit installpre-commit install writes the stub into .git/hooks/pre-commit. The configuration lives in .pre-commit-config.yaml at the repository root:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- repo: local
hooks:
- id: shellcheck
name: shellcheck
entry: shellcheck
language: system
types: [shell]Several points about this file are worth understanding.
revpins a version. The framework clones each remote repository at that tag or commit and builds an isolated environment for it. Everyone on the team gets the same hook code. Runpre-commit autoupdateto move the pins forward.repo: localdefines a hook that runs a command you already have. Withlanguage: system, the framework runsentrydirectly from yourPATHand does not install it. That means each developer must haveshellcheckinstalled.types: [shell]filters files by detected type, using file extensions and shebang lines. Thefiles:option takes a regular expression on the path instead.- File names are passed as arguments. The framework appends the matching staged paths to
entry, splitting them safely across several invocations if the list is long.
Two commands are useful in daily work:
pre-commit run --all-files # run every hook against the whole repository
pre-commit run shellcheck # run one hook against the staged filesRunning with --all-files matters when you first add a hook. Otherwise old files are only checked when someone happens to touch them.
What happens to unstaged changes
The framework checks staged content rather than the working tree. To do this it stashes your unstaged changes before running the hooks and restores them afterward. If a hook modifies a file, for example end-of-file-fixer adding a newline, the hook is reported as failed and the commit is aborted. The fix is in your working tree but not in the index. You review it, run git add on the file and commit again.
Commit-msg and other stages
By default only the pre-commit stub is installed. To also run hooks at other stages, install the matching stub:
pre-commit install --hook-type commit-msg
pre-commit install --hook-type pre-pushA hook then declares its stage with stages: [commit-msg] or stages: [pre-push] in the configuration. Recent versions of the framework renamed some stage values, so check the documentation for the version you pin.
Husky
Husky is the usual choice in JavaScript projects. It integrates with package.json so installation happens automatically when a developer runs npm install.
npm install --save-dev husky
npx husky initnpx husky init adds a prepare script to package.json and creates a sample .husky/pre-commit file. The prepare script runs after every npm install, and it configures core.hooksPath for the clone. This is why Husky needs no separate install step.
In Husky 9, the files in .husky/ are plain shell scripts, and you do not need a shebang line. The hook is whatever commands you put in the file. Husky itself does not select staged files. It is commonly paired with lint-staged, which does:
# .husky/pre-commit
npx lint-staged{
"scripts": {
"prepare": "husky"
},
"lint-staged": {
"*.js": "eslint --fix",
"*.{js,css,md}": "prettier --write"
},
"devDependencies": {
"husky": "^9.0.0",
"lint-staged": "^15.0.0"
}
}lint-staged passes the staged paths matching each glob to the command. It also re-adds the files after a formatter changes them, so you do not have to run git add yourself. Husky's file layout changed between major versions (older versions sourced a helper script at the top of each hook), so follow the documentation for the version you install.
lefthook
lefthook is a single binary with no runtime dependency, so it suits polyglot repositories and teams that do not want Python or Node.js just to run hooks. Install it with your package manager (Homebrew, npm, Go, and others), then enable it in the clone:
lefthook installThe configuration is lefthook.yml:
# lefthook.yml
pre-commit:
parallel: true
commands:
shellcheck:
glob: "*.sh"
run: shellcheck {staged_files}
prettier:
glob: "*.{js,css,md}"
run: prettier --write {staged_files}
stage_fixed: true
commit-msg:
commands:
format:
run: head -n 1 {1} | grep -qE '^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+'The details that matter here:
{staged_files}expands to the staged paths that matchglob.{1}is the first argument Git gave the hook, which forcommit-msgis the message file.parallel: trueruns the commands at the same time. Only use it when the commands touch different files, otherwise two formatters can fight over one file.stage_fixed: truere-stages the files a command modified.- Each command's name appears in the output, which makes it clear which check failed.
Choosing a manager
| Question | Likely answer |
|---|---|
| Is the project already a Node.js project? | Husky with `lint-staged`. Installation is automatic with `npm install`. |
| Do you want ready-made checks without writing scripts? | pre-commit, which has a large catalog of hooks. |
| Is the repository polyglot or free of a language runtime? | lefthook. It is one binary with parallel execution. |
| Do you need hooks to run on Windows without extra setup? | Test all three. Husky and lefthook run hook commands through a shell, so Git for Windows must be present. |
No choice is permanent. All three read your config and call the same tools, so migrating later means rewriting a short config file.
Trade-offs and failure modes
- Install step per clone. None of the managers can force a developer to run the install step. A new contributor who skips it commits with no checks. Husky narrows this gap by running during
npm install. CI must catch the rest. - Another dependency to maintain. A manager adds a tool, its cache and its config format. For a repository with a single check, the
core.hooksPathapproach from the earlier chapter is simpler. - Slow first run. The pre-commit framework builds environments for each remote hook on first use, so the first commit can take a while. Later runs use the cache.
- Mutating hooks. Formatters that rewrite files can surprise people. Decide on a policy: either let the manager re-stage fixes (
lint-staged,stage_fixed) or fail and ask the developer to review the change (the pre-commit framework default). - Existing
core.hooksPath. The pre-commit framework refuses to install whencore.hooksPathis set, because it would not be used. Husky sets that variable itself. Using both in one repository will conflict, so pick one.
Exercise
Exercise
A teammate clones your repository, which uses the pre-commit framework, and makes a commit containing trailing whitespace. The commit succeeds with no checks. Give two likely causes and one fix that does not depend on the teammate remembering anything.
Show answer
Likely causes: the teammate never ran pre-commit install, so no stub exists in .git/hooks/pre-commit. Or they committed with --no-verify. The install step is per clone and is not versioned, so Git has no hook to call. The fix that does not depend on the teammate is to run the same checks in CI, for example pre-commit run --all-files on every push or pull request, and to make that job a required check before merging.
Exercise
You use lefthook with parallel: true and two commands that both run prettier --write on overlapping globs. Why is this risky, and how would you change the config?
Show answer
Both commands can rewrite the same file at the same moment, which can produce corrupted or inconsistent output and an unclear failure. Either merge them into a single command, or remove parallel: true so they run in sequence, or narrow the globs so each file matches only one command.