Straight from the horse’s mouth:
Hooks are programs you can place in a hooks directory to trigger actions at certain points in git’s execution.
Inside your git repository:
Open .git/hooks/pre-commit
.
Add the following sample script:
#!/usr/bin/env bash
echo -e "\n\nPre-commit hook has been triggered\n\n"
$ chmod u+x .git/hooks/pre-commit
git commit
command in that repo.Sure, I have a pre-commit git hook written that… Well, let me just show you:
#!/bin/sh
set -euo pipefail
STAGED=$(git diff --cached --name-only | xargs)
# Lint
yarn eslint --fix $STAGED
# Format
yarn prettier --write $STAGED
# Type check
yarn tsc --noEmit
# Test
yarn jest
# Re-stage
git add $STAGED
This little script does linting, formatting, type checking, and unit testing before the staged files are ready to commit. As a side note, see line 5 to get only staged files. The pipefail
command runs the script in “strict mode”; see Shell Notes for more details.
core.hooksPath
?As above, by default, hooks are placed in .git/hooks
directory. We can have them hooks in another directory inside the repo (e.g. ./hooks) and as such ensure that everyone gets a copy of it when they clone a repo. Then you can have an initialization script (like ‘preinstall’ for package.json) that does the git config core.hooksPath hooks
and voila! hooks installed just like that.
NO. You can have any script that executes. Here’s another example of pre-commit in Nodejs:
#!/usr/bin/env node
console.log("\n\nPre-commit hook in Nodejs has been triggered\n\n")
And Python:
#!/usr/bin/env python
print("\n\nPre-commit hook in Python has been triggered\n\n")
Here ya go:
Thanks for reading and happy hacking!