GIT — add some validations before commit
Hi Folks,
let’s keep this short and sweet, you came to this page / post for one thing:
how to add validations/checks before committing your code to your branch ?
well, there’s a couple of options and I won’t list them all. The purpose of this post is to show you how we can write the script ourselves instead of relying on some library to do the job for us.
First thing first, you should know how git hooks work (here’s a starting point).
now, if your goal is to run e.g unit tests, lint, format checks, then you probably want to run these right before commiting to your branch. That way, you’re sure your branch is always clean, buildable and deployable even with unfinished job. In this case, you should go to your root repo and cd .git/hooks
then find a file named pre-commit.sample
and rename this file pre-commit
. Then reinitialize your git repo: git init
(make sure that you’re back on your root git repo.
Now we can start writing some bash script :)
here’s the final script for those who are in a hurry:
Now, for those who are interested to understand what the script does. it’s quite simple:
1- Position yourself in the right folder (where your package.json is)
2- Stash everything that is not staged (code in progress but not ready to be committed)
3- Run unit tests across all apps (if it fails, it will stop right there with a message)
4- Run lint (checking eslint rules, you’ll get a message if it fails)
5- Run format check (not mandatory, it depends on team/project rules)
6- bringing back stashed changes.
as you can see, it’s a very simple script, straight-forward, checking each step if there’s any error.
I hope this small piece of information/code helped you and if it did, please 👏 or leave a comment for any question or remark