source

Git hooks — The unsung rescuers

What a git hook can do is constrained only by the developer’s imagination. Git hooks are one of the most productive hacks every software engineering team must possess.

First things first:

The need:

“oh! the pull request build failed because of failing unit tests or integration tests”.

“Ahh !! damn I have push the data base password into git.”

On a sincere note, committing passwords into git is a crime that a developer can potentially do unknowingly. I once read about a situation where a developer has committed the passwords of AWS instance which were eventually taken over by a hacker and whole AWS was compromised for the organization and used to mine cryptocurrency for 24hrs. We can stop this using a pre-commit git hook.

To fix the above scenarios developers have to revert that commit or push a new commit with fixed test suite or by removing the password that is pushed. This eventually disturbs the commit history of the application.And yes, there is a difference between a developer and a good developer. We can be good developers. We can handle these types of common mistakes even before we commit the code into our local machines.

Dive in:

A pre-commit hook script will be executed every time you commit the code in to the local machine where as a pre-push hook script will be executed every time you push the code to git.

Pre-commit hook to detect passwords in staged files:

<script src=”https://gist.github.com/akhil-ghatiki/944db313e1fafa66d11c3f189b15eb1e.js"></script>

We are using a regex here to detect any line of the type password:<<text>> in the staged files. (One needs to change this regex according to how passwords go into your code.)

Pre-commit hook to abort commit for failing unit tests:

<script src=”https://gist.github.com/akhil-ghatiki/6ec1e96ec289ff37d861fed823afd560.js"></script>
Of course, both the above implementations can go into one pre-commit git hook. Save the above file as pre-commit.sh

Pre-push hook to abort pushing for failing integration tests:

<script src=”https://gist.github.com/akhil-ghatiki/16ac55b276d6fb42d3f563db6a235dea.js"></script>
Save the above file as pre-push.sh

Save these files in a folder “githooks” and run the below commands. So that any further changes can be made in these files and they will reflect in the git’s hooks.

ln -s -f /Users/<<Path to your project folder>>/githooks/pre-commit ./.git/hooks/pre-commitln -s -f /Users/<<Path to your project folder>>/githooks/pre-push ./.git/hooks/pre-push

God Speed !!!!

Developer at ThoughtWorks. Sometimes ENTP-T and sometimes ESTP-A not sure which one.Loves to talk about tech, code, data privacy, environment.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store