Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aborting git pre-commit hook when var_dump present

Tags:

git

bash

githooks

I am trying (but failing miserably) to make a git pre-commit hook that checks for the presence of a var_dump in my modified files and exits if it finds one. The problem that I'm having is that it appears to always be aborting the commit. Here is the contents of my pre-commit file:

VAR=$(git diff | grep -w "var_dump")
if [ -z $VAR ]; then
  echo "You've left a var_dump in one of your files! Aborting commit..."
  exit 1
fi
like image 833
Kyle Decot Avatar asked May 31 '12 19:05

Kyle Decot


People also ask

How do I disable pre-commit hooks?

Use the --no-verify option to skip git commit hooks, e.g. git commit -m "commit message" --no-verify . When the --no-verify option is used, the pre-commit and commit-msg hooks are bypassed.

How do you force a pre-commit hook?

If you want to manually run all pre-commit hooks on a repository, run pre-commit run --all-files . To run individual hooks use pre-commit run <hook_id> . The first time pre-commit runs on a file it will automatically download, install, and run the hook.

Where are pre-commit hooks stored?

The hooks are all stored in the hooks subdirectory of the Git directory. In most projects, that's . git/hooks .

Are git hooks stored in repo?

By default, hooks are stored in . git/hooks within the project's repository. Git populates this folder with sample scripts that developers can use as a starting point.


1 Answers

First of all, note that plain git diff gives the difference between the working tree and the index (i.e. what can still be staged), not what is about to be committed. Use git diff --cached to see what is about to be committed.

The second thing I encountered as I was experimenting was that using if [ -z $VAR ] directly threw an error, because the + at the beginning of the git diff output was interpreted by Bash. Make sure to surround $VAR with quotes to prevent this.

As for the script, you forgot to negate the test if $VAR is empty. If the output from grep is empty, then "var_dump" was not found, and the hook should return success. The case you want is if it is not empty, meaning "var_dump" was found, and it should abort the commit.

All together:

VAR=$(git diff --cached | grep -w "var_dump")
if [ ! -z "$VAR" ]; then
  echo "You've left a var_dump in one of your files! Aborting commit..."
  exit 1
fi 
like image 128
vergenzt Avatar answered Sep 24 '22 13:09

vergenzt