aborting git pre-commit hook when var_dump present

十年热恋 提交于 2019-12-06 03:15:44

问题


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

回答1:


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 


来源:https://stackoverflow.com/questions/10840196/aborting-git-pre-commit-hook-when-var-dump-present

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!