Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-Commit Hook Unit Test

I am trying to run a pre-commit hook that prevents me from committing if my unit tests don't run. Right now I have a shell script that runs the tests and my terminal tells me that they have failed, which is good. But I am not sure what to put in my Shell Script to actually stop my commit once my terminal detects that I have failing tests. Like this: enter image description here

I am inclined to think that all I am missing is a simple if statement which checks if the tests fail then stop the commit and if the tests pass then complete the commit. But I could be completely wrong about that, and this is my first time working with shell scripts so I am not really sure how to go about doing that. Thanks.

like image 847
benjamin852 Avatar asked Oct 26 '25 18:10

benjamin852


1 Answers

You need to make sure your script exits with a non-zero exit code when the tests fail.

From the Git docs:

Exiting with a non-zero status from this script causes the git commit command to abort before creating a commit.

https://git-scm.com/docs/githooks

Basically, do exit 1 if the tests fail and exit 0 otherwise. Right now, you're probably doing exit 0 (or just letting the script end) in all cases.

Most likely, your unit tests are already returning a valid exit code, which you can use to determine the exit code for your script.

A simple way to do this is something like:

<run unit tests>
EXIT_CODE=$?
...
exit EXIT_CODE
like image 162
mkasberg Avatar answered Oct 29 '25 09:10

mkasberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!