这几天抽空看了一下git文档,发现有个hooks的好东西,在开发过程中常常不小心会把一些不想提交的文件给提交进去,也常常在提交代码后发现 文件有语法错误,这样的提交一旦上线后很可能会导致正式环境出现严重的问题。
今天就说一下 pre-commit 这个hook,它会在你执行 git commit 操作的时候触发,如果该hook返回1,那么这次的 commit 将会被终止。
hook 位于 .git/hooks/ 目录下,可以看到很多 .sample 的文件这些都是示例文件,我们自己建一个 pre-commit 文件,里面可以写shell脚本,比如我写了一个检查php语法错误和config文件不可被提交进去的脚本
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". ROOT_DIR="$(pwd)/" LIST=$(git diff-index --name-only --diff-filter=ACMR HEAD) ERRORS_BUFFER="" for file in $LIST do EXTENSION=$(echo "$file" | grep "config.php$") if [ "$EXTENSION" != "" ]; then echo "注意:有config文件要提交!如果确定要提交可用 git commit --no-verify 来忽略"; exit 1 fi EXTENSION=$(echo "$file" | grep ".php$") if [ "$EXTENSION" != "" ]; then ERRORS=$(php -l $ROOT_DIR$file 2>&1 | grep "Parse error") if [ "$ERRORS" != "" ]; then if [ "$ERRORS_BUFFER" != "" ]; then ERRORS_BUFFER="$ERRORS_BUFFERn$ERRORS" else ERRORS_BUFFER="$ERRORS" fi echo "检测到有语法错误的php文件: $file " fi fi done if [ "$ERRORS_BUFFER" != "" ]; then echo echo "Found PHP parse errors: " echo -e $ERRORS_BUFFER echo echo "PHP parse errors found. Fix errors and commit again." exit 1 else echo "No PHP parse errors found. Committed successfully." fi
大功告成,测试一下: