Adding a pre-commit hook to make sure the important data do not get leaked.

One of the biggest mistakes by a human being is to expose credentials/important data unknowingly. To avoid that we should be looking for some solution. So in this blog, I am going to share the solution to avoid such mistakes. we can commit other changes we want, without any issues.

What is the solution?

Pre-commit hook is the solution to avoid leaking credential files unknowingly. Hooks are simple codes, which are attached to certain events like commit, push, etc. So, that each time when an event occurs, then that particular hook is going to run and do its job.

A Pre-commit hook, it’s a hook that is going to run before every commit into the git. It can be used for various purposes like to verify the username, verify changes in any file, etc.

In this blog, we will be looking into how we can avoid the changes into any file by applying a pre-commit hook. Also here the changes to other files can be committed without any issue. Adding –no-verify to commit message can bypass this hook.

Setup for Pre-commit hook:

Let us have a look at how to set up a pre-commit hook. Below are the steps, need to follow for setting up a pre-commit hook to avoid changes into any specified file at the time of commit.

1. First make the Visual Studio Code settings for accessing hidden .git files within Visual Studio Code.

– Go to File->Preferences-> Settings & search for file.exclude
– You just need to set “**/.git” as { “**/.git” : false} and you are good to go

Visual Code Studio settings

2. Browse inside .git/hooks & find there pre-commit.sample code.

3. Select all the code and comment out the same. Copy the given code and paste it into the file. Also, make sure to change the file names, you don’t want to commit with a path in the file and rename the file as ‘pre-commit’, removing ‘.sample’ extension.

4. From Gitbash, make the file executable from the current working directory.

 chmod +x pre-commit

5. Now make the changes to the file added to pre-commit which you do not want to commit.

6. Commit the changes with that file. Tada!! you will not be allowed to do the commit.


# full paths from the repo root separated by newlines
if git rev-parse --verify HEAD >/dev/null 2>&1
    # Initial commit: diff against an empty tree object
exec 1>&2
if git diff --cached --name-only $against |
grep --quiet --line-regexp --fixed-strings "$MUST_NOT_CHANGE"
    echo Commit would modify one or more files that must not change, Please verify the changes.
    exit 1
    exit 0
Commits before applying pre-commit hook
Commits after applying pre-commit hook
Commit with no-verify Option

I hope this blog is helpful for you. Happy Testing!!

Leave a Reply

Your email address will not be published.