Husky is an excellent way to raise your development process

2 min read
1706

Every developer can’t even imagine life without a version control system. I’m sure that you know a bunch of them, however, at the moment, the monopolist here is git. Git Hooks is one of the grateful things which provide git. As a WordPress developer, you already know that hooks are the greatest bestowed upon us by the supermind. Most importantly, Git Hooks allow the firing of custom scripts when certain important actions occur. In other words, you can fire your own scripts on pre-commit, pre-push, prepare-commit-msg, commit-msg, post-commit, etc. hooks.

To simplify your work with the Git Hooks, you can use a library for it. I’ve chosen the Husky because of its woof and few dozen thousand stars.

The Husky library shall not pass your brilliant code to pass on the remote git repository — the great way to improve your development workflow. - WP Punk

How to install the Husky?

First of all, you should install the Husky as a package:

npm install husky --save-dev

Secondly, install the husky scripts:

npx husky install

Last but not least, add the installation script to the npm post-install event:

{
	"scripts": {
		"postinstall": "npx husky install"
	}
}

If you did all as well, then you can see the .husky directory inside your project.

Create a Git Hook via the Husky

The full git hooks list you can find inside the Git documentation.

Before we get started, let’s add a script to the package.json file that will run the coding standards checker:

{
	"scripts": {
		"cs:php": "vendor/bin/phpcs --standard=WordPress src/"
		"postinstall": "npx husky install"
	}
}

Let’s add the pre-commit hook, that will run the cs:php script.

npx husky add .husky/pre-commit "npm run cs:php"

As a result, Husky creates the .husky/pre-commit script which you can modify as you want:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run cs:php

Moreover, don’t forget to add the script to your git-repository.

How to test Git Hooks via the Husky?

In a nutshell, you should prevent the .husky/pre-commit script. The simplest way is to add the exit 1 to the .husky/pre-commit script, and all your commits should be aborted.

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run cs:php

exit 1

After that, try to commit something, the commit will be aborted, and in addition, you can see the next error:

The Husky library shall not pass your brilliant code to pass on the remote git repository — the great way to improve your development workflow. - WP Punk

In conclusion, I hope the information was helpful because it isn’t polite to the developers, and it can hurt them to end an article by displaying an error.

If the content was useful, share it on social networks

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to news. I promise not to spam :)
Follow me, don't be shy