Get exit code from a Makefile command and use it as a variable in Git hook

654 Views Asked by At

I am currently hooking into Git's pre-push hook to run PHP CS Fixer, but I'm looking for a more less clunky way of doing it. I couldn't figure out how to pass the GNU Make command's script exit code and pass in to the Git hook script.

File setup

pre-push:

#!/bin/bash
output=$(make run-cs-fixer)
exitCode="${output##*$'\n'}" # Gets last line printed from cs-fixer.sh
# Use exitCode to continue or halt push
# Exit code from cs-fixer.sh cannot be obtained here. Make seems to produce its own exit code.

Makefile:

run-cs-fixer:
    @-cd docker-compose exec -T workspace bash ./cs-fixer.sh
    # echo $? gives me the exit code from cs-fixer.sh, but it's not available outside of this area, even if exited with it.

cs-fixer.sh:

#!/bin/bash
./vendor/bin/php-cs-fixer fix...
exitCode=$?
echo $exitCode # This is the exit code I need

So, it goes: git push... > pre-push > Makefile > cs-fixer produces exit code that needs to be available in pre-push.

As you can see, I'm printing the exit code manually from cs-fixer.sh, so that it can be extracted when the entire output of this script is captured in pre-push using output=$(make run-cs-fixer). I just couldn't figure out how to naturally pass the exist code around.

It seems like Make starts a new shell to run its command, so that seems to be one of the problems, but couldn't get .ONESHELL to work. I was able to confirm I can echo the desired exit code with the Make command instructions (below run-cs-fixer:), but that was still unavailable in pre-push.

1

There are 1 best solutions below

0
Beel On

GNU make returns the status of its work, per the man page. You cannot change the exit status of make (other than by forcing a 0, 1 or 2 as per the man page).
To do what you want, you will need to capture the output of the make command, say via echo 0 or echo $$? and use that output as the value you're looking for.