Writing Custom Git Hooks With NodeJS

Shahar Kazaz
ITNEXT
Published in
3 min readJan 17, 2020

--

Originally posted in DEV.to.

Git hooks are a useful tool, especially when working in large teams.
They can help us apply code style and linting standards to our staged files.

In the article, we’ll write a few powerful Javascript git hooks that will help us manage our codebase and have a smoother developing experience.

Running The Script

We are going to run our hooks with the help of Husky 🐶.
After we installed Husky the next thing we need to do is run our node script.
Let’s add our script to the package.json scripts section, and use husky to call it:

scripts: {  
...
"hooks:pre-commit": "node ./hooks/pre-commit.js",
"hooks:pre-push": "node ./hooks/pre-push.js"
},
...
husky: {
"pre-commit": "npm run hooks:pre-commit",
"pre-push": "npm run hooks:pre-push"
},

That’s pretty much it, now let’s see some useful implementations of
pre-commit and pre-push hooks.

Exec.js

I created an exec.js helper function for my hooks scripts, that wraps shelljs‘s exec function.
The exec function spawns a shell then executes a given command within that shell:

Pre-Commit 📦

1. Branch Names Convention

Allow to create only branches that have one of the following prefixes: feature|fix|hotfix|chore|tests|automation

2. Forbidden Tokens ✋

Who hasn’t forgotten to remove a debugger? or an fdescribe in a test? no more!

Pre-Push 🚀

1. Auto Sync Master

We noticed that developers often forget to update their branches regularly from the remote.

This is a simple but important hook that updates your local branch from the remote master.

2. Forbidden Branches ✋

There are brunches that we don’t want their commits ending up in master
such as astagingbranch.

We’ll make a commit in these branches that will act as a “flag” 🚩.
Before pushing to the remote we will verify that this commit isn’t part of the branch being pushed (we will obviously remove this code in the staging branch).

Takeaways

We saw some useful examples for using git hooks, and how easy you can use Husky and NodeJS to apply policies and prevent bad commits.

Now you can customize these hooks in the best way that suits your project 🥳

Have You Tried Transloco Yet? 🌐

ng-neat introduces Transloco, the internationalization (i18n) library for Angular. It allows you to define translations for your content in different languages and switch between them easily in runtime.

It exposes a rich API to manage translations efficiently and cleanly. It provides multiple plugins that will improve your development experience.
We/I highly recommend you read more about it and check it out!

--

--

I’m a Frontend Architect who is passionate about coding & web development.