-
-
Save henrybear327/3256835ea068c6cc64adff6fc2f4c34c to your computer and use it in GitHub Desktop.
Run a makefile command with cleanup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# cleanup.mk | |
# | |
# You can simply copy the last line of this file into your Makefile to make use of it. | |
# | |
# Optionally, you can include this file in your project, and import it using `-include cleanup.mk` | |
# | |
# Usage: | |
# $(call run-with-cleanup, my-foo-func-that-could-fail, my-cleanup-func) | |
# | |
run-with-cleanup = $(1) && $(2) || (ret=$$?; $(2) && exit $$ret) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This file includes example usage and tests for the 'run-with-cleanup' call-able function. | |
.PHONY: test test-success test-failure main cleanup | |
-include cleanup.mk | |
test: | |
test.sh | |
main: | |
echo main | |
$(if $(SHOULD_FAIL),false,true) | |
cleanup: | |
echo cleanup | |
test-success: | |
$(call run-with-cleanup, $(MAKE) main, $(MAKE) cleanup) | |
test-failure: | |
$(call run-with-cleanup, SHOULD_FAIL=1 $(MAKE) main, $(MAKE) cleanup) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env bash | |
# | |
# This file includes tests to validate the behavior of the run-with-cleanup method | |
color_green="\e[32m" | |
color_red="\e[31m" | |
color_clear="\e[0m" | |
fail() { | |
echo -e " $color_red[FAIL]$color_clear" | |
} | |
pass() { | |
echo -e " $color_green[PASS]$color_clear" | |
} | |
assert_did_print() { | |
input="$1" | |
expected="$2" | |
printf " It should print '$expected'" | |
echo "$input" | grep -q "^$expected\$" && pass || fail | |
} | |
assert_zero_exit_code() { | |
printf " It should return with exit code of zero" | |
test "$1" -eq 0 && pass || fail | |
} | |
assert_non_zero_exit_code() { | |
printf " It should return with non-zero exit code" | |
test "$1" -ne 0 && pass || fail | |
} | |
# success case | |
echo "Cleanup after success:" | |
try_success=`make test-success` | |
assert_zero_exit_code "$?" | |
assert_did_print "$try_success" "main" | |
assert_did_print "$try_success" "cleanup" | |
# failure case | |
echo "Cleanup after failure:" | |
try_failure=`make test-failure 2>/dev/null` | |
assert_non_zero_exit_code "$?" | |
assert_did_print "$try_failure" "main" | |
assert_did_print "$try_failure" "cleanup" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment