Search code examples
gitbashgulpgit-bash

Return failure code from pre-commit GIT Hook if test fails


I have a gulp task test which uses mocha to run my unit tests.

I want to run the unit tests as part of a GIT pre-commit hook.

So basically my pre-commit file looks like this:

#!/bin/bash
gulp test

The problem I have is that even if a test fails, the commit is made. How can I detect a test failure from my pre-commit file?


Solution

  • The exit code of a Bash script is the exit code of the last command executed. If gulp test fails, it exits with non-zero, which means failure, and the commit should get aborted.

    Are you sure the hook script gets executed?

    • The script must be at .git/hooks/pre-commit
    • The script must be executable

    Assuming these conditions are met, the script as posted should work as expected. If it doesn't, then modify it to help debugging and post the output of an example commit that you expect to fail.

    #!/bin/bash
    
    gulp test
    
    x=$?
    echo exit code = $x
    exit $x