|
|
|
---
|
|
|
|
title: "Git Tips - Global Pre-commit Hooks"
|
|
|
|
date: 2020-01-01T21:00:39Z
|
|
|
|
tags: [git, testing, bash]
|
|
|
|
---
|
|
|
|
|
|
|
|
[Git hooks][1] are a feature of the Git VCS that allow you to fire off custom logic on the client side when you take
|
|
|
|
actions in your repository. These are shell scripts in the `.git/hooks/` directory of your repository, but they can also
|
|
|
|
exist in your home directory at `~/.githooks/`.
|
|
|
|
|
|
|
|
Any hooks found in `~/.githooks/` are executed globally, this makes it easy to setup a custom workflow that is consistent
|
|
|
|
across your entire machine.
|
|
|
|
|
|
|
|
## Automatically lint and test on commit
|
|
|
|
|
|
|
|
One of my favorite hooks is the `~/.githooks/pre-commit` hook that auto runs test and lint commands from a `makefile` or
|
|
|
|
`package.json` if they're found:
|
|
|
|
|
|
|
|
```sh
|
|
|
|
{{<highlight bash "linenos=table">}}
|
|
|
|
#!/usr/bin/env bash
|
|
|
|
|
|
|
|
if [ -f "$PWD/makefile" ] && [ ! -z "$(cat $PWD/makefile | grep '^lint:')" ]; then
|
|
|
|
echo "running make lint"
|
|
|
|
make lint
|
|
|
|
elif [ -f "$PWD/package.json" ] && [ ! -z "$(cat $PWD/package.json | grep "^\"lint\":")" ]; then
|
|
|
|
echo "running npm run lint"
|
|
|
|
npm run lint
|
|
|
|
fi
|
|
|
|
|
|
|
|
if [ -f "$PWD/makefile" ] && [ ! -z "$(cat $PWD/makefile | grep '^test:')" ]; then
|
|
|
|
echo "running make test"
|
|
|
|
make test
|
|
|
|
elif [ -f "$PWD/package.json" ] && [ ! -z "$(cat $PWD/package.json | grep "^\"test\":")" ]; then
|
|
|
|
echo "running npm run test"
|
|
|
|
npm run test
|
|
|
|
fi
|
|
|
|
{{</highlight>}}
|
|
|
|
```
|
|
|
|
|
|
|
|
The `/usr/bin/env bash` piece ensures that the script has access to all of the environment variables you expect in your
|
|
|
|
regular shell.
|
|
|
|
|
|
|
|
If the test or lint command fails then the `git commit` command fails. If I absolutely need to commit something in spite
|
|
|
|
of the lint/test results I can do `git commit --no-verify` to skip the `pre-commit` hook.
|
|
|
|
|
|
|
|
[1]: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks "Git hooks"
|