Working together as a team and maintaining a clean codebase is becoming increasingly important. Therefore most companies create and use certain rulesets which have to be followed by everyone in the team.
To avoid unnecessary code review time spent to check simple rules we have agreed on, we can leave the work to detect issues and even fix them to software.
It is no surprise that tools like eslint for linting and prettier for formatting are at a weekly download count of whacking 45 million downloads per week (numbers at the time of writing this post, taken from npmjs-prettier and npmjs-eslint).
While many people (yup, me as well) include them in their IDE, there are also people that don't. One way to ensure a formatted and linted code is to tell them to make sure that they run something like
./node_modules/.bin/prettier --write .
for formatting and
./node_modules/.bin/eslint . -c .eslintrc.js --ext .js,.ts,.vue
Since we are all humans and make countless mistakes each day, sometimes people forget to do this before pushing their code. Which would end up in bad code or wasted developer time in the code reviews...
git hooks to the rescue
To fix this issue, we use git hooks (which are just simple shell scripts) which will run these commands/tools on certain git actions (commit/push/pre-push/etc..).
We will set up our git repo with hooks now. Our goal is to:
- Run prettier before every commit
- Run eslint before every push.
- Stop the current action when we receive an error inside our hooks.
- To determine when the git hook will be run, it simply has to be named like the git action.
- Want to run something before a commit? Create the shellscript pre-commit.
- Before a push..? Exactly, pre-push.
NOTE: In the following code $? is used to determine the return code of the last executed command. For us this will be prettier and eslint respectively.
These have to be stored inside the .git/hooks directory in your project root. After doing this your hooks folder should look like this:
Lets imagine we did create this piece of code:
And then we want to include it into our code base. We run
git add .
then try commiting with
git commit -m "create awesome index.js file"