Git and GitHub · Part 4 · Team workflows

Git hooks

Catching mistakes before they're committed

A stray console.log, unformatted code, a commit message like “stuff”: reviewers can catch these, but it's a waste of their time. A Git hook is a script Git runs automatically at a certain moment, such as just before a commit. If the script fails, the commit doesn't happen.

The hooks that matter

HookRunsTypical use
pre-commitBefore a commit is madeFormat and lint the staged files
commit-msgAfter the message is writtenCheck the message format
pre-pushBefore a pushRun the tests

Hooks live in .git/hooks/. Every new repository already has examples there, ending in .sample, which don't run.

A hook by hand

1.Write the script

In any practice repository, create .git/hooks/pre-commit (no extension):

.git/hooks/pre-commit
#!/bin/sh
if git diff --cached | grep -q "console.log"; then
  echo "Remove console.log before committing."
  exit 1
fi

git diff --cached is what's about to be committed. exit 1 means failure, which stops the commit; reaching the end means success.

2.Make it runnable and try it

Terminal
chmod +x .git/hooks/pre-commit
echo 'console.log("hi")' > app.js
git add app.js
git commit -m "Add app"
Output
Remove console.log before committing.

No commit was made. To skip hooks once, on purpose: git commit --no-verify.

Shared hooks with Husky

In JavaScript projects, the usual setup is three tools:

ToolJob
HuskyKeeps hooks in a committed .husky/ folder, installed for everyone on npm install
lint-stagedRuns tools only on the staged files, so it stays fast
commitlintChecks commit messages against Conventional Commits (Lesson 26)

1.Install Husky

Terminal
npm install --save-dev husky
npx husky init

husky init creates .husky/pre-commit and adds a prepare script to package.json. npm install runs prepare automatically, so every teammate who installs the project gets the hooks.

package.json
"scripts": {
  "prepare": "husky"
}

2.Format staged files with lint-staged

Terminal
npm install --save-dev lint-staged prettier

Tell lint-staged which command runs on which files, in package.json:

package.json
"lint-staged": {
  "*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
  "*.{css,md,json}": "prettier --write"
}

Then replace the contents of the pre-commit hook. Husky hooks are plain commands, with no #!/bin/sh line needed:

.husky/pre-commit
npx lint-staged

On every commit, Prettier formats the staged files and the fixed versions are what get committed. If ESLint finds an error it can't fix, the commit stops.

3.Check messages with commitlint

Terminal
npm install --save-dev @commitlint/cli @commitlint/config-conventional
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.mjs
echo 'npx --no -- commitlint --edit $1' > .husky/commit-msg

Now a vague message is refused:

Terminal
git commit -m "added stuff"
Output
⧗   --- input ---
added stuff
✖   subject may not be empty [subject-empty]
✖   type may not be empty [type-empty]

✖   found 2 problems, 0 warnings
ⓘ   Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint

husky - commit-msg script failed (code 1)

git commit -m "feat: add search" passes. The rules also reject a capitalised description (feat: Add search), a full stop at the end, and any type not in the list.

4.Commit the setup

Terminal
git add .husky package.json package-lock.json commitlint.config.mjs
git commit -m "chore: add husky, lint-staged and commitlint"

Everyone who pulls and runs npm install now has the same checks.

Hooks aren't a guarantee

Anyone can skip hooks with --no-verify, or never run npm install. Hooks are a fast first check on the laptop. The guarantee comes from running the same checks again on GitHub, as required status checks on a protected main (Lesson 23). Keep hooks quick, too: a pre-commit hook that takes a minute gets skipped. Slow test suites belong in pre-push or on the server.

Quick reference

TaskCommand or file
Set up Huskynpx husky init
Run lint-staged before commits.husky/pre-commit: npx lint-staged
Check commit messages.husky/commit-msg: npx --no -- commitlint --edit $1
Run tests before pushing.husky/pre-push: npm test
Skip hooks oncegit commit --no-verify