This a an example of how you could use githooks and shell scripts to run pre-commit hooks in a monorepo containing TypeScript sub-projects running on Node.js.
When you want to run tests against your staged files before you can commit the files. This example:
- Only checks modified workspaces
- Skips unnecessary checks
- Checks the workspace types
- Lints staged files
- Formats staged files
If any of the tests fail it will immediately exit.
This offers similar functionality to these common packages:
and
But with zero dependencies
- When you don't want extra dependencies in your codebase
- When you don't need all of their features
- When you can't install extra dependencies in your project
- When you want to use pre-commit githooks but your team doesn't
- Git v1.5.0+
- Unix or unix-like environment (tested with zsh on Mac 13 Ventura, Ubuntu 22.04 & Fedora 38)
- Using npm (you can easily modify this for yarn or pnpm)
- Workspace names match the name and case of the first level directory they are in
Both can be easily edited
- Copy the pre-commit scripts
- Edit
pre-commit
lines for your sub-projects e.g. 32 + 36 - Rename each
pre-commit-*
file to match your workspace names - Edit each
pre-commit-*
file for your workspace name (line 3) and adjust tests for your needs - Make files executable e.g.
chmod +x pre-commit*
- Move files to
.git/hooks
in your project - Run
git config --local core.hooksPath .git/hooks/
to initialise the githooks
- Note: any time you edit
pre-commit
you must re-run this for changes to take effect
- Follow steps 1-5 above.
- Choose the directory you'd like to store these scripts e.g.
.githooks/
- Update the workspace script paths in
pre-commit
- Edit your package.json adding a prepare script:
"scripts": {
"prepare": "git config --local core.hooksPath .githooks/"
}
- Note: If using CI you will most likely not want to initialise these scripts. Take a look at the Husky guide for further advice.
- Run the prepare script e.g.
$ npm run prepare
or just run$ npm i
again
Either:
git commit --no-verify
orgit commit -n
Sometimes you don't want these checks to run by default
- Edit
pre-commit
and uncomment lines 8-10 - Default git commit behaviour will be unchanged and when you want to run the hooks
GIT_HOOKS=1 git commit
- If you so choose, you could alias (git alias or shell alias) this to a shorter command
That's it!
DISCLAIMER:
While every effort has been made that this is correct, you should understand any scripts you run from the internet.
Use as your own risk.