Stop Pushing Build Breaking Code

I'm going to show you an easy way to prevent pushing code that will break your continuous integration pipelines.

This can be achieved by simply linting and testing code, before pushing to the repository. The only problem with that is you have to remember to test and lint.

To solve the problem of forgetting, we'll set up git hooks to automatically lint and test for us. We'll use Husky for this job.

If you have a CI pipeline setup, then you probably also have a linter and testing framework, but for those who don't, you'll just have to set those up yourself.

Installation

Choose the appropriate commands for your package manager.

  1. Install Husky

     # npm
     npm install husky --save-dev
    
     # yarn
     yarn add husky --dev
    
  2. Enable Git hooks

     # npm
     npx husky install
    
     # yarn
     yarn husky install
    
  3. Auto enable Git hooks after installation Add a postinstall script to package.json

     // package.json
     {
       "scripts": {
         "postinstall": "husky install"
       }
     }
    

Add Hooks

We'll set up a pre-commit hook. This hook runs whenever git commit is used. I'm going to run yarn lint && yarn test, since that's what my application requires, but you can replace this with any command you want.

npx husky add .husky/pre-commit "yarn lint && yarn test"

You can find the hook located at .husky/pre-commit, and edit the command from there.

If you'd like to try some other hooks, check this list of hooks.

Testing

Now, let's try to make a commit that fails. If you have a linter, you could update one of your files with some lint. That should cause the linter to fail.

Run through your normal procedure for making a commit.

git status
git add .
git commit -m 'testing - this should fail'

Hopefully, the commit didn't work.

Now, let's try to actually get the commit to work correctly. Remove any lint, update your tests, or whatever you need to do to get your application back to a working state. Go back through the commit process.

git status
git add .
git commit -m 'add a pre-commit hook'

Conclusion

You no longer have to worry about pushing code with failing tests, or lint, because you can't even make a commit unless everything is good.

Resources

No Comments Yet