[ACCEPTED]-Commit in git only if tests pass-githooks

Accepted answer
Score: 33

I would check to make sure that each step 21 of the way, your script returns a non-zero 20 exit code on failure. Check to see if your 19 python3.1 foo.py --test returns a non-zero exit code if a test 18 fails. Check to make sure your make test command 17 returns a non-zero exit code. And finally, check 16 that your pre-commit hook itself returns a non-zero 15 exit code on failure.

You can check for a 14 non-zero exit code by adding || echo $? to the end 13 of a command; that will print out the exit 12 code if the command failed.

The following 11 example works for me (I'm redirecting stderr 10 to /dev/null to avoid including too much extraneous 9 output here):

$ python3.1 test.py 2>/dev/null || echo $?
1
$ make test 2>/dev/null || echo $?
python3.1 test.py
2
$ .git/hooks/pre-commit 2>/dev/null || echo $?
python3.1 test.py
1

test.py:

import unittest

class TestFailure(unittest.TestCase):
    def testFail(self):
        assert(False)

if __name__ == '__main__':
    unittest.main()

Makefile:

test:
    python3.1 test.py

.git/hooks/pre-commit:

#!/bin/sh
make test || exit 1

Note the || exit 1. This isn't necessary 8 if make test is the last command in the hook, as 7 the exit status of the last command will 6 be the exit status of the script. But if 5 you have later checks in your pre-commit hook, then 4 you need to make sure you exit with an error; otherwise, a 3 successful command at the end of the hook 2 will cause your script to exit with a status 1 of 0.

Score: 6

Could you parse the result of the python 13 test session and make sure to exit your 12 pre-commit hook with a non-zero status?

The 11 hook should exit with non-zero status after 10 issuing an appropriate message if it wants 9 to stop the commit.

So if your python script 8 does not return the appropriate status for 7 any reason, you need to determine that status 6 directly from the pre-commit hook script.
That would 5 ensure the commit does not go forward if 4 the tests failed.
(or you could call from 3 the hook a python wrapper which would call 2 the tests, and ensure a sys.exit(exit_status) according to the 1 test results).

Score: 0

Another option, if you don't want to handle 3 manually pre-commit's: There is nice tool 2 to run tests and syntax checks for Python, Ruby 1 and so on: github/overcommit

More Related questions