预提交中的退出1不会中止git commit吗?

时间:2015-04-30 13:30:30

标签: git githooks

如果满足某个条件,我就会中止git commit。

check if my commit has 'import pdb' in emacs/git?

#!/bin/sh

git diff --cached --no-renames --name-status --diff-filter=AM |
  while read st file; do
    case "$file" in
    *.py)
        if git show ":$file" |
          grep -E "^[^#]*\bimport[[:space:]]+pdb\b"; then
            echo "$file: has import pdb"
            exit 1
        fi;;
    esac
done

git diff --cached --name-status --diff-filter=ACM | while read st file; do
    if grep "#[[:space:]]*@test" "$file"; then
        echo "$file: has @test"
        exit 1
    fi
done

代码运行正常,我可以看到日志" ...有导入pdb" 但下一行exit 1不会中止git提交。

过去工作正常,但在某些时候停止了工作。 我是关于git 1.9.1

输出

$ GIT_TRACE=2 git commit
trace: built-in: git 'commit'
trace: run_command: '.git/hooks/pre-commit'
trace: built-in: git 'diff' '--cached' '--no-renames' '--name-status' '--diff-filter=AM'
trace: built-in: git 'show' ':momsite/apps/custom_push_notifications/utils.py'
    import pdb; pdb.set_trace()
momsite/apps/custom_push_notifications/utils.py: has import pdb
trace: built-in: git 'diff' '--cached' '--name-status' '--diff-filter=ACM'
trace: run_command: 'emacs' '/home/eugenekim/Documents/zibann/.git/COMMIT_EDITMSG'
trace: exec: 'emacs' '/home/eugenekim/Documents/zibann/.git/COMMIT_EDITMSG'

1 个答案:

答案 0 :(得分:3)

代码的第一部分读起来像

something | while ...; do ... exit 1; done

由于管道必然涉及两个进程,因此shell必须派一个子shell来执行while循环。因此,{em> subshel​​l 中存在状态为1的exit 1,并返回到您的父shell,忽略返回代码。

您想在|| exit $?关键字之后添加done,如下所示:

something | while ...; do ... exit 1; done || exit $?

请注意,这实际上不是Git问题,而是shell问题。