Using Git Hooks

If you'd like to try out Spectral quickly, and get maximum value quickly, you can try wiring it to a git hook.

πŸ¦Έβ€β™€οΈ
What is a git hook?
Git hooks plug into a Git repo's lifecycle. For example, if you commit a change and put Spectal as a pre-commit, it will reject it if it finds sensitive data that's about to be committed.

Live examples πŸš€

Adding a simple hook

If your repo has no hooks, and maybe you're just starting out with hooks, you can start simple:

$ cd your-repo
$ echo 'spectral run' > .git/hooks/pre-commit

This assumes you have Spectral installed globally for the user.

From now on every time you want to perform a commit, Spectral will run and watch your back.

To remove the hook simply delete the file:

$ rm .git/hooks/pre-commit

A few observations:

  1. This is a set up that's made locally on your repo on your disk, there's no way to enforce that on the central server-hosted repo or on other computers (but more on this later)
  2. In the way we did this now, you can only have just one hook run at a time -- more on this in the next section

Making sure everyone run hooks 🀝

In this section we'll take care of the two observations:

  1. How do I run more than one hook (called hook multiplexing)?
  2. How to make sure my team mates and any new developer is always using the same set of hooks and, in general, always using your hooks?

Integrating Spectral and Husky

There are two solutions here, one is you pick a hook manager for your own language. A popular one for Node.js for example, is Husky; in fact it's so great that I'd use it even if you're not looking at a Node.js or Javascript project.

Here's how to integrate Spectral:

$ yarn init
$ yarn add --dev husky

Now edit your package.json and add the following section:

"husky": {
"hooks": {
"pre-commit": "spectral run"
}
}

Spectral and Other Hooks Managers

If you prefer using a manager that doesn't tie to any programming language, or you prefer using a manager that's specific to your programming language, take a look at this website and pick a hooks manager that you feel comfortable with.

Integrating Spectral with any hook manager is as simple as the above Husky integration.