Git hooks are scripts that we can define and which can be run when certain Git events happen. They can, for example, run tests before a commit and reject if it fails.
There are client-side hooks (run on your own computer when committing) and server-side hooks (run on server after pushing, usually used to test if merging is okay).
pre-commit hookHere we will use our previous example.py and add a git client-side hook the pre-commit hook to run a script before a
commit is recorded.
example.py fileWe are still in the directory pytest-example which
contains example.py:
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add('space', 'ship') == 'spaceship'
$ pytest example.py
$ git init
$ git add example.py
$ git commit
Save this file as pre-commit:
#!/bin/bash
pytest example.py
pre-commit executable$ chmod +x pre-commit
$ mv pre-commit .git/hooks
Now the pre-commit should reject the commit.
Discuss this approach: pros and cons.