Using Git Hooks to improve your workflow

Pawan Rawal
2 min readFeb 13, 2016

--

Git is central to every project that we work on. I can’t imagine a software being developed without it. As you grow as a developer another thing that becomes very important is TDD (Test Driven Development). It gives you confidence in the program you have written and is kind of an insurance policy for your code. At Postman , we have a extensive test suite for every project, which involves infrastructure tests , unit tests, lint tests and sanity tests using Newman .

When we finish developing a feature on one of our projects, we push it to our remote repository which is integrated with a CI server , which runs all the tests and tells us whether the build passed. Ideally, just before pushing our newly written code , we should run our test script to verify that we did not break anything. Though a lot of times we forget to run our test script and only get to know that a build failed on our CI server. Fortunately this step can be automated using Git Hooks. Git provides server and client side hooks to automate a bunch of tasks that you would usually do manually. These hooks can be used to verify that your commit messages follow a certain format , your tests pass before the code is pushed and much more. The hooks are located inside .git/hooks directory. Git provides sample hook files for all projects inside this directory. For a hook to work the file has to be named appropriately and has to be executable. The file can be written as a Shell, Ruby or Python script.

For my use case I added a new file called pre-push (Note- The file does not have any extension) and made it an executable and added

npm run test

to it. We use node.js for most of our projects and have a test shell script which runs all our other test scripts in order. Thats it , adding this made sure that anytime I try to push(git push origin feature/xyz) any code to my remote repository , all my tests are run and if they fail the code is not pushed. The only issue is that every time you create a new git repository , you would have to manually copy the hooks into the new repository. There seems to be a way to have global git hook templates , but for now I am happy with this.

Try this or some other hook out if you haven’t already. If you already use them as part of your workflow , then I would be very happy to know about it.

--

--